blob: 5530143370102a26d696ad102b6daaec1193ec18 [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;
Wenchao Tongf5ea3402015-03-04 13:26:38 -080034import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080035import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090049import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070051import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070052import android.net.INetworkPolicyListener;
53import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070054import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080055import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070056import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070057import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070058import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070059import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070060import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070062import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070063import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070064import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070065import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070066import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070067import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070068import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040069import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070070import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040071import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040072import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090073import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090074import android.net.metrics.NetworkEvent;
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);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700733 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
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) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800823 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600824 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
825 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800826 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600827 state = nai.getNetworkState();
828 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800829 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600830 final NetworkInfo info = new NetworkInfo(networkType, 0,
831 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800832 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
833 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600834 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
835 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800836 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600837 filterNetworkStateForUid(state, uid);
838 return state;
839 } else {
840 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400842 }
843
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800844 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
845 if (network == null) {
846 return null;
847 }
848 synchronized (mNetworkForNetId) {
849 return mNetworkForNetId.get(network.netId);
850 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600851 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800852
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900853 private Network[] getVpnUnderlyingNetworks(int uid) {
854 if (!mLockdownEnabled) {
855 int user = UserHandle.getUserId(uid);
856 synchronized (mVpns) {
857 Vpn vpn = mVpns.get(user);
858 if (vpn != null && vpn.appliesToUid(uid)) {
859 return vpn.getUnderlyingNetworks();
860 }
861 }
862 }
863 return null;
864 }
865
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800866 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400867 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800868
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900869 final Network[] networks = getVpnUnderlyingNetworks(uid);
870 if (networks != null) {
871 // getUnderlyingNetworks() returns:
872 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
873 // empty array => the VPN explicitly said "no default network".
874 // non-empty array => the VPN specified one or more default networks; we use the
875 // first one.
876 if (networks.length > 0) {
877 nai = getNetworkAgentInfoForNetwork(networks[0]);
878 } else {
879 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800880 }
881 }
882
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800883 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600884 return nai.getNetworkState();
885 } else {
886 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800887 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400888 }
889
890 /**
891 * Check if UID should be blocked from using the network with the given LinkProperties.
892 */
893 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700894 final boolean networkCostly;
895 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700896
Robert Greenwalt12e67352014-05-13 21:41:06 -0700897 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700898 synchronized (mRulesLock) {
899 networkCostly = mMeteredIfaces.contains(iface);
900 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700901 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700902
Jeff Sharkeydc988062015-09-14 10:09:47 -0700903 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700904 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700905 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
906 return true;
907 } else {
908 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700909 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700910 }
911
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900912 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
913 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
914 boolean removed = false;
915 boolean added = false;
916 synchronized (mBlockedAppUids) {
917 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
918 added = true;
919 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
920 removed = true;
921 }
922 }
923 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
924 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
925 }
926
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700927 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600928 * Apply any relevant filters to {@link NetworkState} for the given UID. For
929 * example, this may mark the network as {@link DetailedState#BLOCKED} based
930 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
931 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700932 */
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600933 private void filterNetworkStateForUid(NetworkState state, int uid) {
934 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
935
936 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
937 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700938 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600939 if (mLockdownTracker != null) {
940 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700941 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600942
943 // TODO: apply metered state closer to NetworkAgentInfo
944 final long token = Binder.clearCallingIdentity();
945 try {
946 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
947 } catch (RemoteException e) {
948 } finally {
949 Binder.restoreCallingIdentity(token);
950 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700951 }
952
953 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 * Return NetworkInfo for the active (i.e., connected) network interface.
955 * It is assumed that at most one network is active at a time. If more
956 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700957 * @return the info for the active network, or {@code null} if none is
958 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800959 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700960 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800961 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700962 enforceAccessPermission();
963 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600964 final NetworkState state = getUnfilteredActiveNetworkState(uid);
965 filterNetworkStateForUid(state, uid);
966 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
967 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800968 }
969
Paul Jensen31a94f42015-02-13 14:18:39 -0500970 @Override
971 public Network getActiveNetwork() {
972 enforceAccessPermission();
Robin Leed2baf792016-03-24 12:07:00 +0000973 return getActiveNetworkForUidInternal(Binder.getCallingUid());
974 }
975
976 @Override
977 public Network getActiveNetworkForUid(int uid) {
978 enforceConnectivityInternalPermission();
979 return getActiveNetworkForUidInternal(uid);
980 }
981
982 private Network getActiveNetworkForUidInternal(final int uid) {
Paul Jensen31a94f42015-02-13 14:18:39 -0500983 final int user = UserHandle.getUserId(uid);
984 int vpnNetId = NETID_UNSET;
985 synchronized (mVpns) {
986 final Vpn vpn = mVpns.get(user);
987 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
988 }
989 NetworkAgentInfo nai;
990 if (vpnNetId != NETID_UNSET) {
991 synchronized (mNetworkForNetId) {
992 nai = mNetworkForNetId.get(vpnNetId);
993 }
994 if (nai != null) return nai.network;
995 }
996 nai = getDefaultNetwork();
997 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
998 return nai != null ? nai.network : null;
999 }
1000
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001001 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1002 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001003 final int uid = Binder.getCallingUid();
1004 NetworkState state = getUnfilteredActiveNetworkState(uid);
1005 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001006 }
1007
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001008 @Override
1009 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1010 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001011 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1012 filterNetworkStateForUid(state, uid);
1013 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001014 }
1015
1016 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001017 public NetworkInfo getNetworkInfo(int networkType) {
1018 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001020 if (getVpnUnderlyingNetworks(uid) != null) {
1021 // A VPN is active, so we may need to return one of its underlying networks. This
1022 // information is not available in LegacyTypeTracker, so we have to get it from
1023 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001024 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001025 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001026 filterNetworkStateForUid(state, uid);
1027 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001028 }
1029 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001030 final NetworkState state = getFilteredNetworkState(networkType, uid);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001031 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 }
1033
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001034 @Override
1035 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1036 enforceAccessPermission();
1037 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001038 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001039 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001040 final NetworkState state = nai.getNetworkState();
1041 filterNetworkStateForUid(state, uid);
1042 return state.networkInfo;
1043 } else {
1044 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001045 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001046 }
1047
1048 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 public NetworkInfo[] getAllNetworkInfo() {
1050 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001051 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001052 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1053 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001054 NetworkInfo info = getNetworkInfo(networkType);
1055 if (info != null) {
1056 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001059 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 }
1061
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001062 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001063 public Network getNetworkForType(int networkType) {
1064 enforceAccessPermission();
1065 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001066 NetworkState state = getFilteredNetworkState(networkType, uid);
1067 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1068 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001069 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001070 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001071 }
1072
1073 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001074 public Network[] getAllNetworks() {
1075 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001076 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001077 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001078 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001079 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001080 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001081 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001082 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001083 }
1084
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001085 @Override
1086 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1087 // The basic principle is: if an app's traffic could possibly go over a
1088 // network, without the app doing anything multinetwork-specific,
1089 // (hence, by "default"), then include that network's capabilities in
1090 // the array.
1091 //
1092 // In the normal case, app traffic only goes over the system's default
1093 // network connection, so that's the only network returned.
1094 //
1095 // With a VPN in force, some app traffic may go into the VPN, and thus
1096 // over whatever underlying networks the VPN specifies, while other app
1097 // traffic may go over the system default network (e.g.: a split-tunnel
1098 // VPN, or an app disallowed by the VPN), so the set of networks
1099 // returned includes the VPN's underlying networks and the system
1100 // default.
1101 enforceAccessPermission();
1102
1103 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1104
1105 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001106 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001107 if (nc != null) {
1108 result.put(nai.network, nc);
1109 }
1110
1111 if (!mLockdownEnabled) {
1112 synchronized (mVpns) {
1113 Vpn vpn = mVpns.get(userId);
1114 if (vpn != null) {
1115 Network[] networks = vpn.getUnderlyingNetworks();
1116 if (networks != null) {
1117 for (Network network : networks) {
1118 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001119 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001120 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001121 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001122 }
1123 }
1124 }
1125 }
1126 }
1127 }
1128
1129 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1130 out = result.values().toArray(out);
1131 return out;
1132 }
1133
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001134 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001135 public boolean isNetworkSupported(int networkType) {
1136 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001137 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001138 }
1139
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001140 /**
1141 * Return LinkProperties for the active (i.e., connected) default
1142 * network interface. It is assumed that at most one default network
1143 * is active at a time. If more than one is active, it is indeterminate
1144 * which will be returned.
1145 * @return the ip properties for the active network, or {@code null} if
1146 * none is active
1147 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001149 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001150 enforceAccessPermission();
1151 final int uid = Binder.getCallingUid();
1152 NetworkState state = getUnfilteredActiveNetworkState(uid);
1153 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001154 }
1155
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001156 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001157 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001158 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001159 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1160 if (nai != null) {
1161 synchronized (nai) {
1162 return new LinkProperties(nai.linkProperties);
1163 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001164 }
1165 return null;
1166 }
1167
Robert Greenwalt12e67352014-05-13 21:41:06 -07001168 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001169 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001170 public LinkProperties getLinkProperties(Network network) {
1171 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001173 if (nai != null) {
1174 synchronized (nai) {
1175 return new LinkProperties(nai.linkProperties);
1176 }
1177 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001178 return null;
1179 }
1180
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001181 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001182 if (nai != null) {
1183 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001184 if (nai.networkCapabilities != null) {
1185 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001186 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 }
1188 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001189 return null;
1190 }
1191
1192 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001193 public NetworkCapabilities getNetworkCapabilities(Network network) {
1194 enforceAccessPermission();
1195 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1196 }
1197
1198 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001200 // Require internal since we're handing out IMSI details
1201 enforceConnectivityInternalPermission();
1202
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001203 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001204 for (Network network : getAllNetworks()) {
1205 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1206 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001207 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001208 }
1209 }
1210 return result.toArray(new NetworkState[result.size()]);
1211 }
1212
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001213 @Override
1214 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1215 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001216 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001217 final long token = Binder.clearCallingIdentity();
1218 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001219 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1220 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001221 try {
1222 return mPolicyManager.getNetworkQuotaInfo(state);
1223 } catch (RemoteException e) {
1224 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001225 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001226 return null;
1227 } finally {
1228 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001229 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001230 }
1231
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001232 @Override
1233 public boolean isActiveNetworkMetered() {
1234 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001235
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001236 final NetworkInfo info = getActiveNetworkInfo();
1237 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001238 }
1239
Jeff Sharkey216c1812012-08-05 14:29:23 -07001240 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1241 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001242 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001243 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001244 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001245 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001246 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001247
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001248 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 * Ensure that a network route exists to deliver traffic to the specified
1250 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001251 * @param networkType the type of the network over which traffic to the
1252 * specified host is to be routed
1253 * @param hostAddress the IP address of the host to which the route is
1254 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001255 * @return {@code true} on success, {@code false} on failure
1256 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001257 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001259 if (mProtectedNetworks.contains(networkType)) {
1260 enforceConnectivityInternalPermission();
1261 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001262
Chad Brubakerc0234532014-02-14 13:24:29 -08001263 InetAddress addr;
1264 try {
1265 addr = InetAddress.getByAddress(hostAddress);
1266 } catch (UnknownHostException e) {
1267 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1268 return false;
1269 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001270
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001272 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001273 return false;
1274 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001275
1276 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1277 if (nai == null) {
1278 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1279 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1280 } else {
1281 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1282 }
1283 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001284 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001285
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001286 DetailedState netState;
1287 synchronized (nai) {
1288 netState = nai.networkInfo.getDetailedState();
1289 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001290
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001291 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001292 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001293 log("requestRouteToHostAddress on down network "
1294 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001295 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001296 }
1297 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001298 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001299
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001300 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001301 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001302 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001303 LinkProperties lp;
1304 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001305 synchronized (nai) {
1306 lp = nai.linkProperties;
1307 netId = nai.network.netId;
1308 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001309 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001310 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1311 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001312 } finally {
1313 Binder.restoreCallingIdentity(token);
1314 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001315 }
1316
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001317 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001318 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001319 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001320 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001321 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001322 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001323 if (bestRoute.getGateway().equals(addr)) {
1324 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001325 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001326 } else {
1327 // if we will connect to this through another route, add a direct route
1328 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001329 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001330 }
1331 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001332 if (DBG) log("Adding legacy route " + bestRoute +
1333 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001334 try {
1335 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1336 } catch (Exception e) {
1337 // never crash - catch them all
1338 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001339 return false;
1340 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001341 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001342 }
1343
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001344 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1345 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001346 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001347 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001348 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001349 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001350 }
1351
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001352 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001353 // skip update when we've already applied rules
1354 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1355 if (oldRules == uidRules) return;
1356
1357 mUidRules.put(uid, uidRules);
1358 }
1359
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 // TODO: notify UID when it has requested targeted updates
1361 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001362
1363 @Override
1364 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001365 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001366 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001367 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001368 }
1369
1370 synchronized (mRulesLock) {
1371 mMeteredIfaces.clear();
1372 for (String iface : meteredIfaces) {
1373 mMeteredIfaces.add(iface);
1374 }
1375 }
1376 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001377
1378 @Override
1379 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1380 // caller is NPMS, since we only register with them
1381 if (LOGD_RULES) {
1382 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1383 }
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001384 if (restrictBackground) {
1385 log("onRestrictBackgroundChanged(true): disabling tethering");
1386 mTethering.untetherAll();
1387 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001388 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001389
1390 @Override
1391 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1392 if (LOGD_RULES) {
1393 // caller is NPMS, since we only register with them
1394 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1395 + whitelisted + ")");
1396 }
1397 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001398 };
1399
Robin Lee3b3dd942015-05-12 18:14:58 +01001400 /**
1401 * Require that the caller is either in the same user or has appropriate permission to interact
1402 * across users.
1403 *
1404 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1405 */
1406 private void enforceCrossUserPermission(int userId) {
1407 if (userId == UserHandle.getCallingUserId()) {
1408 // Not a cross-user call.
1409 return;
1410 }
1411 mContext.enforceCallingOrSelfPermission(
1412 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1413 "ConnectivityService");
1414 }
1415
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001416 private void enforceInternetPermission() {
1417 mContext.enforceCallingOrSelfPermission(
1418 android.Manifest.permission.INTERNET,
1419 "ConnectivityService");
1420 }
1421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001423 mContext.enforceCallingOrSelfPermission(
1424 android.Manifest.permission.ACCESS_NETWORK_STATE,
1425 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 }
1427
1428 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001429 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001430 }
1431
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001432 private void enforceTetherAccessPermission() {
1433 mContext.enforceCallingOrSelfPermission(
1434 android.Manifest.permission.ACCESS_NETWORK_STATE,
1435 "ConnectivityService");
1436 }
1437
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001438 private void enforceConnectivityInternalPermission() {
1439 mContext.enforceCallingOrSelfPermission(
1440 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1441 "ConnectivityService");
1442 }
1443
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001444 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001445 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001446 }
1447
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001448 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001449 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001450 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001451 }
1452
1453 private void sendInetConditionBroadcast(NetworkInfo info) {
1454 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1455 }
1456
Wink Saville628b0852011-08-04 15:01:58 -07001457 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001458 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001459 info = new NetworkInfo(info);
1460 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001461 }
1462
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001463 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001464 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001465 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 if (info.isFailover()) {
1467 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1468 info.setFailover(false);
1469 }
1470 if (info.getReason() != null) {
1471 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1472 }
1473 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001474 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1475 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001477 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001478 return intent;
1479 }
1480
1481 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1482 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1483 }
1484
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001485 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001486 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1487 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1488 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001489 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001490 final long ident = Binder.clearCallingIdentity();
1491 try {
1492 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1493 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1494 } finally {
1495 Binder.restoreCallingIdentity(ident);
1496 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001497 }
1498
Mike Lockwood0f79b542009-08-14 14:18:49 -04001499 private void sendStickyBroadcast(Intent intent) {
1500 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001501 if (!mSystemReady) {
1502 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001503 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001504 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001505 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001506 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001507 }
1508
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001509 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001510 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001511 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001512 final NetworkInfo ni = intent.getParcelableExtra(
1513 ConnectivityManager.EXTRA_NETWORK_INFO);
1514 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1515 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1516 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001517 } else {
1518 BroadcastOptions opts = BroadcastOptions.makeBasic();
1519 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1520 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001521 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001522 final IBatteryStats bs = BatteryStatsService.getService();
1523 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001524 bs.noteConnectivityChanged(intent.getIntExtra(
1525 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1526 ni != null ? ni.getState().toString() : "?");
1527 } catch (RemoteException e) {
1528 }
1529 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001530 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001531 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001532 } finally {
1533 Binder.restoreCallingIdentity(ident);
1534 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001535 }
1536 }
1537
1538 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001539 loadGlobalProxy();
1540
Mike Lockwood0f79b542009-08-14 14:18:49 -04001541 synchronized(this) {
1542 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001543 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001544 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001545 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001546 }
1547 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001548 // load the global proxy at startup
1549 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001550
Robin Lee244ce8e2016-01-05 18:03:46 +00001551 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1552 // for user to unlock device too.
1553 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001554
Erik Klineda4bfa82015-04-30 12:58:40 +09001555 // Configure whether mobile data is always on.
1556 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1557
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001558 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001559
1560 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001561 }
1562
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001564 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001565 *
1566 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001567 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001568 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001569 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1570 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001571
1572 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001573 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001574
Robert Greenwalt7b816022014-04-18 15:25:25 -07001575 if (networkAgent.networkCapabilities.hasTransport(
1576 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001577 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1578 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001579 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001580 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001581 } else if (networkAgent.networkCapabilities.hasTransport(
1582 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001583 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1584 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001585 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001586 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001587 } else {
1588 // do not track any other networks
1589 timeout = 0;
1590 }
1591
Robert Greenwalt7b816022014-04-18 15:25:25 -07001592 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001593 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001594 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001595 } catch (Exception e) {
1596 // You shall not crash!
1597 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001598 }
1599 }
1600 }
1601
1602 /**
1603 * Remove data activity tracking when network disconnects.
1604 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001605 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1606 final String iface = networkAgent.linkProperties.getInterfaceName();
1607 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001608
Robert Greenwalt7b816022014-04-18 15:25:25 -07001609 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1610 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001611 try {
1612 // the call fails silently if no idletimer setup for this interface
1613 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001614 } catch (Exception e) {
1615 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001616 }
1617 }
1618 }
1619
1620 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001621 * Reads the network specific MTU size from reources.
1622 * and set it on it's iface.
1623 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001624 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1625 final String iface = newLp.getInterfaceName();
1626 final int mtu = newLp.getMtu();
1627 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1628 if (VDBG) log("identical MTU - not setting");
1629 return;
1630 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001631
Robert Greenwalt43074032014-08-15 17:53:05 -07001632 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001633 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001634 return;
1635 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001636
w1997615afd812014-08-05 15:18:11 -07001637 // Cannot set MTU without interface name
1638 if (TextUtils.isEmpty(iface)) {
1639 loge("Setting MTU size with null iface.");
1640 return;
1641 }
1642
Robert Greenwalt7b816022014-04-18 15:25:25 -07001643 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001644 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 mNetd.setMtu(iface, mtu);
1646 } catch (Exception e) {
1647 Slog.e(TAG, "exception in setMtu()" + e);
1648 }
1649 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001650
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001651 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001652 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1653
1654 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001655 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001656 protected int getDefaultTcpRwnd() {
1657 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1658 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001659
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001660 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1661 if (isDefaultNetwork(nai) == false) {
1662 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001663 }
1664
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001665 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1666 String[] values = null;
1667 if (tcpBufferSizes != null) {
1668 values = tcpBufferSizes.split(",");
1669 }
1670
1671 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001672 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001673 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1674 values = tcpBufferSizes.split(",");
1675 }
1676
1677 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1678
1679 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001680 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001681
1682 final String prefix = "/sys/kernel/ipv4/tcp_";
1683 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1684 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1685 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1686 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1687 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1688 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1689 mCurrentTcpBufferSizes = tcpBufferSizes;
1690 } catch (IOException e) {
1691 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001692 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001693
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001694 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001695 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001696 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1697 if (rwndValue != 0) {
1698 SystemProperties.set(sysctlKey, rwndValue.toString());
1699 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001700 }
1701
Mattias Falk8b47b362011-08-23 14:15:13 +02001702 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001703 /*
1704 * Tell the VMs to toss their DNS caches
1705 */
1706 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1707 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001708 /*
1709 * Connectivity events can happen before boot has completed ...
1710 */
1711 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001712 final long ident = Binder.clearCallingIdentity();
1713 try {
1714 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1715 } finally {
1716 Binder.restoreCallingIdentity(ident);
1717 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001718 }
1719
Robert Greenwalt562cc542014-05-15 18:07:26 -07001720 @Override
1721 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001722 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1723 NETWORK_RESTORE_DELAY_PROP_NAME);
1724 if(restoreDefaultNetworkDelayStr != null &&
1725 restoreDefaultNetworkDelayStr.length() != 0) {
1726 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001727 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001728 } catch (NumberFormatException e) {
1729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001731 // if the system property isn't set, use the value for the apn type
1732 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1733
1734 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1735 (mNetConfigs[networkType] != null)) {
1736 ret = mNetConfigs[networkType].restoreTime;
1737 }
1738 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001741 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001742 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001743 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001744 }
1745 return false;
1746 }
1747
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001748 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1749 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1750 final long DIAG_TIME_MS = 5000;
1751 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1752 // Start gathering diagnostic information.
1753 netDiags.add(new NetworkDiagnostics(
1754 nai.network,
1755 new LinkProperties(nai.linkProperties), // Must be a copy.
1756 DIAG_TIME_MS));
1757 }
1758
1759 for (NetworkDiagnostics netDiag : netDiags) {
1760 pw.println();
1761 netDiag.waitForMeasurements();
1762 netDiag.dump(pw);
1763 }
1764 }
1765
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001767 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1768 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001769 if (mContext.checkCallingOrSelfPermission(
1770 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001772 pw.println("Permission Denial: can't dump ConnectivityService " +
1773 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1774 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001775 return;
1776 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001777
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001778 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001779 dumpNetworkDiagnostics(pw);
1780 return;
1781 }
Erik Kline379747a2015-06-05 17:47:34 +09001782
Lorenzo Colittie3805462015-06-03 11:18:24 +09001783 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001784 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001785 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001786 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001787 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001788 pw.println();
1789
Paul Jensen85cf78e2015-06-25 13:25:07 -04001790 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001791 pw.print("Active default network: ");
1792 if (defaultNai == null) {
1793 pw.println("none");
1794 } else {
1795 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001797 pw.println();
1798
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001799 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001800 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001801 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1802 pw.println(nai.toString());
1803 pw.increaseIndent();
1804 pw.println("Requests:");
1805 pw.increaseIndent();
1806 for (int i = 0; i < nai.networkRequests.size(); i++) {
1807 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001808 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001809 pw.decreaseIndent();
1810 pw.println("Lingered:");
1811 pw.increaseIndent();
1812 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1813 pw.decreaseIndent();
1814 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001815 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001816 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001817 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001818
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001819 pw.println("Metered Interfaces:");
1820 pw.increaseIndent();
1821 for (String value : mMeteredIfaces) {
1822 pw.println(value);
1823 }
1824 pw.decreaseIndent();
1825 pw.println();
1826
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001827 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001828 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001829 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1830 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001831 }
1832 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001833 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001834
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001835 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001836
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001837 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001838 pw.print("mNetTransitionWakeLock: currently " +
1839 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1840 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1841 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1842 } else {
1843 pw.println(", last requested never");
1844 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001845 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001846
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001847 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001848 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001849
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001850 pw.println();
1851 mKeepaliveTracker.dump(pw);
1852
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001853 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001854
Lorenzo Colittie3805462015-06-03 11:18:24 +09001855 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001856 pw.println();
1857 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001858 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001859 for(int i = 0; i < mInetLog.size(); i++) {
1860 pw.println(mInetLog.get(i));
1861 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001862 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001863 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001864
1865 if (argsContain(args, "--short") == false) {
1866 pw.println();
1867 synchronized (mValidationLogs) {
1868 pw.println("mValidationLogs (most recent first):");
1869 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1870 pw.println(p.first);
1871 pw.increaseIndent();
1872 p.second.dump(fd, pw, args);
1873 pw.decreaseIndent();
1874 }
1875 }
Erik Kline7523eb32015-07-09 18:24:03 +09001876
1877 pw.println();
1878 pw.println("mNetworkRequestInfoLogs (most recent first):");
1879 pw.increaseIndent();
1880 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1881 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001882 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001883 }
1884
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001885 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001886 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001887 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001888 if (officialNai != null && officialNai.equals(nai)) return true;
1889 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001890 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001891 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001892 " - " + nai);
1893 }
1894 return false;
1895 }
1896
Paul Jensenc8b9a742014-09-30 15:37:41 -04001897 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001898 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001899 }
1900
Robert Greenwalt42acef32009-08-12 16:08:25 -07001901 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001902 private class NetworkStateTrackerHandler extends Handler {
1903 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001904 super(looper);
1905 }
1906
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001907 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001909 default:
1910 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001911 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001912 handleAsyncChannelHalfConnect(msg);
1913 break;
1914 }
1915 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1916 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1917 if (nai != null) nai.asyncChannel.disconnect();
1918 break;
1919 }
1920 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1921 handleAsyncChannelDisconnected(msg);
1922 break;
1923 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001924 }
1925 return true;
1926 }
1927
1928 private void maybeHandleNetworkAgentMessage(Message msg) {
1929 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1930 if (nai == null) {
1931 if (VDBG) {
1932 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
1933 log(String.format("%s from unknown NetworkAgent", what));
1934 }
1935 return;
1936 }
1937
1938 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001939 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001940 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
1941 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1942 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
1943 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07001944 }
Robin Lee585e2482016-05-01 23:00:00 +01001945 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001946 networkCapabilities)) {
1947 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1948 + nai.networkCapabilities + " -> " + networkCapabilities);
1949 }
1950 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001951 break;
1952 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001953 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001954 if (VDBG) {
1955 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01001956 "; created=" + nai.created +
1957 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001958 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001959 LinkProperties oldLp = nai.linkProperties;
1960 synchronized (nai) {
1961 nai.linkProperties = (LinkProperties)msg.obj;
1962 }
Robin Lee585e2482016-05-01 23:00:00 +01001963 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001964 break;
1965 }
1966 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001967 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001968 updateNetworkInfo(nai, info);
1969 break;
1970 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001971 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07001972 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001973 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001974 break;
1975 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001976 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001977 try {
1978 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001979 } catch (Exception e) {
1980 // Never crash!
1981 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001982 }
1983 break;
1984 }
1985 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001986 try {
1987 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001988 } catch (Exception e) {
1989 // Never crash!
1990 loge("Exception in removeVpnUidRanges: " + e);
1991 }
1992 break;
1993 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001994 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01001995 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
1996 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001997 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001998 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001999 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002000 break;
2001 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002002 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002003 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2004 break;
2005 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002006 }
2007 }
2008
2009 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2010 switch (msg.what) {
2011 default:
2012 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002013 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002014 final NetworkAgentInfo nai;
2015 synchronized (mNetworkForNetId) {
2016 nai = mNetworkForNetId.get(msg.arg2);
2017 }
2018 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002019 final boolean valid =
2020 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002021 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2022 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002023 if (valid != nai.lastValidated) {
2024 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002025 nai.lastValidated = valid;
2026 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002027 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002028 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2029 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002030 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002031 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002032 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002033 Bundle redirectUrlBundle = new Bundle();
2034 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002035 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002036 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002037 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002038 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002039 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002040 break;
2041 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002042 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002043 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002044 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002045 handleLingerComplete(nai);
2046 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002047 break;
2048 }
Paul Jensen869868be2014-05-15 10:33:05 -04002049 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002050 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002051 final boolean visible = (msg.arg1 != 0);
2052 final NetworkAgentInfo nai;
2053 synchronized (mNetworkForNetId) {
2054 nai = mNetworkForNetId.get(netId);
2055 }
2056 // If captive portal status has changed, update capabilities.
2057 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2058 nai.lastCaptivePortalDetected = visible;
2059 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002060 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002061 }
2062 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002063 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002064 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002065 if (nai == null) {
2066 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2067 break;
2068 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002069 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002070 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2071 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002072 }
Paul Jensen869868be2014-05-15 10:33:05 -04002073 break;
2074 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002075 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002076 return true;
2077 }
2078
2079 @Override
2080 public void handleMessage(Message msg) {
2081 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2082 maybeHandleNetworkAgentMessage(msg);
2083 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002084 }
2085 }
2086
Paul Jensen85cf78e2015-06-25 13:25:07 -04002087 private void linger(NetworkAgentInfo nai) {
2088 nai.lingering = true;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002089 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002090 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2091 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2092 }
2093
Paul Jensen0cc17322014-11-25 15:26:53 -05002094 // Cancel any lingering so the linger timeout doesn't teardown a network.
2095 // This should be called when a network begins satisfying a NetworkRequest.
2096 // Note: depending on what state the NetworkMonitor is in (e.g.,
2097 // if it's awaiting captive portal login, or if validation failed), this
2098 // may trigger a re-evaluation of the network.
2099 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002100 nai.networkLingered.clear();
2101 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002102 nai.lingering = false;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002103 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002104 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002105 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2106 }
2107
Robert Greenwalt7b816022014-04-18 15:25:25 -07002108 private void handleAsyncChannelHalfConnect(Message msg) {
2109 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002110 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002111 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2112 if (VDBG) log("NetworkFactory connected");
2113 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002114 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002115 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002116 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002117 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002118 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002119 }
2120 } else {
2121 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002122 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002123 }
2124 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2125 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2126 if (VDBG) log("NetworkAgent connected");
2127 // A network agent has requested a connection. Establish the connection.
2128 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2129 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2130 } else {
2131 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002132 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002133 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002134 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002135 synchronized (mNetworkForNetId) {
2136 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002137 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002138 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002139 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002140 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002141 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002142 }
2143 }
2144 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002145
Robert Greenwalt7b816022014-04-18 15:25:25 -07002146 private void handleAsyncChannelDisconnected(Message msg) {
2147 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2148 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002149 if (DBG) {
2150 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2151 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002152 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002153 // TODO - if we move the logic to the network agent (have them disconnect
2154 // because they lost all their requests or because their score isn't good)
2155 // then they would disconnect organically, report their new state and then
2156 // disconnect the channel.
2157 if (nai.networkInfo.isConnected()) {
2158 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2159 null, null);
2160 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002161 final boolean wasDefault = isDefaultNetwork(nai);
2162 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002163 mDefaultInetConditionPublished = 0;
2164 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002165 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002166 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2167 // by other networks that are already connected. Perhaps that can be done by
2168 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2169 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002170 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002171 mKeepaliveTracker.handleStopAllKeepalives(nai,
2172 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002173 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002174 mNetworkAgentInfos.remove(msg.replyTo);
2175 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002176 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002177 // Remove the NetworkAgent, but don't mark the netId as
2178 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002179 mNetworkForNetId.remove(nai.network.netId);
2180 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002181 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002182 for (int i = 0; i < nai.networkRequests.size(); i++) {
2183 NetworkRequest request = nai.networkRequests.valueAt(i);
2184 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2185 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2186 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002187 sendUpdatedScoreToFactories(request, 0);
2188 }
2189 }
2190 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2191 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002192 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002193 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002194 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002195 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002196 rematchAllNetworksAndRequests(null, 0);
Pierre Imai04e222252016-04-12 18:02:58 +09002197 if (wasDefault && getDefaultNetwork() == null) {
2198 // Log that we lost the default network and there is no replacement.
Hugo Benichi5f16f762016-04-20 12:09:33 +09002199 logDefaultNetworkEvent(null, nai);
Pierre Imai04e222252016-04-12 18:02:58 +09002200 }
Paul Jensen62d30802015-06-17 14:42:30 -04002201 if (nai.created) {
2202 // Tell netd to clean up the configuration for this network
2203 // (routing rules, DNS, etc).
2204 // This may be slow as it requires a lot of netd shelling out to ip and
2205 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2206 // after we've rematched networks with requests which should make a potential
2207 // fallback network the default or requested a new network from the
2208 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2209 // long time.
2210 try {
2211 mNetd.removeNetwork(nai.network.netId);
2212 } catch (Exception e) {
2213 loge("Exception removing network: " + e);
2214 }
2215 }
2216 synchronized (mNetworkForNetId) {
2217 mNetIdInUse.delete(nai.network.netId);
2218 }
2219 } else {
2220 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2221 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002222 }
2223 }
2224
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002225 // If this method proves to be too slow then we can maintain a separate
2226 // pendingIntent => NetworkRequestInfo map.
2227 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2228 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2229 Intent intent = pendingIntent.getIntent();
2230 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2231 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2232 if (existingPendingIntent != null &&
2233 existingPendingIntent.getIntent().filterEquals(intent)) {
2234 return entry.getValue();
2235 }
2236 }
2237 return null;
2238 }
2239
2240 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2241 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2242
2243 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2244 if (existingRequest != null) { // remove the existing request.
2245 if (DBG) log("Replacing " + existingRequest.request + " with "
2246 + nri.request + " because their intents matched.");
2247 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2248 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002249 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002250 }
2251
Erik Klineda4bfa82015-04-30 12:58:40 +09002252 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002253 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002254 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002255 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002256 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002257 if (nri.request.networkCapabilities.hasSignalStrength() &&
2258 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2259 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002260 }
2261 }
2262 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002263 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002264 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002265 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002266 }
2267 }
2268
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002269 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2270 int callingUid) {
2271 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2272 if (nri != null) {
2273 handleReleaseNetworkRequest(nri.request, callingUid);
2274 }
2275 }
2276
Paul Jensen99364842014-12-09 11:43:45 -05002277 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002278 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2279 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002280 private boolean unneeded(NetworkAgentInfo nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002281 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002282 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2283 // If this Network is already the highest scoring Network for a request, or if
2284 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002285 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002286 (nai.networkRequests.get(nri.request.requestId) != null ||
2287 // Note that this catches two important cases:
2288 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2289 // is currently satisfying the request. This is desirable when
2290 // cellular ends up validating but WiFi does not.
2291 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002292 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002293 // WiFi ends up validating and out scoring cellular.
2294 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2295 nai.getCurrentScoreAsValidated())) {
2296 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002297 }
2298 }
Paul Jensene0988542015-06-25 15:30:08 -04002299 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002300 }
2301
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002302 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2303 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002304 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002305 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002306 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2307 return;
2308 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002309 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002310 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002311 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002312 synchronized (mUidToNetworkRequestCount) {
2313 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2314 if (requests < 1) {
2315 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2316 nri.mUid);
2317 } else if (requests == 1) {
2318 mUidToNetworkRequestCount.removeAt(
2319 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2320 } else {
2321 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2322 }
2323 }
Erik Kline7523eb32015-07-09 18:24:03 +09002324 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002325 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002326 // Find all networks that are satisfying this request and remove the request
2327 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002328 // TODO - it's my understanding that for a request there is only a single
2329 // network satisfying it, so this loop is wasteful
2330 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002331 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2332 if (nai.networkRequests.get(nri.request.requestId) != null) {
2333 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002334 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002335 log(" Removing from current network " + nai.name() +
2336 ", leaving " + nai.networkRequests.size() +
2337 " requests.");
2338 }
Paul Jensen99364842014-12-09 11:43:45 -05002339 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002340 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002341 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002342 } else {
2343 // suspect there should only be one pass through here
2344 // but if any were kept do the check below
2345 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002346 }
2347 }
2348 }
2349
Robert Greenwalt51481852015-01-08 14:43:31 -08002350 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2351 if (nai != null) {
2352 mNetworkForRequestId.remove(nri.request.requestId);
2353 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002354 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002355 // that a network connected to serve it, even though the network was already
2356 // connected. Now that this request has gone away, we might have to pretend
2357 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002358 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002359 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2360 boolean doRemove = true;
2361 if (wasKept) {
2362 // check if any of the remaining requests for this network are for the
2363 // same legacy type - if so, don't remove the nai
2364 for (int i = 0; i < nai.networkRequests.size(); i++) {
2365 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2366 if (otherRequest.legacyType == nri.request.legacyType &&
2367 isRequest(otherRequest)) {
2368 if (DBG) log(" still have other legacy request - leaving");
2369 doRemove = false;
2370 }
2371 }
2372 }
2373
2374 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002375 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002376 }
2377 }
2378
Robert Greenwalta67be032014-05-16 15:49:14 -07002379 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002380 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2381 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002382 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002383 } else {
2384 // listens don't have a singular affectedNetwork. Check all networks to see
2385 // if this listen request applies and remove it.
2386 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2387 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002388 if (nri.request.networkCapabilities.hasSignalStrength() &&
2389 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2390 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002391 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002392 }
2393 }
2394 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2395 }
2396 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002397
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002398 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2399 enforceConnectivityInternalPermission();
2400 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2401 accept ? 1 : 0, always ? 1: 0, network));
2402 }
2403
2404 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2405 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2406 " accept=" + accept + " always=" + always);
2407
2408 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2409 if (nai == null) {
2410 // Nothing to do.
2411 return;
2412 }
2413
2414 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002415 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002416 return;
2417 }
2418
2419 if (!nai.networkMisc.explicitlySelected) {
2420 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2421 }
2422
2423 if (accept != nai.networkMisc.acceptUnvalidated) {
2424 int oldScore = nai.getCurrentScore();
2425 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002426 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002427 sendUpdatedScoreToFactories(nai);
2428 }
2429
2430 if (always) {
2431 nai.asyncChannel.sendMessage(
2432 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2433 }
2434
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002435 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002436 // Tell the NetworkAgent to not automatically reconnect to the network.
2437 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2438 // Teardown the nework.
2439 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002440 }
2441
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002442 }
2443
2444 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002445 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002446 mHandler.sendMessageDelayed(
2447 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2448 PROMPT_UNVALIDATED_DELAY_MS);
2449 }
2450
2451 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002452 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002453 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2454
2455 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2456 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002457 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002458 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002459 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2460 return;
2461 }
2462
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002463 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002464 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002465 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2466 intent.setClassName("com.android.settings",
2467 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002468
2469 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2470 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2471 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002472 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002473 }
2474
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002475 private class InternalHandler extends Handler {
2476 public InternalHandler(Looper looper) {
2477 super(looper);
2478 }
2479
2480 @Override
2481 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002482 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002483 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002484 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002485 String causedBy = null;
2486 synchronized (ConnectivityService.this) {
2487 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2488 mNetTransitionWakeLock.isHeld()) {
2489 mNetTransitionWakeLock.release();
2490 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002491 } else {
2492 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002493 }
2494 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002495 if (VDBG) {
2496 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2497 log("Failed to find a new network - expiring NetTransition Wakelock");
2498 } else {
2499 log("NetTransition Wakelock (" +
2500 (causedBy == null ? "unknown" : causedBy) +
2501 " cleared because we found a replacement network");
2502 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002503 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002504 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002505 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002506 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002507 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002508 break;
2509 }
Jason Monkdecd2952013-10-10 14:02:51 -04002510 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002511 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002512 break;
2513 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002514 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002515 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2516 break;
2517 }
2518 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2519 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002520 break;
2521 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002522 case EVENT_REGISTER_NETWORK_AGENT: {
2523 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2524 break;
2525 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002526 case EVENT_REGISTER_NETWORK_REQUEST:
2527 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002528 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002529 break;
2530 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002531 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2532 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002533 handleRegisterNetworkRequestWithIntent(msg);
2534 break;
2535 }
2536 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2537 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2538 break;
2539 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002540 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002541 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002542 break;
2543 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002544 case EVENT_SET_ACCEPT_UNVALIDATED: {
2545 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2546 break;
2547 }
2548 case EVENT_PROMPT_UNVALIDATED: {
2549 handlePromptUnvalidated((Network) msg.obj);
2550 break;
2551 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002552 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2553 handleMobileDataAlwaysOn();
2554 break;
2555 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002556 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2557 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2558 mKeepaliveTracker.handleStartKeepalive(msg);
2559 break;
2560 }
2561 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2562 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2563 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2564 int slot = msg.arg1;
2565 int reason = msg.arg2;
2566 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2567 break;
2568 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002569 case EVENT_SYSTEM_READY: {
2570 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2571 nai.networkMonitor.systemReady = true;
2572 }
2573 break;
2574 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002575 }
2576 }
2577 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002578
2579 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002580 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002581 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002582 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002583 final int status = mTethering.tether(iface);
2584 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2585 try {
2586 mPolicyManager.onTetheringChanged(iface, true);
2587 } catch (RemoteException e) {
2588 }
2589 }
2590 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002591 } else {
2592 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2593 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002594 }
2595
2596 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002597 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002598 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002599
2600 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002601 final int status = mTethering.untether(iface);
2602 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2603 try {
2604 mPolicyManager.onTetheringChanged(iface, false);
2605 } catch (RemoteException e) {
2606 }
2607 }
2608 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002609 } else {
2610 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2611 }
2612 }
2613
2614 // javadoc from interface
2615 public int getLastTetherError(String iface) {
2616 enforceTetherAccessPermission();
2617
2618 if (isTetheringSupported()) {
2619 return mTethering.getLastTetherError(iface);
2620 } else {
2621 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2622 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002623 }
2624
2625 // TODO - proper iface API for selection by property, inspection, etc
2626 public String[] getTetherableUsbRegexs() {
2627 enforceTetherAccessPermission();
2628 if (isTetheringSupported()) {
2629 return mTethering.getTetherableUsbRegexs();
2630 } else {
2631 return new String[0];
2632 }
2633 }
2634
2635 public String[] getTetherableWifiRegexs() {
2636 enforceTetherAccessPermission();
2637 if (isTetheringSupported()) {
2638 return mTethering.getTetherableWifiRegexs();
2639 } else {
2640 return new String[0];
2641 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002642 }
2643
Danica Chang6fdd0c62010-08-11 14:54:43 -07002644 public String[] getTetherableBluetoothRegexs() {
2645 enforceTetherAccessPermission();
2646 if (isTetheringSupported()) {
2647 return mTethering.getTetherableBluetoothRegexs();
2648 } else {
2649 return new String[0];
2650 }
2651 }
2652
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002653 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002654 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002655 if (isTetheringSupported()) {
2656 return mTethering.setUsbTethering(enable);
2657 } else {
2658 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2659 }
2660 }
2661
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002662 // TODO - move iface listing, queries, etc to new module
2663 // javadoc from interface
2664 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002665 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002666 return mTethering.getTetherableIfaces();
2667 }
2668
2669 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002670 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002671 return mTethering.getTetheredIfaces();
2672 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002673
Robert Greenwalt5a735062010-03-02 17:25:02 -08002674 public String[] getTetheringErroredIfaces() {
2675 enforceTetherAccessPermission();
2676 return mTethering.getErroredIfaces();
2677 }
2678
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002679 public String[] getTetheredDhcpRanges() {
2680 enforceConnectivityInternalPermission();
2681 return mTethering.getTetheredDhcpRanges();
2682 }
2683
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002684 // if ro.tether.denied = true we default to no tethering
2685 // gservices could set the secure setting to 1 though to enable it on a build where it
2686 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002687 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002688 public boolean isTetheringSupported() {
2689 enforceTetherAccessPermission();
2690 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002691 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002692 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2693 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002694 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2695 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002696 mTethering.getTetherableWifiRegexs().length != 0 ||
2697 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2698 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002699 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002700
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002701 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002702 public void startTethering(int type, ResultReceiver receiver,
2703 boolean showProvisioningUi) {
2704 ConnectivityManager.enforceTetherChangePermission(mContext);
2705 if (!isTetheringSupported()) {
2706 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2707 return;
2708 }
2709 mTethering.startTethering(type, receiver, showProvisioningUi);
2710 }
2711
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002712 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002713 public void stopTethering(int type) {
2714 ConnectivityManager.enforceTetherChangePermission(mContext);
2715 mTethering.stopTethering(type);
2716 }
2717
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002718 // Called when we lose the default network and have no replacement yet.
2719 // This will automatically be cleared after X seconds or a new default network
2720 // becomes CONNECTED, whichever happens first. The timer is started by the
2721 // first caller and not restarted by subsequent callers.
2722 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002723 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002724 synchronized (this) {
2725 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002726 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002727 mNetTransitionWakeLock.acquire();
2728 mNetTransitionWakeLockCausedBy = forWhom;
2729 }
2730 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002731 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002732 mNetTransitionWakeLockTimeout);
2733 return;
2734 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002735
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002736 // 100 percent is full good, 0 is full bad.
2737 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002738 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002739 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002740 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002741 }
2742
Paul Jensenbfd17b72015-04-07 12:43:13 -04002743 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002744 enforceAccessPermission();
2745 enforceInternetPermission();
2746
Paul Jensenbfd17b72015-04-07 12:43:13 -04002747 NetworkAgentInfo nai;
2748 if (network == null) {
2749 nai = getDefaultNetwork();
2750 } else {
2751 nai = getNetworkAgentInfoForNetwork(network);
2752 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002753 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2754 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2755 return;
2756 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002757 // Revalidate if the app report does not match our current validated state.
2758 if (hasConnectivity == nai.lastValidated) return;
2759 final int uid = Binder.getCallingUid();
2760 if (DBG) {
2761 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2762 ") by " + uid);
2763 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002764 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002765 // Validating a network that has not yet connected could result in a call to
2766 // rematchNetworkAndRequests() which is not meant to work on such networks.
2767 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04002768
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002769 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002770
2771 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2772 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002773 }
2774
Paul Jensencee9b512015-05-06 07:32:40 -04002775 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002776 // this information is already available as a world read/writable jvm property
2777 // so this API change wouldn't have a benifit. It also breaks the passing
2778 // of proxy info to all the JVMs.
2779 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002780 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002781 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002782 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2783 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002784 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002785 }
2786
Paul Jensencee9b512015-05-06 07:32:40 -04002787 public ProxyInfo getProxyForNetwork(Network network) {
2788 if (network == null) return getDefaultProxy();
2789 final ProxyInfo globalProxy = getGlobalProxy();
2790 if (globalProxy != null) return globalProxy;
2791 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2792 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2793 // caller may not have.
2794 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2795 if (nai == null) return null;
2796 synchronized (nai) {
2797 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2798 if (proxyInfo == null) return null;
2799 return new ProxyInfo(proxyInfo);
2800 }
2801 }
2802
Paul Jensene0bef712014-12-10 15:12:18 -05002803 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2804 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2805 // proxy is null then there is no proxy in place).
2806 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2807 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2808 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2809 proxy = null;
2810 }
2811 return proxy;
2812 }
2813
2814 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2815 // better for determining if a new proxy broadcast is necessary:
2816 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2817 // avoid unnecessary broadcasts.
2818 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2819 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2820 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2821 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2822 // all set.
2823 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2824 a = canonicalizeProxyInfo(a);
2825 b = canonicalizeProxyInfo(b);
2826 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2827 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2828 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2829 }
2830
Jason Monk207900c2014-04-25 15:00:09 -04002831 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002832 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002833
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002834 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002835 if (proxyProperties == mGlobalProxy) return;
2836 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2837 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2838
2839 String host = "";
2840 int port = 0;
2841 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002842 String pacFileUrl = "";
2843 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002844 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002845 if (!proxyProperties.isValid()) {
2846 if (DBG)
2847 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2848 return;
2849 }
Jason Monk207900c2014-04-25 15:00:09 -04002850 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 host = mGlobalProxy.getHost();
2852 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002853 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002854 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002855 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002856 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002857 } else {
2858 mGlobalProxy = null;
2859 }
2860 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002861 final long token = Binder.clearCallingIdentity();
2862 try {
2863 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2864 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2865 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2866 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002867 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002868 } finally {
2869 Binder.restoreCallingIdentity(token);
2870 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002871
Jason Monkcf0f97a2014-10-02 15:39:38 -04002872 if (mGlobalProxy == null) {
2873 proxyProperties = mDefaultProxy;
2874 }
2875 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002876 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002877 }
2878
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002879 private void loadGlobalProxy() {
2880 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002881 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2882 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2883 String exclList = Settings.Global.getString(res,
2884 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002885 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2886 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002887 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002888 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002889 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002890 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002891 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002892 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002893 if (!proxyProperties.isValid()) {
2894 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2895 return;
2896 }
2897
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002898 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002899 mGlobalProxy = proxyProperties;
2900 }
2901 }
2902 }
2903
Jason Monk207900c2014-04-25 15:00:09 -04002904 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002905 // this information is already available as a world read/writable jvm property
2906 // so this API change wouldn't have a benifit. It also breaks the passing
2907 // of proxy info to all the JVMs.
2908 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002909 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002910 return mGlobalProxy;
2911 }
2912 }
2913
Jason Monk207900c2014-04-25 15:00:09 -04002914 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002915 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002916 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002917 proxy = null;
2918 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002919 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002920 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002921 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002922 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002923 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2924 return;
2925 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002926
2927 // This call could be coming from the PacManager, containing the port of the local
2928 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2929 // global (to get the correct local port), and send a broadcast.
2930 // TODO: Switch PacManager to have its own message to send back rather than
2931 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002932 if ((mGlobalProxy != null) && (proxy != null)
2933 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002934 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2935 mGlobalProxy = proxy;
2936 sendProxyBroadcast(mGlobalProxy);
2937 return;
2938 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002939 mDefaultProxy = proxy;
2940
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002941 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002942 if (!mDefaultProxyDisabled) {
2943 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002944 }
2945 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002946 }
2947
Paul Jensene0bef712014-12-10 15:12:18 -05002948 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2949 // This method gets called when any network changes proxy, but the broadcast only ever contains
2950 // the default proxy (even if it hasn't changed).
2951 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2952 // world where an app might be bound to a non-default network.
2953 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2954 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2955 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2956
2957 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2958 sendProxyBroadcast(getDefaultProxy());
2959 }
2960 }
2961
Robert Greenwalt434203a2010-10-11 16:00:27 -07002962 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002963 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2964 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002965 if (!TextUtils.isEmpty(proxy)) {
2966 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002967 if (data.length == 0) {
2968 return;
2969 }
2970
Robert Greenwalt434203a2010-10-11 16:00:27 -07002971 String proxyHost = data[0];
2972 int proxyPort = 8080;
2973 if (data.length > 1) {
2974 try {
2975 proxyPort = Integer.parseInt(data[1]);
2976 } catch (NumberFormatException e) {
2977 return;
2978 }
2979 }
Jason Monk207900c2014-04-25 15:00:09 -04002980 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002981 setGlobalProxy(p);
2982 }
2983 }
2984
Jason Monk207900c2014-04-25 15:00:09 -04002985 private void sendProxyBroadcast(ProxyInfo proxy) {
2986 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002987 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002988 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002989 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002990 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2991 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002992 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002993 final long ident = Binder.clearCallingIdentity();
2994 try {
2995 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2996 } finally {
2997 Binder.restoreCallingIdentity(ident);
2998 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002999 }
3000
3001 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003002 final private HashMap<Uri, Integer> mUriEventMap;
3003 final private Context mContext;
3004 final private Handler mHandler;
3005
3006 SettingsObserver(Context context, Handler handler) {
3007 super(null);
3008 mUriEventMap = new HashMap<Uri, Integer>();
3009 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003010 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003011 }
3012
Erik Klineda4bfa82015-04-30 12:58:40 +09003013 void observe(Uri uri, int what) {
3014 mUriEventMap.put(uri, what);
3015 final ContentResolver resolver = mContext.getContentResolver();
3016 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003017 }
3018
3019 @Override
3020 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003021 Slog.wtf(TAG, "Should never be reached.");
3022 }
3023
3024 @Override
3025 public void onChange(boolean selfChange, Uri uri) {
3026 final Integer what = mUriEventMap.get(uri);
3027 if (what != null) {
3028 mHandler.obtainMessage(what.intValue()).sendToTarget();
3029 } else {
3030 loge("No matching event to send for URI=" + uri);
3031 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003032 }
3033 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003034
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003035 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003036 Slog.d(TAG, s);
3037 }
3038
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003039 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003040 Slog.e(TAG, s);
3041 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003042
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003043 private static <T> T checkNotNull(T value, String message) {
3044 if (value == null) {
3045 throw new NullPointerException(message);
3046 }
3047 return value;
3048 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003049
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003050 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003051 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003052 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3053 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3054 *
3055 * @param oldPackage Package name of the application which currently controls VPN, which will
3056 * be replaced. If there is no such application, this should should either be
3057 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3058 * @param newPackage Package name of the application which should gain control of VPN, or
3059 * {@code null} to disable.
3060 * @param userId User for whom to prepare the new VPN.
3061 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003062 * @hide
3063 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003064 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003065 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3066 int userId) {
3067 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003068 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003069
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003070 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003071 Vpn vpn = mVpns.get(userId);
3072 if (vpn != null) {
3073 return vpn.prepare(oldPackage, newPackage);
3074 } else {
3075 return false;
3076 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003077 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003078 }
3079
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003080 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003081 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3082 * This method is used by system-privileged apps.
3083 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3084 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3085 *
3086 * @param packageName The package for which authorization state should change.
3087 * @param userId User for whom {@code packageName} is installed.
3088 * @param authorized {@code true} if this app should be able to start a VPN connection without
3089 * explicit user approval, {@code false} if not.
3090 *
Jeff Davidson05542602014-08-11 14:07:27 -07003091 * @hide
3092 */
3093 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003094 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3095 enforceCrossUserPermission(userId);
3096
Jeff Davidson05542602014-08-11 14:07:27 -07003097 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003098 Vpn vpn = mVpns.get(userId);
3099 if (vpn != null) {
3100 vpn.setPackageAuthorization(packageName, authorized);
3101 }
Jeff Davidson05542602014-08-11 14:07:27 -07003102 }
3103 }
3104
3105 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003106 * Configure a TUN interface and return its file descriptor. Parameters
3107 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003108 * and not available in ConnectivityManager. Permissions are checked in
3109 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003110 * @hide
3111 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003112 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003113 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003114 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003115 int user = UserHandle.getUserId(Binder.getCallingUid());
3116 synchronized(mVpns) {
3117 return mVpns.get(user).establish(config);
3118 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003119 }
3120
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003121 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003122 * Start legacy VPN, controlling native daemons as needed. Creates a
3123 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003124 */
3125 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003126 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003127 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003128 final LinkProperties egress = getActiveLinkProperties();
3129 if (egress == null) {
3130 throw new IllegalStateException("Missing active network connection");
3131 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003132 int user = UserHandle.getUserId(Binder.getCallingUid());
3133 synchronized(mVpns) {
3134 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3135 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003136 }
3137
3138 /**
3139 * Return the information of the ongoing legacy VPN. This method is used
3140 * by VpnSettings and not available in ConnectivityManager. Permissions
3141 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003142 */
3143 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003144 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3145 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003146 if (mLockdownEnabled) {
3147 return null;
3148 }
3149
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003150 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003151 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003152 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003153 }
3154
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003155 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003156 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3157 * and not available in ConnectivityManager.
3158 */
3159 @Override
3160 public VpnInfo[] getAllVpnInfo() {
3161 enforceConnectivityInternalPermission();
3162 if (mLockdownEnabled) {
3163 return new VpnInfo[0];
3164 }
3165
3166 synchronized(mVpns) {
3167 List<VpnInfo> infoList = new ArrayList<>();
3168 for (int i = 0; i < mVpns.size(); i++) {
3169 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3170 if (info != null) {
3171 infoList.add(info);
3172 }
3173 }
3174 return infoList.toArray(new VpnInfo[infoList.size()]);
3175 }
3176 }
3177
3178 /**
3179 * @return VPN information for accounting, or null if we can't retrieve all required
3180 * information, e.g primary underlying iface.
3181 */
3182 @Nullable
3183 private VpnInfo createVpnInfo(Vpn vpn) {
3184 VpnInfo info = vpn.getVpnInfo();
3185 if (info == null) {
3186 return null;
3187 }
3188 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3189 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3190 // the underlyingNetworks list.
3191 if (underlyingNetworks == null) {
3192 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3193 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3194 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3195 }
3196 } else if (underlyingNetworks.length > 0) {
3197 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3198 if (linkProperties != null) {
3199 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3200 }
3201 }
3202 return info.primaryUnderlyingIface == null ? null : info;
3203 }
3204
3205 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003206 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3207 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003208 * Permissions are checked in Vpn class.
3209 * @hide
3210 */
3211 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003212 public VpnConfig getVpnConfig(int userId) {
3213 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003214 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003215 Vpn vpn = mVpns.get(userId);
3216 if (vpn != null) {
3217 return vpn.getVpnConfig();
3218 } else {
3219 return null;
3220 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003221 }
3222 }
3223
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003224 @Override
3225 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003226 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3227 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3228 return false;
3229 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003230
3231 // Tear down existing lockdown if profile was removed
3232 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3233 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003234 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3235 final VpnProfile profile = VpnProfile.decode(
3236 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003237 if (profile == null) {
3238 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3239 setLockdownTracker(null);
3240 return true;
3241 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003242 int user = UserHandle.getUserId(Binder.getCallingUid());
3243 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003244 Vpn vpn = mVpns.get(user);
3245 if (vpn == null) {
3246 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3247 return false;
3248 }
3249 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003250 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003251 } else {
3252 setLockdownTracker(null);
3253 }
3254
3255 return true;
3256 }
3257
3258 /**
3259 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3260 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3261 */
3262 private void setLockdownTracker(LockdownVpnTracker tracker) {
3263 // Shutdown any existing tracker
3264 final LockdownVpnTracker existing = mLockdownTracker;
3265 mLockdownTracker = null;
3266 if (existing != null) {
3267 existing.shutdown();
3268 }
3269
3270 try {
3271 if (tracker != null) {
3272 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003273 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003274 mLockdownTracker = tracker;
3275 mLockdownTracker.init();
3276 } else {
3277 mNetd.setFirewallEnabled(false);
3278 }
3279 } catch (RemoteException e) {
3280 // ignored; NMS lives inside system_server
3281 }
3282 }
3283
3284 private void throwIfLockdownEnabled() {
3285 if (mLockdownEnabled) {
3286 throw new IllegalStateException("Unavailable in lockdown mode");
3287 }
3288 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003289
Robin Lee244ce8e2016-01-05 18:03:46 +00003290 /**
3291 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3292 *
3293 * @return {@code false} in case of errors; {@code true} otherwise.
3294 */
3295 private boolean updateAlwaysOnVpn(int user) {
3296 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3297 if (lockdownPackage == null) {
3298 return true;
3299 }
3300
3301 // Create an intent to start the VPN service declared in the app's manifest.
3302 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3303 serviceIntent.setPackage(lockdownPackage);
3304
3305 try {
3306 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3307 } catch (RuntimeException e) {
3308 return false;
3309 }
3310 }
3311
3312 @Override
3313 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3314 enforceConnectivityInternalPermission();
3315 enforceCrossUserPermission(userId);
3316
3317 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3318 if (LockdownVpnTracker.isEnabled()) {
3319 return false;
3320 }
3321
3322 // If the current VPN package is the same as the new one, this is a no-op
3323 final String oldPackage = getAlwaysOnVpnPackage(userId);
3324 if (TextUtils.equals(oldPackage, packageName)) {
3325 return true;
3326 }
3327
3328 synchronized (mVpns) {
3329 Vpn vpn = mVpns.get(userId);
3330 if (vpn == null) {
3331 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3332 return false;
3333 }
3334 if (!vpn.setAlwaysOnPackage(packageName)) {
3335 return false;
3336 }
3337 if (!updateAlwaysOnVpn(userId)) {
3338 vpn.setAlwaysOnPackage(null);
3339 return false;
3340 }
3341 }
3342 return true;
3343 }
3344
3345 @Override
3346 public String getAlwaysOnVpnPackage(int userId) {
3347 enforceConnectivityInternalPermission();
3348 enforceCrossUserPermission(userId);
3349
3350 synchronized (mVpns) {
3351 Vpn vpn = mVpns.get(userId);
3352 if (vpn == null) {
3353 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3354 return null;
3355 }
3356 return vpn.getAlwaysOnPackage();
3357 }
3358 }
3359
Wink Savilleab9321d2013-06-29 21:10:57 -07003360 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003361 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003362 // TODO: Remove? Any reason to trigger a provisioning check?
3363 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003364 }
3365
3366 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003367 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003368
Paul Jensen89e0f092014-09-15 15:59:36 -04003369 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003370 Intent intent = new Intent(action);
3371 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003372 // Concatenate the range of types onto the range of NetIDs.
3373 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003374 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003375 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003376 }
3377
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003378 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003379 * Show or hide network provisioning notifications.
3380 *
3381 * We use notifications for two purposes: to notify that a network requires sign in
3382 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3383 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3384 * particular network we can display the notification type that was most recently requested.
3385 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3386 * might first display NO_INTERNET, and then when the captive portal check completes, display
3387 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003388 *
3389 * @param id an identifier that uniquely identifies this notification. This must match
3390 * between show and hide calls. We use the NetID value but for legacy callers
3391 * we concatenate the range of types with the range of NetIDs.
3392 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003393 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003394 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3395 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003396 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003397 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3398 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003399 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003400 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003401
3402 Resources r = Resources.getSystem();
3403 NotificationManager notificationManager = (NotificationManager) mContext
3404 .getSystemService(Context.NOTIFICATION_SERVICE);
3405
3406 if (visible) {
3407 CharSequence title;
3408 CharSequence details;
3409 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003410 if (notifyType == NotificationType.NO_INTERNET &&
3411 networkType == ConnectivityManager.TYPE_WIFI) {
3412 title = r.getString(R.string.wifi_no_internet, 0);
3413 details = r.getString(R.string.wifi_no_internet_detailed);
3414 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3415 } else if (notifyType == NotificationType.SIGN_IN) {
3416 switch (networkType) {
3417 case ConnectivityManager.TYPE_WIFI:
3418 title = r.getString(R.string.wifi_available_sign_in, 0);
3419 details = r.getString(R.string.network_available_sign_in_detailed,
3420 extraInfo);
3421 icon = R.drawable.stat_notify_wifi_in_range;
3422 break;
3423 case ConnectivityManager.TYPE_MOBILE:
3424 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3425 title = r.getString(R.string.network_available_sign_in, 0);
3426 // TODO: Change this to pull from NetworkInfo once a printable
3427 // name has been added to it
3428 details = mTelephonyManager.getNetworkOperatorName();
3429 icon = R.drawable.stat_notify_rssi_in_range;
3430 break;
3431 default:
3432 title = r.getString(R.string.network_available_sign_in, 0);
3433 details = r.getString(R.string.network_available_sign_in_detailed,
3434 extraInfo);
3435 icon = R.drawable.stat_notify_rssi_in_range;
3436 break;
3437 }
3438 } else {
3439 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3440 + getNetworkTypeName(networkType));
3441 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003442 }
3443
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003444 Notification notification = new Notification.Builder(mContext)
3445 .setWhen(0)
3446 .setSmallIcon(icon)
3447 .setAutoCancel(true)
3448 .setTicker(title)
3449 .setColor(mContext.getColor(
3450 com.android.internal.R.color.system_notification_accent_color))
3451 .setContentTitle(title)
3452 .setContentText(details)
3453 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003454 .setLocalOnly(true)
3455 .setPriority(highPriority ?
3456 Notification.PRIORITY_HIGH :
3457 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003458 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003459 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003460 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003461
Wink Saville948282b2013-08-29 08:55:16 -07003462 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003463 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003464 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003465 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003466 npe.printStackTrace();
3467 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003468 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003469 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003470 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003471 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003472 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003473 npe.printStackTrace();
3474 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003475 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003476 }
3477
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003478 /** Location to an updatable file listing carrier provisioning urls.
3479 * An example:
3480 *
3481 * <?xml version="1.0" encoding="utf-8"?>
3482 * <provisioningUrls>
3483 * <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 -07003484 * </provisioningUrls>
3485 */
3486 private static final String PROVISIONING_URL_PATH =
3487 "/data/misc/radio/provisioning_urls.xml";
3488 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003489
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003490 /** XML tag for root element. */
3491 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3492 /** XML tag for individual url */
3493 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003494 /** XML attribute for mcc */
3495 private static final String ATTR_MCC = "mcc";
3496 /** XML attribute for mnc */
3497 private static final String ATTR_MNC = "mnc";
3498
Paul Jensen434dde82015-06-11 09:43:30 -04003499 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003500 FileReader fileReader = null;
3501 XmlPullParser parser = null;
3502 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003503
3504 try {
3505 fileReader = new FileReader(mProvisioningUrlFile);
3506 parser = Xml.newPullParser();
3507 parser.setInput(fileReader);
3508 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3509
3510 while (true) {
3511 XmlUtils.nextElement(parser);
3512
3513 String element = parser.getName();
3514 if (element == null) break;
3515
Paul Jensen434dde82015-06-11 09:43:30 -04003516 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003517 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3518 try {
3519 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3520 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3521 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3522 parser.next();
3523 if (parser.getEventType() == XmlPullParser.TEXT) {
3524 return parser.getText();
3525 }
3526 }
3527 }
3528 } catch (NumberFormatException e) {
3529 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3530 }
3531 }
3532 }
3533 return null;
3534 } catch (FileNotFoundException e) {
3535 loge("Carrier Provisioning Urls file not found");
3536 } catch (XmlPullParserException e) {
3537 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3538 } catch (IOException e) {
3539 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3540 } finally {
3541 if (fileReader != null) {
3542 try {
3543 fileReader.close();
3544 } catch (IOException e) {}
3545 }
3546 }
3547 return null;
3548 }
3549
Wink Saville42d4f082013-07-20 20:31:59 -07003550 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003551 public String getMobileProvisioningUrl() {
3552 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003553 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003554 if (TextUtils.isEmpty(url)) {
3555 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003556 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003557 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003558 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003559 }
Wink Saville8cf35602013-07-10 23:00:07 -07003560 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003561 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003562 String phoneNumber = mTelephonyManager.getLine1Number();
3563 if (TextUtils.isEmpty(phoneNumber)) {
3564 phoneNumber = "0000000000";
3565 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003566 url = String.format(url,
3567 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3568 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003569 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003570 }
3571
Wink Savilleab9321d2013-06-29 21:10:57 -07003572 return url;
3573 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003574
Wink Saville948282b2013-08-29 08:55:16 -07003575 @Override
3576 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003577 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003578 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003579 final long ident = Binder.clearCallingIdentity();
3580 try {
3581 setProvNotificationVisible(visible, networkType, action);
3582 } finally {
3583 Binder.restoreCallingIdentity(ident);
3584 }
Wink Saville948282b2013-08-29 08:55:16 -07003585 }
Wink Saville7788c612013-08-29 14:57:08 -07003586
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003587 @Override
3588 public void setAirplaneMode(boolean enable) {
3589 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003590 final long ident = Binder.clearCallingIdentity();
3591 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003592 final ContentResolver cr = mContext.getContentResolver();
3593 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3594 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3595 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003596 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003597 } finally {
3598 Binder.restoreCallingIdentity(ident);
3599 }
3600 }
3601
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003602 private void onUserStart(int userId) {
3603 synchronized(mVpns) {
3604 Vpn userVpn = mVpns.get(userId);
3605 if (userVpn != null) {
3606 loge("Starting user already has a VPN");
3607 return;
3608 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003609 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003610 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003611 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003612 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3613 updateLockdownVpn();
3614 } else {
3615 updateAlwaysOnVpn(userId);
3616 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003617 }
3618
3619 private void onUserStop(int userId) {
3620 synchronized(mVpns) {
3621 Vpn userVpn = mVpns.get(userId);
3622 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003623 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003624 return;
3625 }
3626 mVpns.delete(userId);
3627 }
3628 }
3629
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003630 private void onUserAdded(int userId) {
3631 synchronized(mVpns) {
3632 final int vpnsSize = mVpns.size();
3633 for (int i = 0; i < vpnsSize; i++) {
3634 Vpn vpn = mVpns.valueAt(i);
3635 vpn.onUserAdded(userId);
3636 }
3637 }
3638 }
3639
3640 private void onUserRemoved(int userId) {
3641 synchronized(mVpns) {
3642 final int vpnsSize = mVpns.size();
3643 for (int i = 0; i < vpnsSize; i++) {
3644 Vpn vpn = mVpns.valueAt(i);
3645 vpn.onUserRemoved(userId);
3646 }
3647 }
3648 }
3649
Robin Lee89e7a692016-02-29 14:38:17 +00003650 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003651 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3652 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3653 updateLockdownVpn();
3654 } else {
3655 updateAlwaysOnVpn(userId);
3656 }
3657 }
3658
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003659 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3660 @Override
3661 public void onReceive(Context context, Intent intent) {
3662 final String action = intent.getAction();
3663 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3664 if (userId == UserHandle.USER_NULL) return;
3665
3666 if (Intent.ACTION_USER_STARTING.equals(action)) {
3667 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003668 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003669 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003670 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3671 onUserAdded(userId);
3672 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3673 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003674 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3675 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003676 }
3677 }
3678 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003679
Robert Greenwalta67be032014-05-16 15:49:14 -07003680 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3681 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003682 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3683 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003684
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003685 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3686 // Map from UID to number of NetworkRequests that UID has filed.
3687 @GuardedBy("mUidToNetworkRequestCount")
3688 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3689
Robert Greenwalta67be032014-05-16 15:49:14 -07003690 private static class NetworkFactoryInfo {
3691 public final String name;
3692 public final Messenger messenger;
3693 public final AsyncChannel asyncChannel;
3694
3695 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3696 this.name = name;
3697 this.messenger = messenger;
3698 this.asyncChannel = asyncChannel;
3699 }
3700 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003701
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003702 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003703 * A NetworkRequest as registered by an application can be one of three
3704 * types:
3705 *
3706 * - "listen", for which the framework will issue callbacks about any
3707 * and all networks that match the specified NetworkCapabilities,
3708 *
3709 * - "request", capable of causing a specific network to be created
3710 * first (e.g. a telephony DUN request), the framework will issue
3711 * callbacks about the single, highest scoring current network
3712 * (if any) that matches the specified NetworkCapabilities, or
3713 *
3714 * - "track the default network", a hybrid of the two designed such
3715 * that the framework will issue callbacks for the single, highest
3716 * scoring current network (if any) that matches the capabilities of
3717 * the default Internet request (mDefaultRequest), but which cannot
3718 * cause the framework to either create or retain the existence of
3719 * any specific network.
3720 *
3721 */
3722 private static enum NetworkRequestType {
3723 LISTEN,
3724 TRACK_DEFAULT,
3725 REQUEST
3726 };
3727
3728 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003729 * Tracks info about the requester.
3730 * Also used to notice when the calling process dies so we can self-expire
3731 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003732 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003733 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003734 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003735 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003736 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003737 final int mPid;
3738 final int mUid;
3739 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003740 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003741
Erik Kline371c7b72016-03-22 17:04:20 +09003742 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003743 request = r;
3744 mPendingIntent = pi;
3745 messenger = null;
3746 mBinder = null;
3747 mPid = getCallingPid();
3748 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003749 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003750 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003751 }
3752
Erik Kline371c7b72016-03-22 17:04:20 +09003753 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003754 super();
3755 messenger = m;
3756 request = r;
3757 mBinder = binder;
3758 mPid = getCallingPid();
3759 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003760 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003761 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003762 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003763
3764 try {
3765 mBinder.linkToDeath(this, 0);
3766 } catch (RemoteException e) {
3767 binderDied();
3768 }
3769 }
3770
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003771 private void enforceRequestCountLimit() {
3772 synchronized (mUidToNetworkRequestCount) {
3773 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3774 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3775 throw new IllegalArgumentException("Too many NetworkRequests filed");
3776 }
3777 mUidToNetworkRequestCount.put(mUid, networkRequests);
3778 }
3779 }
3780
Erik Kline371c7b72016-03-22 17:04:20 +09003781 private String typeString() {
3782 switch (mType) {
3783 case LISTEN: return "Listen";
3784 case REQUEST: return "Request";
3785 case TRACK_DEFAULT: return "Track default";
3786 default:
3787 return "unknown type";
3788 }
3789 }
3790
Robert Greenwalt9258c642014-03-26 16:47:06 -07003791 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003792 if (mBinder != null) {
3793 mBinder.unlinkToDeath(this, 0);
3794 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003795 }
3796
3797 public void binderDied() {
3798 log("ConnectivityService NetworkRequestInfo binderDied(" +
3799 request + ", " + mBinder + ")");
3800 releaseNetworkRequest(request);
3801 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003802
Erik Kline371c7b72016-03-22 17:04:20 +09003803 /**
3804 * Returns true iff. the contained NetworkRequest is one that:
3805 *
3806 * - should be associated with at most one satisfying network
3807 * at a time;
3808 *
3809 * - should cause a network to be kept up if it is the only network
3810 * which can satisfy the NetworkReqeust.
3811 *
3812 * For full detail of how isRequest() is used for pairing Networks with
3813 * NetworkRequests read rematchNetworkAndRequests().
3814 *
3815 * TODO: Rename to something more properly descriptive.
3816 */
3817 public boolean isRequest() {
3818 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3819 (mType == NetworkRequestType.REQUEST);
3820 }
3821
Robert Greenwalta67be032014-05-16 15:49:14 -07003822 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003823 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003824 " from uid/pid:" + mUid + "/" + mPid +
3825 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003826 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003827 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003828 }
3829
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003830 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3831 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3832 if (badCapability != null) {
3833 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003834 }
3835 }
3836
Erik Kline9d598e12015-07-13 16:37:51 +09003837 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003838 final SortedSet<Integer> thresholds = new TreeSet();
3839 synchronized (nai) {
3840 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3841 if (nri.request.networkCapabilities.hasSignalStrength() &&
3842 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3843 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3844 }
3845 }
3846 }
Erik Kline9d598e12015-07-13 16:37:51 +09003847 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003848 }
3849
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003850 private void updateSignalStrengthThresholds(
3851 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3852 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003853 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003854 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3855
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003856 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003857 String detail;
3858 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3859 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3860 } else {
3861 detail = reason;
3862 }
3863 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3864 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3865 }
3866
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003867 nai.asyncChannel.sendMessage(
3868 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003869 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003870 }
3871
Robert Greenwalt9258c642014-03-26 16:47:06 -07003872 @Override
3873 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003874 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003875 final NetworkRequestType type = (networkCapabilities == null)
3876 ? NetworkRequestType.TRACK_DEFAULT
3877 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003878 // If the requested networkCapabilities is null, take them instead from
3879 // the default network request. This allows callers to keep track of
3880 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003881 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003882 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3883 enforceAccessPermission();
3884 } else {
3885 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3886 enforceNetworkRequestPermissions(networkCapabilities);
3887 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003888 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003889 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003890
Robert Greenwalt6078b502014-06-11 16:05:07 -07003891 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003892 throw new IllegalArgumentException("Bad timeout specified");
3893 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003894
Etan Cohenddb9ef02015-11-18 10:56:15 -08003895 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3896 .equals(networkCapabilities.getNetworkSpecifier())) {
3897 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3898 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3899 }
3900
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003901 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3902 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09003903 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09003904 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003905
3906 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003907 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003908 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003909 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003910 }
3911 return networkRequest;
3912 }
3913
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003914 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003915 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003916 enforceConnectivityInternalPermission();
3917 } else {
3918 enforceChangePermission();
3919 }
3920 }
3921
fenglub15e72b2015-03-20 11:29:56 -07003922 @Override
fengludb571472015-04-21 17:12:05 -07003923 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003924 enforceAccessPermission();
3925 NetworkAgentInfo nai = null;
3926 if (network == null) {
3927 return false;
3928 }
3929 synchronized (mNetworkForNetId) {
3930 nai = mNetworkForNetId.get(network.netId);
3931 }
3932 if (nai != null) {
3933 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3934 return true;
3935 }
3936 return false;
3937 }
3938
3939
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003940 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3941 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003942 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003943 final int uidRules;
3944 final int uid = Binder.getCallingUid();
3945 synchronized(mRulesLock) {
3946 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3947 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003948 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003949 // we could silently fail or we can filter the available nets to only give
3950 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003951 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003952 }
3953 }
3954 }
3955
Robert Greenwalt9258c642014-03-26 16:47:06 -07003956 @Override
3957 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3958 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003959 checkNotNull(operation, "PendingIntent cannot be null.");
3960 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3961 enforceNetworkRequestPermissions(networkCapabilities);
3962 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003963 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003964
3965 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3966 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003967 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09003968 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003969 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003970 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3971 nri));
3972 return networkRequest;
3973 }
3974
Jeremy Joslin79294842014-12-03 17:15:28 -08003975 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3976 mHandler.sendMessageDelayed(
3977 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3978 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3979 }
3980
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003981 @Override
3982 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003983 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003984 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3985 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003986 }
3987
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003988 // In order to implement the compatibility measure for pre-M apps that call
3989 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3990 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3991 // This ensures it has permission to do so.
3992 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3993 if (nc == null) {
3994 return false;
3995 }
3996 int[] transportTypes = nc.getTransportTypes();
3997 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3998 return false;
3999 }
4000 try {
4001 mContext.enforceCallingOrSelfPermission(
4002 android.Manifest.permission.ACCESS_WIFI_STATE,
4003 "ConnectivityService");
4004 } catch (SecurityException e) {
4005 return false;
4006 }
4007 return true;
4008 }
4009
Robert Greenwalt9258c642014-03-26 16:47:06 -07004010 @Override
4011 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4012 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004013 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4014 enforceAccessPermission();
4015 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004016
Erik Kline7523eb32015-07-09 18:24:03 +09004017 NetworkRequest networkRequest = new NetworkRequest(
4018 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004019 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09004020 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004021 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022
4023 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4024 return networkRequest;
4025 }
4026
4027 @Override
4028 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4029 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004030 checkNotNull(operation, "PendingIntent cannot be null.");
4031 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4032 enforceAccessPermission();
4033 }
4034
Erik Kline7523eb32015-07-09 18:24:03 +09004035 NetworkRequest networkRequest = new NetworkRequest(
4036 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004037 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004038 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004039 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004040
4041 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042 }
4043
4044 @Override
4045 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004046 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4047 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004048 }
4049
4050 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004051 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004052 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004053 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4054 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004055 }
4056
Robert Greenwalta67be032014-05-16 15:49:14 -07004057 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004058 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004059 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4060 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4061 }
4062
4063 @Override
4064 public void unregisterNetworkFactory(Messenger messenger) {
4065 enforceConnectivityInternalPermission();
4066 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4067 }
4068
4069 private void handleUnregisterNetworkFactory(Messenger messenger) {
4070 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4071 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004072 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004073 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004074 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004075 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004076 }
4077
Robert Greenwalt7b816022014-04-18 15:25:25 -07004078 /**
4079 * NetworkAgentInfo supporting a request by requestId.
4080 * These have already been vetted (their Capabilities satisfy the request)
4081 * and the are the highest scored network available.
4082 * the are keyed off the Requests requestId.
4083 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004084 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004085 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4086 new SparseArray<NetworkAgentInfo>();
4087
Paul Jensen31a94f42015-02-13 14:18:39 -05004088 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4089 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004090 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4091 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004092 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4093 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4094 // there may not be a strict 1:1 correlation between the two.
4095 @GuardedBy("mNetworkForNetId")
4096 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004097
Robert Greenwalt7b816022014-04-18 15:25:25 -07004098 // NetworkAgentInfo keyed off its connecting messenger
4099 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004100 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004101 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4102 new HashMap<Messenger, NetworkAgentInfo>();
4103
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004104 @GuardedBy("mBlockedAppUids")
4105 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4106
Paul Jensen2c311d62014-11-17 12:34:51 -05004107 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004108 private final NetworkRequest mDefaultRequest;
4109
Erik Klineda4bfa82015-04-30 12:58:40 +09004110 // Request used to optionally keep mobile data active even when higher
4111 // priority networks like Wi-Fi are active.
4112 private final NetworkRequest mDefaultMobileDataRequest;
4113
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004114 private NetworkAgentInfo getDefaultNetwork() {
4115 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4116 }
4117
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004118 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004119 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004120 }
4121
Paul Jensen31a94f42015-02-13 14:18:39 -05004122 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004123 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004124 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004125 enforceConnectivityInternalPermission();
4126
Paul Jensen2c311d62014-11-17 12:34:51 -05004127 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4128 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004129 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004130 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4131 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004132 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004133 synchronized (this) {
4134 nai.networkMonitor.systemReady = mSystemReady;
4135 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004136 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004137 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004138 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004139 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004140 }
4141
4142 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4143 if (VDBG) log("Got NetworkAgent Messenger");
4144 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004145 synchronized (mNetworkForNetId) {
4146 mNetworkForNetId.put(na.network.netId, na);
4147 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004148 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4149 NetworkInfo networkInfo = na.networkInfo;
4150 na.networkInfo = null;
4151 updateNetworkInfo(na, networkInfo);
4152 }
4153
4154 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4155 LinkProperties newLp = networkAgent.linkProperties;
4156 int netId = networkAgent.network.netId;
4157
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004158 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4159 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004160 if (networkAgent.clatd != null) {
4161 networkAgent.clatd.fixupLinkProperties(oldLp);
4162 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004163
Paul Jensen992f2522014-04-28 10:33:11 -04004164 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004165 updateMtu(newLp, oldLp);
4166 // TODO - figure out what to do for clat
4167// for (LinkProperties lp : newLp.getStackedLinks()) {
4168// updateMtu(lp, null);
4169// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004170 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004171
Erik Kline94887872016-04-05 13:30:49 +09004172 updateRoutes(newLp, oldLp, netId);
4173 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004174
Paul Jensen3b759822014-05-13 11:44:01 -04004175 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004176 if (isDefaultNetwork(networkAgent)) {
4177 handleApplyDefaultProxy(newLp.getHttpProxy());
4178 } else {
4179 updateProxy(newLp, oldLp, networkAgent);
4180 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004181 // TODO - move this check to cover the whole function
4182 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004183 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004184 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4185 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004186
4187 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004188 }
4189
Lorenzo Colitti95439462014-10-09 13:44:48 +09004190 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4191 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4192 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004193
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004194 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004195 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4196 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004197 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004198 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004199 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004200 }
Paul Jensen992f2522014-04-28 10:33:11 -04004201
4202 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4203 CompareResult<String> interfaceDiff = new CompareResult<String>();
4204 if (oldLp != null) {
4205 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4206 } else if (newLp != null) {
4207 interfaceDiff.added = newLp.getAllInterfaceNames();
4208 }
4209 for (String iface : interfaceDiff.added) {
4210 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004211 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004212 mNetd.addInterfaceToNetwork(iface, netId);
4213 } catch (Exception e) {
4214 loge("Exception adding interface: " + e);
4215 }
4216 }
4217 for (String iface : interfaceDiff.removed) {
4218 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004219 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004220 mNetd.removeInterfaceFromNetwork(iface, netId);
4221 } catch (Exception e) {
4222 loge("Exception removing interface: " + e);
4223 }
4224 }
4225 }
4226
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004227 /**
4228 * Have netd update routes from oldLp to newLp.
4229 * @return true if routes changed between oldLp and newLp
4230 */
4231 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004232 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4233 if (oldLp != null) {
4234 routeDiff = oldLp.compareAllRoutes(newLp);
4235 } else if (newLp != null) {
4236 routeDiff.added = newLp.getAllRoutes();
4237 }
4238
4239 // add routes before removing old in case it helps with continuous connectivity
4240
4241 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4242 for (RouteInfo route : routeDiff.added) {
4243 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004244 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004245 try {
4246 mNetd.addRoute(netId, route);
4247 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004248 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4249 loge("Exception in addRoute for non-gateway: " + e);
4250 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004251 }
4252 }
4253 for (RouteInfo route : routeDiff.added) {
4254 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004255 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004256 try {
4257 mNetd.addRoute(netId, route);
4258 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004259 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4260 loge("Exception in addRoute for gateway: " + e);
4261 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004262 }
4263 }
4264
4265 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004266 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004267 try {
4268 mNetd.removeRoute(netId, route);
4269 } catch (Exception e) {
4270 loge("Exception in removeRoute: " + e);
4271 }
4272 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004273 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004274 }
Erik Kline41368502015-06-17 13:19:54 +09004275
Erik Kline94887872016-04-05 13:30:49 +09004276 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4277 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4278 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004279 }
Erik Kline94887872016-04-05 13:30:49 +09004280
4281 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004282 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004283 try {
4284 mNetd.setDnsServersForNetwork(
4285 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4286 } catch (Exception e) {
4287 loge("Exception in setDnsServersForNetwork: " + e);
4288 }
4289 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4290 if (defaultNai != null && defaultNai.network.netId == netId) {
4291 setDefaultDnsSystemProperties(dnses);
4292 }
4293 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004294 }
4295
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004296 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4297 int last = 0;
4298 for (InetAddress dns : dnses) {
4299 ++last;
4300 String key = "net.dns" + last;
4301 String value = dns.getHostAddress();
4302 SystemProperties.set(key, value);
4303 }
4304 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4305 String key = "net.dns" + i;
4306 SystemProperties.set(key, "");
4307 }
4308 mNumDnsEntries = last;
4309 }
4310
Paul Jensen3d194ea2015-06-16 14:27:36 -04004311 /**
4312 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4313 * augmented with any stateful capabilities implied from {@code networkAgent}
4314 * (e.g., validated status and captive portal status).
4315 *
Paul Jensene0988542015-06-25 15:30:08 -04004316 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004317 * @param networkCapabilities the new network capabilities.
4318 */
Paul Jensene0988542015-06-25 15:30:08 -04004319 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004320 // Don't modify caller's NetworkCapabilities.
4321 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004322 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004323 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4324 } else {
4325 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4326 }
Paul Jensene0988542015-06-25 15:30:08 -04004327 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004328 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4329 } else {
4330 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4331 }
Paul Jensene0988542015-06-25 15:30:08 -04004332 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4333 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004334 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4335 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4336 try {
4337 mNetd.setNetworkPermission(nai.network.netId,
4338 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4339 null : NetworkManagementService.PERMISSION_SYSTEM);
4340 } catch (RemoteException e) {
4341 loge("Exception in setNetworkPermission: " + e);
4342 }
4343 }
Paul Jensene0988542015-06-25 15:30:08 -04004344 synchronized (nai) {
4345 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004346 }
Paul Jensene0988542015-06-25 15:30:08 -04004347 rematchAllNetworksAndRequests(nai, oldScore);
4348 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004349 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004350 }
4351
Paul Jensenc8b9a742014-09-30 15:37:41 -04004352 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4353 for (int i = 0; i < nai.networkRequests.size(); i++) {
4354 NetworkRequest nr = nai.networkRequests.valueAt(i);
4355 // Don't send listening requests to factories. b/17393458
4356 if (!isRequest(nr)) continue;
4357 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4358 }
4359 }
4360
Robert Greenwalt7b816022014-04-18 15:25:25 -07004361 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4362 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004363 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004364 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4365 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004366 }
4367 }
4368
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004369 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4370 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004371 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004372 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004373 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4374 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004375 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004376 sendIntent(nri.mPendingIntent, intent);
4377 }
4378 // else not handled
4379 }
4380
4381 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4382 mPendingIntentWakeLock.acquire();
4383 try {
4384 if (DBG) log("Sending " + pendingIntent);
4385 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4386 } catch (PendingIntent.CanceledException e) {
4387 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4388 mPendingIntentWakeLock.release();
4389 releasePendingNetworkRequest(pendingIntent);
4390 }
4391 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4392 }
4393
4394 @Override
4395 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4396 String resultData, Bundle resultExtras) {
4397 if (DBG) log("Finished sending " + pendingIntent);
4398 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004399 // Release with a delay so the receiving client has an opportunity to put in its
4400 // own request.
4401 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004402 }
4403
Robert Greenwalt9258c642014-03-26 16:47:06 -07004404 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004405 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004406 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004407 Bundle bundle = new Bundle();
4408 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4409 new NetworkRequest(nri.request));
4410 Message msg = Message.obtain();
4411 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4412 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4413 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4414 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004415 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004416 case ConnectivityManager.CALLBACK_LOSING: {
4417 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4418 break;
4419 }
4420 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4421 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4422 new NetworkCapabilities(networkAgent.networkCapabilities));
4423 break;
4424 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004425 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004426 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4427 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004428 break;
4429 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004430 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004431 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004432 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004433 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004434 if (VDBG) {
4435 log("sending notification " + notifyTypeToName(notificationType) +
4436 " for " + nri.request);
4437 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004438 nri.messenger.send(msg);
4439 } catch (RemoteException e) {
4440 // may occur naturally in the race of binder death.
4441 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4442 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004443 }
4444
Paul Jensenc8b9a742014-09-30 15:37:41 -04004445 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4446 for (int i = 0; i < nai.networkRequests.size(); i++) {
4447 NetworkRequest nr = nai.networkRequests.valueAt(i);
4448 // Ignore listening requests.
4449 if (!isRequest(nr)) continue;
4450 loge("Dead network still had at least " + nr);
4451 break;
4452 }
4453 nai.asyncChannel.disconnect();
4454 }
4455
Robert Greenwalt7b816022014-04-18 15:25:25 -07004456 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4457 if (oldNetwork == null) {
4458 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4459 return;
4460 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004461 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4462 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004463 }
4464
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004465 private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004466 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004467 setupDataActivityTracking(newNetwork);
4468 try {
4469 mNetd.setDefaultNetId(newNetwork.network.netId);
4470 } catch (Exception e) {
4471 loge("Exception setting default network :" + e);
4472 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004473 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004474 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004475 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004476 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Hugo Benichi5f16f762016-04-20 12:09:33 +09004477 logDefaultNetworkEvent(newNetwork, prevNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004478 }
4479
Paul Jensen2161a8e2014-09-11 11:00:39 -04004480 // Handles a network appearing or improving its score.
4481 //
4482 // - Evaluates all current NetworkRequests that can be
4483 // satisfied by newNetwork, and reassigns to newNetwork
4484 // any such requests for which newNetwork is the best.
4485 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004486 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004487 // needed. A network is needed if it is the best network for
4488 // one or more NetworkRequests, or if it is a VPN.
4489 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004490 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004491 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004492 //
4493 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4494 // networks that have no chance (i.e. even if validated)
4495 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004496 //
4497 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4498 // it does not remove NetworkRequests that other Networks could better satisfy.
4499 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4500 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4501 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004502 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004503 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004504 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4505 // performed to tear down unvalidated networks that have no chance (i.e. even if
4506 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004507 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004508 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Robin Lee585e2482016-05-01 23:00:00 +01004509 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004510 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004511 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004512 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004513 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004514 // Find and migrate to this Network any NetworkRequests for
4515 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004516 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004517 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004518 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004519 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004520 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4521 final boolean satisfies = newNetwork.satisfies(nri.request);
4522 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004523 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004524 log("Network " + newNetwork.name() + " was already satisfying" +
4525 " request " + nri.request.requestId + ". No change.");
4526 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004527 keep = true;
4528 continue;
4529 }
4530
4531 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004532 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004533 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004534 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004535 // This is not a request, it's a callback listener.
4536 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004537 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004538 continue;
4539 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004540
Robert Greenwalt7b816022014-04-18 15:25:25 -07004541 // next check if it's better than any current network we're using for
4542 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004543 if (VDBG) {
4544 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004545 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4546 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004547 }
4548 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004549 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004550 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004551 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004552 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004553 currentNetwork.networkRequests.remove(nri.request.requestId);
4554 currentNetwork.networkLingered.add(nri.request);
4555 affectedNetworks.add(currentNetwork);
4556 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004557 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004558 }
Paul Jensen573a0352015-01-08 10:49:34 -05004559 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004560 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004561 if (!newNetwork.addRequest(nri.request)) {
4562 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4563 }
4564 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004565 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004566 // Tell NetworkFactories about the new score, so they can stop
4567 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004568 // TODO - this could get expensive if we have alot of requests for this
4569 // network. Think about if there is a way to reduce this. Push
4570 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004571 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004572 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004573 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004574 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004575 }
4576 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004577 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4578 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4579 // mark it as no longer satisfying "nri". Because networks are processed by
4580 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4581 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4582 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4583 // This means this code doesn't have to handle the case where "currentNetwork" no
4584 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4585 if (DBG) {
4586 log("Network " + newNetwork.name() + " stopped satisfying" +
4587 " request " + nri.request.requestId);
4588 }
4589 newNetwork.networkRequests.remove(nri.request.requestId);
4590 if (currentNetwork == newNetwork) {
4591 mNetworkForRequestId.remove(nri.request.requestId);
4592 sendUpdatedScoreToFactories(nri.request, 0);
4593 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004594 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004595 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4596 newNetwork.name() +
4597 " without updating mNetworkForRequestId or factories!");
4598 }
4599 }
4600 // TODO: technically, sending CALLBACK_LOST here is
4601 // incorrect if nri is a request (not a listen) and there
4602 // is a replacement network currently connected that can
4603 // satisfy it. However, the only capability that can both
4604 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4605 // so this code is only incorrect for a network that loses
4606 // the TRUSTED capability, which is a rare case.
4607 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004608 }
4609 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004610 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004611 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004612 if (nai.lingering) {
4613 // Already lingered. Nothing to do. This can only happen if "nai" is in
4614 // "affectedNetworks" twice. The reasoning being that to get added to
4615 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4616 // (i.e. not lingered) so it could have only been lingered by this loop.
4617 // unneeded(nai) will be false and we'll call unlinger() below which would
4618 // be bad, so handle it here.
4619 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004620 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004621 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004622 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004623 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004624 }
4625 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004626 if (isNewDefault) {
4627 // Notify system services that this network is up.
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004628 makeDefault(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004629 synchronized (ConnectivityService.this) {
4630 // have a new default network, release the transition wakelock in
4631 // a second if it's held. The second pause is to allow apps
4632 // to reconnect over the new network
4633 if (mNetTransitionWakeLock.isHeld()) {
4634 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4635 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4636 mNetTransitionWakeLockSerialNumber, 0),
4637 1000);
4638 }
4639 }
4640 }
4641
4642 // do this after the default net is switched, but
4643 // before LegacyTypeTracker sends legacy broadcasts
4644 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4645
4646 if (isNewDefault) {
4647 // Maintain the illusion: since the legacy API only
4648 // understands one network at a time, we must pretend
4649 // that the current default network disconnected before
4650 // the new one connected.
4651 if (oldDefaultNetwork != null) {
4652 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4653 oldDefaultNetwork, true);
4654 }
4655 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4656 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4657 notifyLockdownVpn(newNetwork);
4658 }
4659
Robert Greenwalt7b816022014-04-18 15:25:25 -07004660 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004661 // Notify battery stats service about this network, both the normal
4662 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004663 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004664 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004665 final IBatteryStats bs = BatteryStatsService.getService();
4666 final int type = newNetwork.networkInfo.getType();
4667
4668 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4669 bs.noteNetworkInterfaceType(baseIface, type);
4670 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4671 final String stackedIface = stacked.getInterfaceName();
4672 bs.noteNetworkInterfaceType(stackedIface, type);
4673 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4674 }
4675 } catch (RemoteException ignored) {
4676 }
4677
Robert Greenwalt152ed372014-12-17 17:19:53 -08004678 // This has to happen after the notifyNetworkCallbacks as that tickles each
4679 // ConnectivityManager instance so that legacy requests correctly bind dns
4680 // requests to this network. The legacy users are listening for this bcast
4681 // and will generally do a dns request so they can ensureRouteToHost and if
4682 // they do that before the callbacks happen they'll use the default network.
4683 //
4684 // TODO: Is there still a race here? We send the broadcast
4685 // after sending the callback, but if the app can receive the
4686 // broadcast before the callback, it might still break.
4687 //
4688 // This *does* introduce a race where if the user uses the new api
4689 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4690 // they may get old info. Reverse this after the old startUsing api is removed.
4691 // This is on top of the multiple intent sequencing referenced in the todo above.
4692 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4693 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4694 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4695 // legacy type tracker filters out repeat adds
4696 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4697 }
4698 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004699
4700 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4701 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4702 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4703 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4704 if (newNetwork.isVPN()) {
4705 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4706 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004707 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004708 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4709 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004710 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004711 if (DBG) log("Reaping " + nai.name());
4712 teardownUnneededNetwork(nai);
4713 }
4714 }
4715 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004716 }
4717
Paul Jensen1c7ba022015-06-16 14:27:36 -04004718 /**
4719 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4720 * being disconnected.
4721 * @param changed If only one Network's score or capabilities have been modified since the last
4722 * time this function was called, pass this Network in this argument, otherwise pass
4723 * null.
4724 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4725 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4726 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4727 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4728 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004729 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004730 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004731 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4732 // to avoid the slowness. It is not simply enough to process just "changed", for
4733 // example in the case where "changed"'s score decreases and another network should begin
4734 // satifying a NetworkRequest that "changed" currently satisfies.
4735
4736 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4737 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4738 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004739 if (changed != null && oldScore < changed.getCurrentScore()) {
4740 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004741 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004742 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4743 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4744 // Rematch higher scoring networks first to prevent requests first matching a lower
4745 // scoring network and then a higher scoring network, which could produce multiple
4746 // callbacks and inadvertently unlinger networks.
4747 Arrays.sort(nais);
4748 for (NetworkAgentInfo nai : nais) {
4749 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004750 // Only reap the last time through the loop. Reaping before all rematching
4751 // is complete could incorrectly teardown a network that hasn't yet been
4752 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004753 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004754 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004755 }
4756 }
4757 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004758
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004759 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004760 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004761 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004762 // For now only update icons for default connection.
4763 // TODO: Update WiFi and cellular icons separately. b/17237507
4764 if (!isDefaultNetwork(nai)) return;
4765
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004766 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004767 // Don't repeat publish.
4768 if (newInetCondition == mDefaultInetConditionPublished) return;
4769
4770 mDefaultInetConditionPublished = newInetCondition;
4771 sendInetConditionBroadcast(nai.networkInfo);
4772 }
4773
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004774 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4775 if (mLockdownTracker != null) {
4776 if (nai != null && nai.isVPN()) {
4777 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4778 } else {
4779 mLockdownTracker.onNetworkInfoChanged();
4780 }
4781 }
4782 }
4783
Robert Greenwalt7b816022014-04-18 15:25:25 -07004784 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4785 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004786 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004787 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004788 synchronized (networkAgent) {
4789 oldInfo = networkAgent.networkInfo;
4790 networkAgent.networkInfo = newInfo;
4791 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004792 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004793
4794 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004795 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4796 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4797 notifyIfacesChangedForNetworkStats();
4798 } else if (VDBG) log("ignoring duplicate network state non-change");
4799 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004800 return;
4801 }
4802 if (DBG) {
4803 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4804 (oldInfo == null ? "null" : oldInfo.getState()) +
4805 " to " + state);
4806 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004807
Robin Lee585e2482016-05-01 23:00:00 +01004808 if (!networkAgent.created
4809 && (state == NetworkInfo.State.CONNECTED
4810 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004811 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004812 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004813 if (networkAgent.isVPN()) {
4814 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004815 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4816 (networkAgent.networkMisc == null ||
4817 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004818 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004819 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4820 networkAgent.networkCapabilities.hasCapability(
4821 NET_CAPABILITY_NOT_RESTRICTED) ?
4822 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004823 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004824 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004825 loge("Error creating network " + networkAgent.network.netId + ": "
4826 + e.getMessage());
4827 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004828 }
Paul Jenseneec75412014-08-04 12:21:19 -04004829 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004830 }
4831
4832 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4833 networkAgent.everConnected = true;
4834
Robert Greenwalt7b816022014-04-18 15:25:25 -07004835 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004836 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004837
Paul Jensenca8f16a2014-05-09 12:47:55 -04004838 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004839 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004840
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004841 if (networkAgent.isVPN()) {
4842 // Temporarily disable the default proxy (not global).
4843 synchronized (mProxyLock) {
4844 if (!mDefaultProxyDisabled) {
4845 mDefaultProxyDisabled = true;
4846 if (mGlobalProxy == null && mDefaultProxy != null) {
4847 sendProxyBroadcast(null);
4848 }
4849 }
4850 }
4851 // TODO: support proxy per network.
4852 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004853
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004854 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4855 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4856 // capabilities, so it only needs to be done once on initial connect, not every time the
4857 // network's capabilities change. Note that we do this before rematching the network,
4858 // so we could decide to tear it down immediately afterwards. That's fine though - on
4859 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4860 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004861 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004862
Paul Jensen2161a8e2014-09-11 11:00:39 -04004863 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004864 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004865
4866 // This has to happen after matching the requests, because callbacks are just requests.
4867 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004868 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004869 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004870 if (networkAgent.isVPN()) {
4871 synchronized (mProxyLock) {
4872 if (mDefaultProxyDisabled) {
4873 mDefaultProxyDisabled = false;
4874 if (mGlobalProxy == null && mDefaultProxy != null) {
4875 sendProxyBroadcast(mDefaultProxy);
4876 }
4877 }
4878 }
4879 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004880 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4881 state == NetworkInfo.State.SUSPENDED) {
4882 // going into or coming out of SUSPEND: rescore and notify
4883 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004884 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004885 }
4886 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4887 ConnectivityManager.CALLBACK_SUSPENDED :
4888 ConnectivityManager.CALLBACK_RESUMED));
4889 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004890 }
4891 }
4892
Robert Greenwaltac96c522014-06-03 16:43:57 -07004893 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004894 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004895 if (score < 0) {
4896 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4897 "). Bumping score to min of 0");
4898 score = 0;
4899 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004900
Paul Jensen2161a8e2014-09-11 11:00:39 -04004901 final int oldScore = nai.getCurrentScore();
4902 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004903
Paul Jensen85cf78e2015-06-25 13:25:07 -04004904 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004905
Paul Jensenc8b9a742014-09-30 15:37:41 -04004906 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004907 }
4908
Robert Greenwalt9258c642014-03-26 16:47:06 -07004909 // notify only this one new request of the current state
4910 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4911 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4912 // TODO - read state from monitor to decide what to send.
4913// if (nai.networkMonitor.isLingering()) {
4914// notifyType = NetworkCallbacks.LOSING;
4915// } else if (nai.networkMonitor.isEvaluating()) {
4916// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4917// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004918 if (nri.mPendingIntent == null) {
4919 callCallbackForRequest(nri, nai, notifyType);
4920 } else {
4921 sendPendingIntentForRequest(nri, nai, notifyType);
4922 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004923 }
4924
Robert Greenwalt8d482522015-06-24 13:23:42 -07004925 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004926 // The NetworkInfo we actually send out has no bearing on the real
4927 // state of affairs. For example, if the default connection is mobile,
4928 // and a request for HIPRI has just gone away, we need to pretend that
4929 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4930 // the state to DISCONNECTED, even though the network is of type MOBILE
4931 // and is still connected.
4932 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4933 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004934 if (state != DetailedState.DISCONNECTED) {
4935 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004936 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004937 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004938 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004939 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4940 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4941 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4942 if (info.isFailover()) {
4943 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4944 nai.networkInfo.setFailover(false);
4945 }
4946 if (info.getReason() != null) {
4947 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4948 }
4949 if (info.getExtraInfo() != null) {
4950 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4951 }
4952 NetworkAgentInfo newDefaultAgent = null;
4953 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004954 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004955 if (newDefaultAgent != null) {
4956 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4957 newDefaultAgent.networkInfo);
4958 } else {
4959 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4960 }
4961 }
4962 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4963 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004964 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004965 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004966 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004967 }
4968 }
4969 }
4970
Robert Greenwalt7b816022014-04-18 15:25:25 -07004971 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004972 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004973 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004974 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4975 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4976 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004977 if (nri.mPendingIntent == null) {
4978 callCallbackForRequest(nri, networkAgent, notifyType);
4979 } else {
4980 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4981 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004982 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004983 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004984
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004985 private String notifyTypeToName(int notifyType) {
4986 switch (notifyType) {
4987 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4988 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4989 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4990 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4991 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4992 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4993 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4994 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4995 }
4996 return "UNKNOWN";
4997 }
4998
Jeff Sharkey69736342014-12-08 14:50:12 -08004999 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005000 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5001 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005002 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005003 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005004 try {
5005 mStatsService.forceUpdateIfaces();
5006 } catch (Exception ignored) {
5007 }
5008 }
5009
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005010 @Override
5011 public boolean addVpnAddress(String address, int prefixLength) {
5012 throwIfLockdownEnabled();
5013 int user = UserHandle.getUserId(Binder.getCallingUid());
5014 synchronized (mVpns) {
5015 return mVpns.get(user).addAddress(address, prefixLength);
5016 }
5017 }
5018
5019 @Override
5020 public boolean removeVpnAddress(String address, int prefixLength) {
5021 throwIfLockdownEnabled();
5022 int user = UserHandle.getUserId(Binder.getCallingUid());
5023 synchronized (mVpns) {
5024 return mVpns.get(user).removeAddress(address, prefixLength);
5025 }
5026 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005027
5028 @Override
5029 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5030 throwIfLockdownEnabled();
5031 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005032 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005033 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005034 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005035 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005036 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005037 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005038 }
5039 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005040 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005041
5042 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005043 public String getCaptivePortalServerUrl() {
5044 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5045 }
5046
5047 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005048 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5049 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5050 enforceKeepalivePermission();
5051 mKeepaliveTracker.startNattKeepalive(
5052 getNetworkAgentInfoForNetwork(network),
5053 intervalSeconds, messenger, binder,
5054 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5055 }
5056
5057 @Override
5058 public void stopKeepalive(Network network, int slot) {
5059 mHandler.sendMessage(mHandler.obtainMessage(
5060 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5061 }
5062
5063 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005064 public void factoryReset() {
5065 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005066
5067 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5068 return;
5069 }
5070
Robin Lee3b3dd942015-05-12 18:14:58 +01005071 final int userId = UserHandle.getCallingUserId();
5072
Stuart Scottf1fb3972015-04-02 18:00:02 -07005073 // Turn airplane mode off
5074 setAirplaneMode(false);
5075
Stuart Scotte3e314d2015-04-20 14:07:45 -07005076 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5077 // Untether
5078 for (String tether : getTetheredIfaces()) {
5079 untether(tether);
5080 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005081 }
5082
Stuart Scotte3e314d2015-04-20 14:07:45 -07005083 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5084 // Turn VPN off
5085 VpnConfig vpnConfig = getVpnConfig(userId);
5086 if (vpnConfig != null) {
5087 if (vpnConfig.legacy) {
5088 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5089 } else {
5090 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5091 // in the future without user intervention.
5092 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005093
Stuart Scotte3e314d2015-04-20 14:07:45 -07005094 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5095 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005096 }
5097 }
5098 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005099
5100 @VisibleForTesting
5101 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5102 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5103 return new NetworkMonitor(context, handler, nai, defaultRequest);
5104 }
Erik Kline48f12f22016-04-14 17:30:59 +09005105
Hugo Benichi5f16f762016-04-20 12:09:33 +09005106 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5107 int newNetid = NETID_UNSET;
5108 int prevNetid = NETID_UNSET;
5109 int[] transports = new int[0];
5110 boolean hadIPv4 = false;
5111 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005112
Hugo Benichi5f16f762016-04-20 12:09:33 +09005113 if (newNai != null) {
5114 newNetid = newNai.network.netId;
5115 transports = newNai.networkCapabilities.getTransportTypes();
5116 }
5117 if (prevNai != null) {
5118 prevNetid = prevNai.network.netId;
5119 final LinkProperties lp = prevNai.linkProperties;
5120 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5121 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5122 }
5123
5124 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005125 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005126}