blob: df20704f862dfbb61d9db947aa5db040b0433c44 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070036import android.app.AlarmManager;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080037import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070038import android.app.Notification;
39import android.app.NotificationManager;
40import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070041import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.ContentResolver;
43import android.content.Context;
44import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070047import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090048import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070049import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090051import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070053import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070054import android.net.INetworkPolicyListener;
55import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070056import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080057import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070058import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070059import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070060import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070061import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070062import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070064import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070065import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070066import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070067import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070068import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070069import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070070import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040071import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070072import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040073import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040074import android.net.Uri;
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;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070090import android.os.SystemClock;
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;
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700118import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700119import com.android.internal.util.IndentingPrintWriter;
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;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500157import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700158import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700159import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700160import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700161import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
163/**
164 * @hide
165 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800166public class ConnectivityService extends IConnectivityManager.Stub
167 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700168 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700170 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700171 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
Jake Hamby786e71a2014-02-06 14:43:50 -0800173 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700174
Jeff Sharkey899223b2012-08-04 15:24:58 -0700175 // TODO: create better separation between radio types and network types
176
Robert Greenwalt42acef32009-08-12 16:08:25 -0700177 // how long to wait before switching back to a radio's default network
178 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
179 // system property that can override the above value
180 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
181 "android.telephony.apn-restore";
182
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900183 // How long to wait before putting up a "This network doesn't have an Internet connection,
184 // connect anyway?" dialog after the user selects a network that doesn't validate.
185 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
186
Jeremy Joslin79294842014-12-03 17:15:28 -0800187 // How long to delay to removal of a pending intent based request.
188 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
189 private final int mReleasePendingIntentDelayMs;
190
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800191 private Tethering mTethering;
192
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700193 private final PermissionMonitor mPermissionMonitor;
194
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700195 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700196
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700197 @GuardedBy("mVpns")
198 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700199
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700200 private boolean mLockdownEnabled;
201 private LockdownVpnTracker mLockdownTracker;
202
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700203 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
204 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700205 /** Currently active network rules by UID. */
206 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700207 /** Set of ifaces that are costly. */
208 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700209
Erik Klineda4bfa82015-04-30 12:58:40 +0900210 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700212 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700213 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800215 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
217 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700218 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700220 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800221 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700223
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700224 private String mCurrentTcpBufferSizes;
225
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700226 private static final int ENABLED = 1;
227 private static final int DISABLED = 0;
228
Paul Jensenb10e37f2014-11-25 12:33:08 -0500229 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400230 // Tear down networks that have no chance (e.g. even if validated) of becoming
231 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500232 // all networks have been rematched against all NetworkRequests.
233 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400234 // Don't reap networks. This should be passed when some networks have not yet been
235 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500236 DONT_REAP
237 };
238
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700239 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700240 * used internally to change our mobile data enabled flag
241 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700242 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700243
244 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700245 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700246 * from one net to another. Clear happens when we get a new
247 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
248 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700250 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700251
Robert Greenwalt434203a2010-10-11 16:00:27 -0700252 /**
253 * used internally to reload global proxy settings
254 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700255 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700256
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700257 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400258 * PAC manager has received new port.
259 */
260 private static final int EVENT_PROXY_HAS_CHANGED = 16;
261
Robert Greenwalte049c232014-04-11 15:53:27 -0700262 /**
263 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700264 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700265 */
266 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
267
Robert Greenwalt7b816022014-04-18 15:25:25 -0700268 /**
269 * used internally when registering NetworkAgents
270 * obj = Messenger
271 */
272 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
273
Robert Greenwalt9258c642014-03-26 16:47:06 -0700274 /**
275 * used to add a network request
276 * includes a NetworkRequestInfo
277 */
278 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
279
280 /**
281 * indicates a timeout period is over - check if we had a network yet or not
282 * and if not, call the timeout calback (but leave the request live until they
283 * cancel it.
284 * includes a NetworkRequestInfo
285 */
286 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
287
288 /**
289 * used to add a network listener - no request
290 * includes a NetworkRequestInfo
291 */
292 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
293
294 /**
295 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400296 * arg1 = UID of caller
297 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700298 */
299 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
300
Robert Greenwalta67be032014-05-16 15:49:14 -0700301 /**
302 * used internally when registering NetworkFactories
303 * obj = Messenger
304 */
305 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
306
Robert Greenwalt27711812014-06-25 16:45:57 -0700307 /**
308 * used internally to expire a wakelock when transitioning
309 * from one net to another. Expire happens when we fail to find
310 * a new network (typically after 1 minute) -
311 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
312 * a replacement network.
313 */
314 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
315
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700316 /**
317 * Used internally to indicate the system is ready.
318 */
319 private static final int EVENT_SYSTEM_READY = 25;
320
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800321 /**
322 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400323 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800324 */
325 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
326
327 /**
328 * used to remove a pending intent and its associated network request.
329 * arg1 = UID of caller
330 * obj = PendingIntent
331 */
332 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
333
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900334 /**
335 * used to specify whether a network should be used even if unvalidated.
336 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
337 * arg2 = whether to remember this choice in the future (1 or 0)
338 * obj = network
339 */
340 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
341
342 /**
343 * used to ask the user to confirm a connection to an unvalidated network.
344 * obj = network
345 */
346 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700347
Erik Klineda4bfa82015-04-30 12:58:40 +0900348 /**
349 * used internally to (re)configure mobile data always-on settings.
350 */
351 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
352
Paul Jensen694f2b82015-06-17 14:15:39 -0400353 /**
354 * used to add a network listener with a pending intent
355 * obj = NetworkRequestInfo
356 */
357 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
358
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900359 /** Handler thread used for both of the handlers below. */
360 @VisibleForTesting
361 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700362 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700363 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700364 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700365 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366
Mike Lockwood0f79b542009-08-14 14:18:49 -0400367 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800368 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400369
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700370 private PowerManager.WakeLock mNetTransitionWakeLock;
371 private String mNetTransitionWakeLockCausedBy = "";
372 private int mNetTransitionWakeLockSerialNumber;
373 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800374 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700375
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700376 private InetAddress mDefaultDns;
377
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
453 private static final boolean DBG = true;
454 private static final boolean VDBG = false;
455 private static final String TAG = "CSLegacyTypeTracker";
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Robert Greenwalt8d482522015-06-24 13:23:42 -0700496 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900497 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700499 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900501 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 }
503 }
504
505 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700506 public void add(int type, NetworkAgentInfo nai) {
507 if (!isTypeSupported(type)) {
508 return; // Invalid network type.
509 }
510 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
511
512 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
513 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700514 return;
515 }
516
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900517 list.add(nai);
518
519 // 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 +0900520 final boolean isDefaultNetwork = isDefaultNetwork(nai);
521 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700522 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
523 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 }
526
Lorenzo Colittia793a672014-07-31 23:20:17 +0900527 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900528 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
530 if (list == null || list.isEmpty()) {
531 return;
532 }
533
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900534 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900535
536 if (!list.remove(nai)) {
537 return;
538 }
539
Robert Greenwalt8d482522015-06-24 13:23:42 -0700540 final DetailedState state = DetailedState.DISCONNECTED;
541
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900542 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700543 maybeLogBroadcast(nai, state, type, wasDefault);
544 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900545 }
546
547 if (!list.isEmpty() && wasFirstNetwork) {
548 if (DBG) log("Other network available for type " + type +
549 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900550 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700551 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
552 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553 }
554 }
555
556 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900557 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
558 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900560 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
562 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700563
Robert Greenwalt8d482522015-06-24 13:23:42 -0700564 // send out another legacy broadcast - currently only used for suspend/unsuspend
565 // toggle
566 public void update(NetworkAgentInfo nai) {
567 final boolean isDefault = isDefaultNetwork(nai);
568 final DetailedState state = nai.networkInfo.getDetailedState();
569 for (int type = 0; type < mTypeLists.length; type++) {
570 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700571 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700572 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700573 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 maybeLogBroadcast(nai, state, type, isDefault);
575 sendLegacyNetworkBroadcast(nai, state, type);
576 }
577 }
578 }
579
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 private String naiToString(NetworkAgentInfo nai) {
581 String name = (nai != null) ? nai.name() : "null";
582 String state = (nai.networkInfo != null) ?
583 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
584 "???/???";
585 return name + " " + state;
586 }
587
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700588 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900589 pw.println("mLegacyTypeTracker:");
590 pw.increaseIndent();
591 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700592 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900593 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700594 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900595 pw.println();
596 pw.println("Current state:");
597 pw.increaseIndent();
598 for (int type = 0; type < mTypeLists.length; type++) {
599 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
600 for (NetworkAgentInfo nai : mTypeLists[type]) {
601 pw.println(type + " " + naiToString(nai));
602 }
603 }
604 pw.decreaseIndent();
605 pw.decreaseIndent();
606 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700607 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608
609 // This class needs its own log method because it has a different TAG.
610 private void log(String s) {
611 Slog.d(TAG, s);
612 }
613
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700614 }
615 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
616
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900617 @VisibleForTesting
618 protected HandlerThread createHandlerThread() {
619 return new HandlerThread("ConnectivityServiceThread");
620 }
621
Jeff Sharkey899223b2012-08-04 15:24:58 -0700622 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700623 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800624 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800625
Erik Klineda4bfa82015-04-30 12:58:40 +0900626 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900627 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
628 new Binder(), NetworkRequestInfo.REQUEST);
629 mNetworkRequests.put(mDefaultRequest, defaultNRI);
630 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900631
632 mDefaultMobileDataRequest = createInternetRequestForTransport(
633 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700634
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900635 mHandlerThread = createHandlerThread();
636 mHandlerThread.start();
637 mHandler = new InternalHandler(mHandlerThread.getLooper());
638 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700639
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800640 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800641 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
642 String id = Settings.Secure.getString(context.getContentResolver(),
643 Settings.Secure.ANDROID_ID);
644 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700645 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800646 SystemProperties.set("net.hostname", name);
647 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800648 }
649
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700650 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700651 String dns = Settings.Global.getString(context.getContentResolver(),
652 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700653 if (dns == null || dns.length() == 0) {
654 dns = context.getResources().getString(
655 com.android.internal.R.string.config_default_dns_server);
656 }
657 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800658 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
659 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800660 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700661 }
662
Jeremy Joslin79294842014-12-03 17:15:28 -0800663 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
664 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
665
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700666 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700667 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800668 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700669 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700670 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700671 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700672
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700673 try {
674 mPolicyManager.registerListener(mPolicyListener);
675 } catch (RemoteException e) {
676 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700677 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700678 }
679
680 final PowerManager powerManager = (PowerManager) context.getSystemService(
681 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700682 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
683 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
684 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800685 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700686
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700687 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700688
Wink Saville51f456f2013-04-23 14:26:51 -0700689 // TODO: What is the "correct" way to do determine if this is a wifi only device?
690 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
691 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700692 String[] naStrings = context.getResources().getStringArray(
693 com.android.internal.R.array.networkAttributes);
694 for (String naString : naStrings) {
695 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700696 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700697 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700698 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800699 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700700 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700701 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700702 }
Wink Saville51f456f2013-04-23 14:26:51 -0700703 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
704 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
705 n.type);
706 continue;
707 }
Wink Saville975c8482011-04-07 14:23:45 -0700708 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800709 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700710 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700711 continue;
712 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700713 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700714
Wink Saville975c8482011-04-07 14:23:45 -0700715 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700716 mNetworksDefined++;
717 } catch(Exception e) {
718 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700719 }
720 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700721
722 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
723 if (mNetConfigs[TYPE_VPN] == null) {
724 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
725 // don't need to add TYPE_VPN to mNetConfigs.
726 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
727 mNetworksDefined++; // used only in the log() statement below.
728 }
729
Wink Saville5e56bc52013-07-29 15:00:57 -0700730 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700731
Robert Greenwalt50393202011-06-21 17:26:14 -0700732 mProtectedNetworks = new ArrayList<Integer>();
733 int[] protectedNetworks = context.getResources().getIntArray(
734 com.android.internal.R.array.config_protectedNetworks);
735 for (int p : protectedNetworks) {
736 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
737 mProtectedNetworks.add(p);
738 } else {
739 if (DBG) loge("Ignoring protectedNetwork " + p);
740 }
741 }
742
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700743 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
744 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700745
Robert Greenwaltfab501672014-07-23 11:44:01 -0700746 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800747
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700748 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
749
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700750 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700751 IntentFilter intentFilter = new IntentFilter();
752 intentFilter.addAction(Intent.ACTION_USER_STARTING);
753 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700754 intentFilter.addAction(Intent.ACTION_USER_ADDED);
755 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee9a5f4852015-12-17 11:42:22 +0000756 intentFilter.addAction(Intent.ACTION_USER_PRESENT);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700757 mContext.registerReceiverAsUser(
758 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900759
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700760 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700761 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700762 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700763 } catch (RemoteException e) {
764 loge("Error registering observer :" + e);
765 }
766
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700767 if (DBG) {
768 mInetLog = new ArrayList();
769 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700770
Erik Klineda4bfa82015-04-30 12:58:40 +0900771 mSettingsObserver = new SettingsObserver(mContext, mHandler);
772 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800773
John Spurlockbf991a82013-06-24 14:20:23 -0400774 mDataConnectionStats = new DataConnectionStats(mContext);
775 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400776
Jason Monkdecd2952013-10-10 14:02:51 -0400777 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700778
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400779 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900780
781 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800782 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700783
Erik Klineda4bfa82015-04-30 12:58:40 +0900784 private NetworkRequest createInternetRequestForTransport(int transportType) {
785 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900786 netCap.addCapability(NET_CAPABILITY_INTERNET);
787 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900788 if (transportType > -1) {
789 netCap.addTransportType(transportType);
790 }
791 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
792 }
793
794 private void handleMobileDataAlwaysOn() {
795 final boolean enable = (Settings.Global.getInt(
796 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
797 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
798 if (enable == isEnabled) {
799 return; // Nothing to do.
800 }
801
802 if (enable) {
803 handleRegisterNetworkRequest(new NetworkRequestInfo(
804 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
805 } else {
806 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
807 }
808 }
809
810 private void registerSettingsCallbacks() {
811 // Watch for global HTTP proxy changes.
812 mSettingsObserver.observe(
813 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
814 EVENT_APPLY_GLOBAL_HTTP_PROXY);
815
816 // Watch for whether or not to keep mobile data always on.
817 mSettingsObserver.observe(
818 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
819 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
820 }
821
Robert Greenwalt34524f02014-05-18 16:22:10 -0700822 private synchronized int nextNetworkRequestId() {
823 return mNextNetworkRequestId++;
824 }
825
Paul Jensen67b0b072015-06-10 11:22:17 -0400826 @VisibleForTesting
827 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400828 synchronized (mNetworkForNetId) {
829 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
830 int netId = mNextNetId;
831 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
832 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500833 if (!mNetIdInUse.get(netId)) {
834 mNetIdInUse.put(netId, true);
835 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400836 }
837 }
838 }
839 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700840 }
841
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800842 private NetworkState getFilteredNetworkState(int networkType, int uid) {
843 NetworkInfo info = null;
844 LinkProperties lp = null;
845 NetworkCapabilities nc = null;
846 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800847 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800848
849 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
850 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
851 if (nai != null) {
852 synchronized (nai) {
853 info = new NetworkInfo(nai.networkInfo);
854 lp = new LinkProperties(nai.linkProperties);
855 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400856 // Network objects are outwardly immutable so there is no point to duplicating.
857 // Duplicating also precludes sharing socket factories and connection pools.
858 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800859 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800860 }
861 info.setType(networkType);
862 } else {
863 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
864 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
865 info.setIsAvailable(true);
866 lp = new LinkProperties();
867 nc = new NetworkCapabilities();
868 network = null;
869 }
870 info = getFilteredNetworkInfo(info, lp, uid);
871 }
872
Jeff Sharkey32566012014-12-02 18:30:14 -0800873 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400874 }
875
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800876 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
877 if (network == null) {
878 return null;
879 }
880 synchronized (mNetworkForNetId) {
881 return mNetworkForNetId.get(network.netId);
882 }
883 };
884
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900885 private Network[] getVpnUnderlyingNetworks(int uid) {
886 if (!mLockdownEnabled) {
887 int user = UserHandle.getUserId(uid);
888 synchronized (mVpns) {
889 Vpn vpn = mVpns.get(user);
890 if (vpn != null && vpn.appliesToUid(uid)) {
891 return vpn.getUnderlyingNetworks();
892 }
893 }
894 }
895 return null;
896 }
897
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800898 private NetworkState getUnfilteredActiveNetworkState(int uid) {
899 NetworkInfo info = null;
900 LinkProperties lp = null;
901 NetworkCapabilities nc = null;
902 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800903 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800904
Paul Jensen85cf78e2015-06-25 13:25:07 -0400905 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800906
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900907 final Network[] networks = getVpnUnderlyingNetworks(uid);
908 if (networks != null) {
909 // getUnderlyingNetworks() returns:
910 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
911 // empty array => the VPN explicitly said "no default network".
912 // non-empty array => the VPN specified one or more default networks; we use the
913 // first one.
914 if (networks.length > 0) {
915 nai = getNetworkAgentInfoForNetwork(networks[0]);
916 } else {
917 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800918 }
919 }
920
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800921 if (nai != null) {
922 synchronized (nai) {
923 info = new NetworkInfo(nai.networkInfo);
924 lp = new LinkProperties(nai.linkProperties);
925 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400926 // Network objects are outwardly immutable so there is no point to duplicating.
927 // Duplicating also precludes sharing socket factories and connection pools.
928 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800929 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800930 }
931 }
932
Jeff Sharkey32566012014-12-02 18:30:14 -0800933 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400934 }
935
936 /**
937 * Check if UID should be blocked from using the network with the given LinkProperties.
938 */
939 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700940 final boolean networkCostly;
941 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700942
Robert Greenwalt12e67352014-05-13 21:41:06 -0700943 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700944 synchronized (mRulesLock) {
945 networkCostly = mMeteredIfaces.contains(iface);
946 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700947 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700948
Jeff Sharkeydc988062015-09-14 10:09:47 -0700949 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700950 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700951 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
952 return true;
953 } else {
954 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700955 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700956 }
957
958 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700959 * Return a filtered {@link NetworkInfo}, potentially marked
960 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800961 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700962 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800963 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
964 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400965 // network is blocked; clone and override state
966 info = new NetworkInfo(info);
967 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900968 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900969 log("returning Blocked NetworkInfo for ifname=" +
970 lp.getInterfaceName() + ", uid=" + uid);
971 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700972 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800973 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700974 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900975 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700976 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700977 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700978 }
979
980 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800981 * Return NetworkInfo for the active (i.e., connected) network interface.
982 * It is assumed that at most one network is active at a time. If more
983 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700984 * @return the info for the active network, or {@code null} if none is
985 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800986 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700987 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700989 enforceAccessPermission();
990 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800991 NetworkState state = getUnfilteredActiveNetworkState(uid);
992 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 }
994
Paul Jensen31a94f42015-02-13 14:18:39 -0500995 @Override
996 public Network getActiveNetwork() {
997 enforceAccessPermission();
998 final int uid = Binder.getCallingUid();
999 final int user = UserHandle.getUserId(uid);
1000 int vpnNetId = NETID_UNSET;
1001 synchronized (mVpns) {
1002 final Vpn vpn = mVpns.get(user);
1003 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1004 }
1005 NetworkAgentInfo nai;
1006 if (vpnNetId != NETID_UNSET) {
1007 synchronized (mNetworkForNetId) {
1008 nai = mNetworkForNetId.get(vpnNetId);
1009 }
1010 if (nai != null) return nai.network;
1011 }
1012 nai = getDefaultNetwork();
1013 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1014 return nai != null ? nai.network : null;
1015 }
1016
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001017 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1018 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001019 final int uid = Binder.getCallingUid();
1020 NetworkState state = getUnfilteredActiveNetworkState(uid);
1021 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001022 }
1023
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001024 @Override
1025 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1026 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001027 NetworkState state = getUnfilteredActiveNetworkState(uid);
1028 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001029 }
1030
1031 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001032 public NetworkInfo getNetworkInfo(int networkType) {
1033 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001034 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001035 if (getVpnUnderlyingNetworks(uid) != null) {
1036 // A VPN is active, so we may need to return one of its underlying networks. This
1037 // information is not available in LegacyTypeTracker, so we have to get it from
1038 // getUnfilteredActiveNetworkState.
1039 NetworkState state = getUnfilteredActiveNetworkState(uid);
1040 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1041 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1042 }
1043 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001044 NetworkState state = getFilteredNetworkState(networkType, uid);
1045 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 }
1047
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001048 @Override
1049 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1050 enforceAccessPermission();
1051 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001053 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1054 if (nai != null) {
1055 synchronized (nai) {
1056 info = new NetworkInfo(nai.networkInfo);
1057 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001058 }
1059 }
1060 return info;
1061 }
1062
1063 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001064 public NetworkInfo[] getAllNetworkInfo() {
1065 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001066 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001067 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1068 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001069 NetworkInfo info = getNetworkInfo(networkType);
1070 if (info != null) {
1071 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001072 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001074 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
1076
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001077 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001078 public Network getNetworkForType(int networkType) {
1079 enforceAccessPermission();
1080 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001081 NetworkState state = getFilteredNetworkState(networkType, uid);
1082 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1083 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001084 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001085 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001086 }
1087
1088 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001089 public Network[] getAllNetworks() {
1090 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001091 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001092 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001093 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001094 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001095 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001096 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001097 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001098 }
1099
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001100 @Override
1101 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1102 // The basic principle is: if an app's traffic could possibly go over a
1103 // network, without the app doing anything multinetwork-specific,
1104 // (hence, by "default"), then include that network's capabilities in
1105 // the array.
1106 //
1107 // In the normal case, app traffic only goes over the system's default
1108 // network connection, so that's the only network returned.
1109 //
1110 // With a VPN in force, some app traffic may go into the VPN, and thus
1111 // over whatever underlying networks the VPN specifies, while other app
1112 // traffic may go over the system default network (e.g.: a split-tunnel
1113 // VPN, or an app disallowed by the VPN), so the set of networks
1114 // returned includes the VPN's underlying networks and the system
1115 // default.
1116 enforceAccessPermission();
1117
1118 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1119
1120 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001121 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001122 if (nc != null) {
1123 result.put(nai.network, nc);
1124 }
1125
1126 if (!mLockdownEnabled) {
1127 synchronized (mVpns) {
1128 Vpn vpn = mVpns.get(userId);
1129 if (vpn != null) {
1130 Network[] networks = vpn.getUnderlyingNetworks();
1131 if (networks != null) {
1132 for (Network network : networks) {
1133 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001134 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001135 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001136 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001137 }
1138 }
1139 }
1140 }
1141 }
1142 }
1143
1144 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1145 out = result.values().toArray(out);
1146 return out;
1147 }
1148
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001149 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001150 public boolean isNetworkSupported(int networkType) {
1151 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001153 }
1154
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001155 /**
1156 * Return LinkProperties for the active (i.e., connected) default
1157 * network interface. It is assumed that at most one default network
1158 * is active at a time. If more than one is active, it is indeterminate
1159 * which will be returned.
1160 * @return the ip properties for the active network, or {@code null} if
1161 * none is active
1162 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001164 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 enforceAccessPermission();
1166 final int uid = Binder.getCallingUid();
1167 NetworkState state = getUnfilteredActiveNetworkState(uid);
1168 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001169 }
1170
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001171 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001172 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001173 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1175 if (nai != null) {
1176 synchronized (nai) {
1177 return new LinkProperties(nai.linkProperties);
1178 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001179 }
1180 return null;
1181 }
1182
Robert Greenwalt12e67352014-05-13 21:41:06 -07001183 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001184 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001185 public LinkProperties getLinkProperties(Network network) {
1186 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001188 if (nai != null) {
1189 synchronized (nai) {
1190 return new LinkProperties(nai.linkProperties);
1191 }
1192 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001193 return null;
1194 }
1195
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001196 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001197 if (nai != null) {
1198 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001199 if (nai.networkCapabilities != null) {
1200 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001201 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001202 }
1203 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001204 return null;
1205 }
1206
1207 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001208 public NetworkCapabilities getNetworkCapabilities(Network network) {
1209 enforceAccessPermission();
1210 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1211 }
1212
1213 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001214 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001215 // Require internal since we're handing out IMSI details
1216 enforceConnectivityInternalPermission();
1217
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001218 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001219 for (Network network : getAllNetworks()) {
1220 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1221 if (nai != null) {
1222 synchronized (nai) {
1223 final String subscriberId = (nai.networkMisc != null)
1224 ? nai.networkMisc.subscriberId : null;
1225 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1226 nai.networkCapabilities, network, subscriberId, null));
1227 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001228 }
1229 }
1230 return result.toArray(new NetworkState[result.size()]);
1231 }
1232
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001233 @Override
1234 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1235 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001237 final long token = Binder.clearCallingIdentity();
1238 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1240 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001241 try {
1242 return mPolicyManager.getNetworkQuotaInfo(state);
1243 } catch (RemoteException e) {
1244 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001245 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001246 return null;
1247 } finally {
1248 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001249 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001250 }
1251
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001252 @Override
1253 public boolean isActiveNetworkMetered() {
1254 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001255 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001256 final long token = Binder.clearCallingIdentity();
1257 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001258 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001259 } finally {
1260 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001261 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001262 }
1263
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001264 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1265 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1266 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001267 try {
1268 return mPolicyManager.isNetworkMetered(state);
1269 } catch (RemoteException e) {
1270 }
1271 }
1272 return false;
1273 }
1274
Jeff Sharkey216c1812012-08-05 14:29:23 -07001275 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1276 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001277 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001278 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001279 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001280 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001281 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001282
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001283 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001284 * Ensure that a network route exists to deliver traffic to the specified
1285 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001286 * @param networkType the type of the network over which traffic to the
1287 * specified host is to be routed
1288 * @param hostAddress the IP address of the host to which the route is
1289 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 * @return {@code true} on success, {@code false} on failure
1291 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001292 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001293 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001294 if (mProtectedNetworks.contains(networkType)) {
1295 enforceConnectivityInternalPermission();
1296 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001297
Chad Brubakerc0234532014-02-14 13:24:29 -08001298 InetAddress addr;
1299 try {
1300 addr = InetAddress.getByAddress(hostAddress);
1301 } catch (UnknownHostException e) {
1302 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1303 return false;
1304 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001305
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001306 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001307 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 return false;
1309 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001310
1311 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1312 if (nai == null) {
1313 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1314 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1315 } else {
1316 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1317 }
1318 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001319 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001320
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001321 DetailedState netState;
1322 synchronized (nai) {
1323 netState = nai.networkInfo.getDetailedState();
1324 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001325
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001326 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001327 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001328 log("requestRouteToHostAddress on down network "
1329 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001330 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001331 }
1332 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001333 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001334
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001335 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001336 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001337 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001338 LinkProperties lp;
1339 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001340 synchronized (nai) {
1341 lp = nai.linkProperties;
1342 netId = nai.network.netId;
1343 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001344 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001345 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1346 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001347 } finally {
1348 Binder.restoreCallingIdentity(token);
1349 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001350 }
1351
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001352 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001353 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001354 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001355 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001356 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001357 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001358 if (bestRoute.getGateway().equals(addr)) {
1359 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001360 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001361 } else {
1362 // if we will connect to this through another route, add a direct route
1363 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001364 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001365 }
1366 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001367 if (DBG) log("Adding legacy route " + bestRoute +
1368 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001369 try {
1370 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1371 } catch (Exception e) {
1372 // never crash - catch them all
1373 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001374 return false;
1375 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001376 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 }
1378
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001379 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1380 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001381 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001382 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001383 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001384 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001385 }
1386
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001387 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001388 // skip update when we've already applied rules
1389 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1390 if (oldRules == uidRules) return;
1391
1392 mUidRules.put(uid, uidRules);
1393 }
1394
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001395 // TODO: notify UID when it has requested targeted updates
1396 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001397
1398 @Override
1399 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001400 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001401 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001402 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001403 }
1404
1405 synchronized (mRulesLock) {
1406 mMeteredIfaces.clear();
1407 for (String iface : meteredIfaces) {
1408 mMeteredIfaces.add(iface);
1409 }
1410 }
1411 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001412
1413 @Override
1414 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1415 // caller is NPMS, since we only register with them
1416 if (LOGD_RULES) {
1417 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1418 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001419 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001420 };
1421
Robin Lee3b3dd942015-05-12 18:14:58 +01001422 /**
1423 * Require that the caller is either in the same user or has appropriate permission to interact
1424 * across users.
1425 *
1426 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1427 */
1428 private void enforceCrossUserPermission(int userId) {
1429 if (userId == UserHandle.getCallingUserId()) {
1430 // Not a cross-user call.
1431 return;
1432 }
1433 mContext.enforceCallingOrSelfPermission(
1434 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1435 "ConnectivityService");
1436 }
1437
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001438 private void enforceInternetPermission() {
1439 mContext.enforceCallingOrSelfPermission(
1440 android.Manifest.permission.INTERNET,
1441 "ConnectivityService");
1442 }
1443
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001444 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001445 mContext.enforceCallingOrSelfPermission(
1446 android.Manifest.permission.ACCESS_NETWORK_STATE,
1447 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 }
1449
1450 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001451 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001452 }
1453
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001454 private void enforceTetherAccessPermission() {
1455 mContext.enforceCallingOrSelfPermission(
1456 android.Manifest.permission.ACCESS_NETWORK_STATE,
1457 "ConnectivityService");
1458 }
1459
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001460 private void enforceConnectivityInternalPermission() {
1461 mContext.enforceCallingOrSelfPermission(
1462 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1463 "ConnectivityService");
1464 }
1465
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001466 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001467 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001468 }
1469
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001470 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001471 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001472 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001473 }
1474
1475 private void sendInetConditionBroadcast(NetworkInfo info) {
1476 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1477 }
1478
Wink Saville628b0852011-08-04 15:01:58 -07001479 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001480 if (mLockdownTracker != null) {
1481 info = mLockdownTracker.augmentNetworkInfo(info);
1482 }
1483
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001484 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001485 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001486 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 if (info.isFailover()) {
1488 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1489 info.setFailover(false);
1490 }
1491 if (info.getReason() != null) {
1492 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1493 }
1494 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001495 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1496 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001498 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001499 return intent;
1500 }
1501
1502 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1503 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1504 }
1505
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001506 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001507 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1508 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1509 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001510 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001511 final long ident = Binder.clearCallingIdentity();
1512 try {
1513 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1514 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1515 } finally {
1516 Binder.restoreCallingIdentity(ident);
1517 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001518 }
1519
Mike Lockwood0f79b542009-08-14 14:18:49 -04001520 private void sendStickyBroadcast(Intent intent) {
1521 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001522 if (!mSystemReady) {
1523 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001524 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001525 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001526 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001527 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001528 }
1529
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001530 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001531 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001532 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001533 final NetworkInfo ni = intent.getParcelableExtra(
1534 ConnectivityManager.EXTRA_NETWORK_INFO);
1535 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1536 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1537 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001538 } else {
1539 BroadcastOptions opts = BroadcastOptions.makeBasic();
1540 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1541 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001542 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001543 final IBatteryStats bs = BatteryStatsService.getService();
1544 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001545 bs.noteConnectivityChanged(intent.getIntExtra(
1546 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1547 ni != null ? ni.getState().toString() : "?");
1548 } catch (RemoteException e) {
1549 }
1550 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001551 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001552 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001553 } finally {
1554 Binder.restoreCallingIdentity(ident);
1555 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001556 }
1557 }
1558
1559 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001560 loadGlobalProxy();
1561
Mike Lockwood0f79b542009-08-14 14:18:49 -04001562 synchronized(this) {
1563 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001564 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001565 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001566 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001567 }
1568 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001569 // load the global proxy at startup
1570 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001571
Robin Lee244ce8e2016-01-05 18:03:46 +00001572 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1573 // for user to unlock device too.
1574 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001575
Erik Klineda4bfa82015-04-30 12:58:40 +09001576 // Configure whether mobile data is always on.
1577 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1578
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001579 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001580
1581 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001582 }
1583
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001585 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001586 *
1587 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001588 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001589 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001590 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1591 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001592
1593 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001594 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001595
Robert Greenwalt7b816022014-04-18 15:25:25 -07001596 if (networkAgent.networkCapabilities.hasTransport(
1597 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001598 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1599 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001600 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001601 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001602 } else if (networkAgent.networkCapabilities.hasTransport(
1603 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001604 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1605 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001606 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001607 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001608 } else {
1609 // do not track any other networks
1610 timeout = 0;
1611 }
1612
Robert Greenwalt7b816022014-04-18 15:25:25 -07001613 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001614 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001615 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001616 } catch (Exception e) {
1617 // You shall not crash!
1618 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001619 }
1620 }
1621 }
1622
1623 /**
1624 * Remove data activity tracking when network disconnects.
1625 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001626 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1627 final String iface = networkAgent.linkProperties.getInterfaceName();
1628 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001629
Robert Greenwalt7b816022014-04-18 15:25:25 -07001630 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1631 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001632 try {
1633 // the call fails silently if no idletimer setup for this interface
1634 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001635 } catch (Exception e) {
1636 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001637 }
1638 }
1639 }
1640
1641 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001642 * Reads the network specific MTU size from reources.
1643 * and set it on it's iface.
1644 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1646 final String iface = newLp.getInterfaceName();
1647 final int mtu = newLp.getMtu();
1648 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1649 if (VDBG) log("identical MTU - not setting");
1650 return;
1651 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001652
Robert Greenwalt43074032014-08-15 17:53:05 -07001653 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001654 loge("Unexpected mtu value: " + mtu + ", " + iface);
1655 return;
1656 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001657
w1997615afd812014-08-05 15:18:11 -07001658 // Cannot set MTU without interface name
1659 if (TextUtils.isEmpty(iface)) {
1660 loge("Setting MTU size with null iface.");
1661 return;
1662 }
1663
Robert Greenwalt7b816022014-04-18 15:25:25 -07001664 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001665 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001666 mNetd.setMtu(iface, mtu);
1667 } catch (Exception e) {
1668 Slog.e(TAG, "exception in setMtu()" + e);
1669 }
1670 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001671
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001672 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001673 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1674
1675 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001676 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001677 protected int getDefaultTcpRwnd() {
1678 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1679 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001680
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001681 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1682 if (isDefaultNetwork(nai) == false) {
1683 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001684 }
1685
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001686 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1687 String[] values = null;
1688 if (tcpBufferSizes != null) {
1689 values = tcpBufferSizes.split(",");
1690 }
1691
1692 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001693 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001694 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1695 values = tcpBufferSizes.split(",");
1696 }
1697
1698 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1699
1700 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001701 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001702
1703 final String prefix = "/sys/kernel/ipv4/tcp_";
1704 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1705 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1706 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1707 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1708 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1709 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1710 mCurrentTcpBufferSizes = tcpBufferSizes;
1711 } catch (IOException e) {
1712 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001713 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001714
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001715 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001716 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001717 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1718 if (rwndValue != 0) {
1719 SystemProperties.set(sysctlKey, rwndValue.toString());
1720 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001721 }
1722
Mattias Falk8b47b362011-08-23 14:15:13 +02001723 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001724 /*
1725 * Tell the VMs to toss their DNS caches
1726 */
1727 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1728 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001729 /*
1730 * Connectivity events can happen before boot has completed ...
1731 */
1732 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001733 final long ident = Binder.clearCallingIdentity();
1734 try {
1735 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1736 } finally {
1737 Binder.restoreCallingIdentity(ident);
1738 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001739 }
1740
Robert Greenwalt562cc542014-05-15 18:07:26 -07001741 @Override
1742 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001743 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1744 NETWORK_RESTORE_DELAY_PROP_NAME);
1745 if(restoreDefaultNetworkDelayStr != null &&
1746 restoreDefaultNetworkDelayStr.length() != 0) {
1747 try {
1748 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1749 } catch (NumberFormatException e) {
1750 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001752 // if the system property isn't set, use the value for the apn type
1753 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1754
1755 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1756 (mNetConfigs[networkType] != null)) {
1757 ret = mNetConfigs[networkType].restoreTime;
1758 }
1759 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001760 }
1761
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001762 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001763 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001764 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001765 }
1766 return false;
1767 }
1768
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001770 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1771 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001772 if (mContext.checkCallingOrSelfPermission(
1773 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001775 pw.println("Permission Denial: can't dump ConnectivityService " +
1776 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1777 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 return;
1779 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001780
Erik Kline379747a2015-06-05 17:47:34 +09001781 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001782 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001783 final long DIAG_TIME_MS = 5000;
1784 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1785 // Start gathering diagnostic information.
1786 netDiags.add(new NetworkDiagnostics(
1787 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001788 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001789 DIAG_TIME_MS));
1790 }
1791
1792 for (NetworkDiagnostics netDiag : netDiags) {
1793 pw.println();
1794 netDiag.waitForMeasurements();
1795 netDiag.dump(pw);
1796 }
1797
1798 return;
1799 }
1800
Lorenzo Colittie3805462015-06-03 11:18:24 +09001801 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001802 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001803 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001804 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001805 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001806 pw.println();
1807
Paul Jensen85cf78e2015-06-25 13:25:07 -04001808 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001809 pw.print("Active default network: ");
1810 if (defaultNai == null) {
1811 pw.println("none");
1812 } else {
1813 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001815 pw.println();
1816
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001817 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001818 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001819 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1820 pw.println(nai.toString());
1821 pw.increaseIndent();
1822 pw.println("Requests:");
1823 pw.increaseIndent();
1824 for (int i = 0; i < nai.networkRequests.size(); i++) {
1825 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001826 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001827 pw.decreaseIndent();
1828 pw.println("Lingered:");
1829 pw.increaseIndent();
1830 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1831 pw.decreaseIndent();
1832 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001833 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001834 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001835 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001836
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001837 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001838 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001839 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1840 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001841 }
1842 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001843 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001844
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001845 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001846
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001847 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001848 pw.print("mNetTransitionWakeLock: currently " +
1849 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1850 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1851 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1852 } else {
1853 pw.println(", last requested never");
1854 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001855 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001856
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001857 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001858 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001859
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001860 pw.println();
1861 mKeepaliveTracker.dump(pw);
1862
Lorenzo Colittie3805462015-06-03 11:18:24 +09001863 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001864 pw.println();
1865 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001866 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001867 for(int i = 0; i < mInetLog.size(); i++) {
1868 pw.println(mInetLog.get(i));
1869 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001870 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001871 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001872
1873 if (argsContain(args, "--short") == false) {
1874 pw.println();
1875 synchronized (mValidationLogs) {
1876 pw.println("mValidationLogs (most recent first):");
1877 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1878 pw.println(p.first);
1879 pw.increaseIndent();
1880 p.second.dump(fd, pw, args);
1881 pw.decreaseIndent();
1882 }
1883 }
Erik Kline7523eb32015-07-09 18:24:03 +09001884
1885 pw.println();
1886 pw.println("mNetworkRequestInfoLogs (most recent first):");
1887 pw.increaseIndent();
1888 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1889 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001890 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001891 }
1892
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001893 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001894 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001895 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001896 if (officialNai != null && officialNai.equals(nai)) return true;
1897 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001898 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001899 " - " + nai);
1900 }
1901 return false;
1902 }
1903
Paul Jensenc8b9a742014-09-30 15:37:41 -04001904 private boolean isRequest(NetworkRequest request) {
1905 return mNetworkRequests.get(request).isRequest;
1906 }
1907
Robert Greenwalt42acef32009-08-12 16:08:25 -07001908 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001909 private class NetworkStateTrackerHandler extends Handler {
1910 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001911 super(looper);
1912 }
1913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001914 @Override
1915 public void handleMessage(Message msg) {
1916 NetworkInfo info;
1917 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001918 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001919 handleAsyncChannelHalfConnect(msg);
1920 break;
1921 }
1922 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1923 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1924 if (nai != null) nai.asyncChannel.disconnect();
1925 break;
1926 }
1927 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1928 handleAsyncChannelDisconnected(msg);
1929 break;
1930 }
1931 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1932 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1933 if (nai == null) {
1934 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1935 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001936 final NetworkCapabilities networkCapabilities =
1937 (NetworkCapabilities)msg.obj;
1938 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1939 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001940 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001941 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001942 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1943 networkCapabilities)) {
1944 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1945 + nai.networkCapabilities + " -> " + networkCapabilities);
1946 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001947 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001948 }
1949 break;
1950 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001951 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1952 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1953 if (nai == null) {
1954 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1955 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001956 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001957 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001958 "; created=" + nai.created);
1959 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001960 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001961 synchronized (nai) {
1962 nai.linkProperties = (LinkProperties)msg.obj;
1963 }
Paul Jenseneec75412014-08-04 12:21:19 -04001964 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001965 }
1966 break;
1967 }
1968 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1969 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1970 if (nai == null) {
1971 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1972 break;
1973 }
1974 info = (NetworkInfo) msg.obj;
1975 updateNetworkInfo(nai, info);
1976 break;
1977 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001978 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1979 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1980 if (nai == null) {
1981 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1982 break;
1983 }
1984 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001985 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001986 break;
1987 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001988 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1989 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1990 if (nai == null) {
1991 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1992 break;
1993 }
1994 try {
1995 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001996 } catch (Exception e) {
1997 // Never crash!
1998 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001999 }
2000 break;
2001 }
2002 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2003 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2004 if (nai == null) {
2005 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2006 break;
2007 }
2008 try {
2009 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002010 } catch (Exception e) {
2011 // Never crash!
2012 loge("Exception in removeVpnUidRanges: " + e);
2013 }
2014 break;
2015 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002016 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2017 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2018 if (nai == null) {
2019 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2020 break;
2021 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002022 if (nai.created && !nai.networkMisc.explicitlySelected) {
2023 loge("ERROR: created network explicitly selected.");
2024 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002025 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002026 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002027 break;
2028 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002029 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2030 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2031 if (nai == null) {
2032 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2033 break;
2034 }
2035 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2036 break;
2037 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002038 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002039 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002040 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2041 final boolean valid =
2042 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002043 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2044 if (valid != nai.lastValidated) {
2045 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002046 nai.lastValidated = valid;
2047 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002048 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002049 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2050 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002051 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002052 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002053 // Let the NetworkAgent know the state of its network
2054 nai.asyncChannel.sendMessage(
2055 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2056 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2057 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002058 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002059 break;
2060 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002061 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002062 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002063 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2064 handleLingerComplete(nai);
2065 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002066 break;
2067 }
Paul Jensen869868be2014-05-15 10:33:05 -04002068 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002069 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002070 final boolean visible = (msg.arg1 != 0);
2071 final NetworkAgentInfo nai;
2072 synchronized (mNetworkForNetId) {
2073 nai = mNetworkForNetId.get(netId);
2074 }
2075 // If captive portal status has changed, update capabilities.
2076 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2077 nai.lastCaptivePortalDetected = visible;
2078 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002079 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002080 }
2081 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002082 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002083 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002084 if (nai == null) {
2085 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2086 break;
2087 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002088 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002089 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2090 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002091 }
Paul Jensen869868be2014-05-15 10:33:05 -04002092 break;
2093 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002094 }
2095 }
2096 }
2097
Paul Jensen85cf78e2015-06-25 13:25:07 -04002098 private void linger(NetworkAgentInfo nai) {
2099 nai.lingering = true;
2100 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2101 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2102 }
2103
Paul Jensen0cc17322014-11-25 15:26:53 -05002104 // Cancel any lingering so the linger timeout doesn't teardown a network.
2105 // This should be called when a network begins satisfying a NetworkRequest.
2106 // Note: depending on what state the NetworkMonitor is in (e.g.,
2107 // if it's awaiting captive portal login, or if validation failed), this
2108 // may trigger a re-evaluation of the network.
2109 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002110 nai.networkLingered.clear();
2111 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002112 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002113 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002114 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2115 }
2116
Robert Greenwalt7b816022014-04-18 15:25:25 -07002117 private void handleAsyncChannelHalfConnect(Message msg) {
2118 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002119 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002120 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2121 if (VDBG) log("NetworkFactory connected");
2122 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002123 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002124 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002125 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002126 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002127 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 }
2129 } else {
2130 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002131 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 }
2133 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2134 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2135 if (VDBG) log("NetworkAgent connected");
2136 // A network agent has requested a connection. Establish the connection.
2137 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2138 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2139 } else {
2140 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002141 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002142 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002143 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002144 synchronized (mNetworkForNetId) {
2145 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002146 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002147 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002148 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002149 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002150 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002151 }
2152 }
2153 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002154
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 private void handleAsyncChannelDisconnected(Message msg) {
2156 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2157 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002158 if (DBG) {
2159 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2160 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002161 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002162 // TODO - if we move the logic to the network agent (have them disconnect
2163 // because they lost all their requests or because their score isn't good)
2164 // then they would disconnect organically, report their new state and then
2165 // disconnect the channel.
2166 if (nai.networkInfo.isConnected()) {
2167 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2168 null, null);
2169 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002170 final boolean wasDefault = isDefaultNetwork(nai);
2171 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002172 mDefaultInetConditionPublished = 0;
2173 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002174 notifyIfacesChanged();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002175 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2176 // by other networks that are already connected. Perhaps that can be done by
2177 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2178 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002179 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002180 mKeepaliveTracker.handleStopAllKeepalives(nai,
2181 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002182 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002183 mNetworkAgentInfos.remove(msg.replyTo);
2184 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002185 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002186 // Remove the NetworkAgent, but don't mark the netId as
2187 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002188 mNetworkForNetId.remove(nai.network.netId);
2189 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002190 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002191 for (int i = 0; i < nai.networkRequests.size(); i++) {
2192 NetworkRequest request = nai.networkRequests.valueAt(i);
2193 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2194 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2195 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002196 sendUpdatedScoreToFactories(request, 0);
2197 }
2198 }
2199 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2200 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002201 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002202 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002203 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002204 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002205 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002206 if (nai.created) {
2207 // Tell netd to clean up the configuration for this network
2208 // (routing rules, DNS, etc).
2209 // This may be slow as it requires a lot of netd shelling out to ip and
2210 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2211 // after we've rematched networks with requests which should make a potential
2212 // fallback network the default or requested a new network from the
2213 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2214 // long time.
2215 try {
2216 mNetd.removeNetwork(nai.network.netId);
2217 } catch (Exception e) {
2218 loge("Exception removing network: " + e);
2219 }
2220 }
2221 synchronized (mNetworkForNetId) {
2222 mNetIdInUse.delete(nai.network.netId);
2223 }
2224 } else {
2225 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2226 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002227 }
2228 }
2229
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002230 // If this method proves to be too slow then we can maintain a separate
2231 // pendingIntent => NetworkRequestInfo map.
2232 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2233 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2234 Intent intent = pendingIntent.getIntent();
2235 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2236 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2237 if (existingPendingIntent != null &&
2238 existingPendingIntent.getIntent().filterEquals(intent)) {
2239 return entry.getValue();
2240 }
2241 }
2242 return null;
2243 }
2244
2245 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2246 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2247
2248 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2249 if (existingRequest != null) { // remove the existing request.
2250 if (DBG) log("Replacing " + existingRequest.request + " with "
2251 + nri.request + " because their intents matched.");
2252 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2253 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002254 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002255 }
2256
Erik Klineda4bfa82015-04-30 12:58:40 +09002257 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002258 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002259 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002260 if (!nri.isRequest) {
2261 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002262 if (nri.request.networkCapabilities.hasSignalStrength() &&
2263 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2264 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002265 }
2266 }
2267 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002268 rematchAllNetworksAndRequests(null, 0);
2269 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2270 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002271 }
2272 }
2273
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002274 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2275 int callingUid) {
2276 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2277 if (nri != null) {
2278 handleReleaseNetworkRequest(nri.request, callingUid);
2279 }
2280 }
2281
Paul Jensen99364842014-12-09 11:43:45 -05002282 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002283 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2284 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002285 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002286 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002287 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2288 // If this Network is already the highest scoring Network for a request, or if
2289 // there is hope for it to become one if it validated, then it is needed.
2290 if (nri.isRequest && nai.satisfies(nri.request) &&
2291 (nai.networkRequests.get(nri.request.requestId) != null ||
2292 // Note that this catches two important cases:
2293 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2294 // is currently satisfying the request. This is desirable when
2295 // cellular ends up validating but WiFi does not.
2296 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002297 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002298 // WiFi ends up validating and out scoring cellular.
2299 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2300 nai.getCurrentScoreAsValidated())) {
2301 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002302 }
2303 }
Paul Jensene0988542015-06-25 15:30:08 -04002304 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002305 }
2306
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002307 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2308 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002309 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002310 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002311 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2312 return;
2313 }
2314 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002315 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002316 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002317 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002318 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002319 // Find all networks that are satisfying this request and remove the request
2320 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002321 // TODO - it's my understanding that for a request there is only a single
2322 // network satisfying it, so this loop is wasteful
2323 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002324 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2325 if (nai.networkRequests.get(nri.request.requestId) != null) {
2326 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002327 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002328 log(" Removing from current network " + nai.name() +
2329 ", leaving " + nai.networkRequests.size() +
2330 " requests.");
2331 }
Paul Jensen99364842014-12-09 11:43:45 -05002332 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002333 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002334 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002335 } else {
2336 // suspect there should only be one pass through here
2337 // but if any were kept do the check below
2338 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002339 }
2340 }
2341 }
2342
Robert Greenwalt51481852015-01-08 14:43:31 -08002343 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2344 if (nai != null) {
2345 mNetworkForRequestId.remove(nri.request.requestId);
2346 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002347 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002348 // that a network connected to serve it, even though the network was already
2349 // connected. Now that this request has gone away, we might have to pretend
2350 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002351 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002352 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2353 boolean doRemove = true;
2354 if (wasKept) {
2355 // check if any of the remaining requests for this network are for the
2356 // same legacy type - if so, don't remove the nai
2357 for (int i = 0; i < nai.networkRequests.size(); i++) {
2358 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2359 if (otherRequest.legacyType == nri.request.legacyType &&
2360 isRequest(otherRequest)) {
2361 if (DBG) log(" still have other legacy request - leaving");
2362 doRemove = false;
2363 }
2364 }
2365 }
2366
2367 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002368 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002369 }
2370 }
2371
Robert Greenwalta67be032014-05-16 15:49:14 -07002372 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002373 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2374 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002375 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002376 } else {
2377 // listens don't have a singular affectedNetwork. Check all networks to see
2378 // if this listen request applies and remove it.
2379 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2380 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002381 if (nri.request.networkCapabilities.hasSignalStrength() &&
2382 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2383 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002384 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002385 }
2386 }
2387 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2388 }
2389 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002390
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002391 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2392 enforceConnectivityInternalPermission();
2393 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2394 accept ? 1 : 0, always ? 1: 0, network));
2395 }
2396
2397 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2398 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2399 " accept=" + accept + " always=" + always);
2400
2401 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2402 if (nai == null) {
2403 // Nothing to do.
2404 return;
2405 }
2406
2407 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002408 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002409 return;
2410 }
2411
2412 if (!nai.networkMisc.explicitlySelected) {
2413 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2414 }
2415
2416 if (accept != nai.networkMisc.acceptUnvalidated) {
2417 int oldScore = nai.getCurrentScore();
2418 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002419 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002420 sendUpdatedScoreToFactories(nai);
2421 }
2422
2423 if (always) {
2424 nai.asyncChannel.sendMessage(
2425 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2426 }
2427
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002428 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002429 // Tell the NetworkAgent to not automatically reconnect to the network.
2430 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2431 // Teardown the nework.
2432 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002433 }
2434
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002435 }
2436
2437 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002438 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002439 mHandler.sendMessageDelayed(
2440 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2441 PROMPT_UNVALIDATED_DELAY_MS);
2442 }
2443
2444 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002445 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002446 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2447
2448 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2449 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002450 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002451 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002452 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2453 return;
2454 }
2455
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002456 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002457 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002458 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2459 intent.setClassName("com.android.settings",
2460 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002461
2462 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2463 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2464 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002465 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002466 }
2467
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002468 private class InternalHandler extends Handler {
2469 public InternalHandler(Looper looper) {
2470 super(looper);
2471 }
2472
2473 @Override
2474 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002475 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002476 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002477 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002478 String causedBy = null;
2479 synchronized (ConnectivityService.this) {
2480 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2481 mNetTransitionWakeLock.isHeld()) {
2482 mNetTransitionWakeLock.release();
2483 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002484 } else {
2485 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002486 }
2487 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002488 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2489 log("Failed to find a new network - expiring NetTransition Wakelock");
2490 } else {
2491 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2492 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002493 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002494 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002495 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002496 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002497 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002498 break;
2499 }
Jason Monkdecd2952013-10-10 14:02:51 -04002500 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002501 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002502 break;
2503 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002504 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002505 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2506 break;
2507 }
2508 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2509 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002510 break;
2511 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002512 case EVENT_REGISTER_NETWORK_AGENT: {
2513 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2514 break;
2515 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002516 case EVENT_REGISTER_NETWORK_REQUEST:
2517 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002518 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002519 break;
2520 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002521 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2522 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002523 handleRegisterNetworkRequestWithIntent(msg);
2524 break;
2525 }
2526 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2527 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2528 break;
2529 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002530 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002531 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002532 break;
2533 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002534 case EVENT_SET_ACCEPT_UNVALIDATED: {
2535 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2536 break;
2537 }
2538 case EVENT_PROMPT_UNVALIDATED: {
2539 handlePromptUnvalidated((Network) msg.obj);
2540 break;
2541 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002542 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2543 handleMobileDataAlwaysOn();
2544 break;
2545 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002546 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2547 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2548 mKeepaliveTracker.handleStartKeepalive(msg);
2549 break;
2550 }
2551 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2552 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2553 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2554 int slot = msg.arg1;
2555 int reason = msg.arg2;
2556 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2557 break;
2558 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002559 case EVENT_SYSTEM_READY: {
2560 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2561 nai.networkMonitor.systemReady = true;
2562 }
2563 break;
2564 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002565 }
2566 }
2567 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002568
2569 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002570 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002571 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002572 if (isTetheringSupported()) {
2573 return mTethering.tether(iface);
2574 } else {
2575 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2576 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002577 }
2578
2579 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002580 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002581 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002582
2583 if (isTetheringSupported()) {
2584 return mTethering.untether(iface);
2585 } else {
2586 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2587 }
2588 }
2589
2590 // javadoc from interface
2591 public int getLastTetherError(String iface) {
2592 enforceTetherAccessPermission();
2593
2594 if (isTetheringSupported()) {
2595 return mTethering.getLastTetherError(iface);
2596 } else {
2597 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2598 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002599 }
2600
2601 // TODO - proper iface API for selection by property, inspection, etc
2602 public String[] getTetherableUsbRegexs() {
2603 enforceTetherAccessPermission();
2604 if (isTetheringSupported()) {
2605 return mTethering.getTetherableUsbRegexs();
2606 } else {
2607 return new String[0];
2608 }
2609 }
2610
2611 public String[] getTetherableWifiRegexs() {
2612 enforceTetherAccessPermission();
2613 if (isTetheringSupported()) {
2614 return mTethering.getTetherableWifiRegexs();
2615 } else {
2616 return new String[0];
2617 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002618 }
2619
Danica Chang6fdd0c62010-08-11 14:54:43 -07002620 public String[] getTetherableBluetoothRegexs() {
2621 enforceTetherAccessPermission();
2622 if (isTetheringSupported()) {
2623 return mTethering.getTetherableBluetoothRegexs();
2624 } else {
2625 return new String[0];
2626 }
2627 }
2628
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002629 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002630 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002631 if (isTetheringSupported()) {
2632 return mTethering.setUsbTethering(enable);
2633 } else {
2634 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2635 }
2636 }
2637
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002638 // TODO - move iface listing, queries, etc to new module
2639 // javadoc from interface
2640 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002641 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002642 return mTethering.getTetherableIfaces();
2643 }
2644
2645 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002646 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002647 return mTethering.getTetheredIfaces();
2648 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002649
Robert Greenwalt5a735062010-03-02 17:25:02 -08002650 public String[] getTetheringErroredIfaces() {
2651 enforceTetherAccessPermission();
2652 return mTethering.getErroredIfaces();
2653 }
2654
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002655 public String[] getTetheredDhcpRanges() {
2656 enforceConnectivityInternalPermission();
2657 return mTethering.getTetheredDhcpRanges();
2658 }
2659
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002660 // if ro.tether.denied = true we default to no tethering
2661 // gservices could set the secure setting to 1 though to enable it on a build where it
2662 // had previously been turned off.
2663 public boolean isTetheringSupported() {
2664 enforceTetherAccessPermission();
2665 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002666 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002667 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2668 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002669 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2670 mTethering.getTetherableWifiRegexs().length != 0 ||
2671 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2672 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002673 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002674
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002675 // Called when we lose the default network and have no replacement yet.
2676 // This will automatically be cleared after X seconds or a new default network
2677 // becomes CONNECTED, whichever happens first. The timer is started by the
2678 // first caller and not restarted by subsequent callers.
2679 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002680 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002681 synchronized (this) {
2682 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002683 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002684 mNetTransitionWakeLock.acquire();
2685 mNetTransitionWakeLockCausedBy = forWhom;
2686 }
2687 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002688 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002689 mNetTransitionWakeLockTimeout);
2690 return;
2691 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002692
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002693 // 100 percent is full good, 0 is full bad.
2694 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002695 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002696 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002697 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002698 }
2699
Paul Jensenbfd17b72015-04-07 12:43:13 -04002700 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002701 enforceAccessPermission();
2702 enforceInternetPermission();
2703
Paul Jensenbfd17b72015-04-07 12:43:13 -04002704 NetworkAgentInfo nai;
2705 if (network == null) {
2706 nai = getDefaultNetwork();
2707 } else {
2708 nai = getNetworkAgentInfoForNetwork(network);
2709 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002710 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2711 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2712 return;
2713 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002714 // Revalidate if the app report does not match our current validated state.
2715 if (hasConnectivity == nai.lastValidated) return;
2716 final int uid = Binder.getCallingUid();
2717 if (DBG) {
2718 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2719 ") by " + uid);
2720 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002721 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002722 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2723 // which isn't meant to work on uncreated networks.
2724 if (!nai.created) return;
2725
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002726 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002727
2728 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2729 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002730 }
2731
Paul Jensencee9b512015-05-06 07:32:40 -04002732 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002733 // this information is already available as a world read/writable jvm property
2734 // so this API change wouldn't have a benifit. It also breaks the passing
2735 // of proxy info to all the JVMs.
2736 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002737 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002738 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002739 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2740 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002741 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002742 }
2743
Paul Jensencee9b512015-05-06 07:32:40 -04002744 public ProxyInfo getProxyForNetwork(Network network) {
2745 if (network == null) return getDefaultProxy();
2746 final ProxyInfo globalProxy = getGlobalProxy();
2747 if (globalProxy != null) return globalProxy;
2748 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2749 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2750 // caller may not have.
2751 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2752 if (nai == null) return null;
2753 synchronized (nai) {
2754 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2755 if (proxyInfo == null) return null;
2756 return new ProxyInfo(proxyInfo);
2757 }
2758 }
2759
Paul Jensene0bef712014-12-10 15:12:18 -05002760 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2761 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2762 // proxy is null then there is no proxy in place).
2763 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2764 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2765 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2766 proxy = null;
2767 }
2768 return proxy;
2769 }
2770
2771 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2772 // better for determining if a new proxy broadcast is necessary:
2773 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2774 // avoid unnecessary broadcasts.
2775 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2776 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2777 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2778 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2779 // all set.
2780 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2781 a = canonicalizeProxyInfo(a);
2782 b = canonicalizeProxyInfo(b);
2783 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2784 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2785 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2786 }
2787
Jason Monk207900c2014-04-25 15:00:09 -04002788 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002789 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002790
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002791 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002792 if (proxyProperties == mGlobalProxy) return;
2793 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2794 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2795
2796 String host = "";
2797 int port = 0;
2798 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002799 String pacFileUrl = "";
2800 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002801 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002802 if (!proxyProperties.isValid()) {
2803 if (DBG)
2804 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2805 return;
2806 }
Jason Monk207900c2014-04-25 15:00:09 -04002807 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002808 host = mGlobalProxy.getHost();
2809 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002810 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002811 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002812 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002813 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002814 } else {
2815 mGlobalProxy = null;
2816 }
2817 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002818 final long token = Binder.clearCallingIdentity();
2819 try {
2820 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2821 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2822 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2823 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002824 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002825 } finally {
2826 Binder.restoreCallingIdentity(token);
2827 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002828
Jason Monkcf0f97a2014-10-02 15:39:38 -04002829 if (mGlobalProxy == null) {
2830 proxyProperties = mDefaultProxy;
2831 }
2832 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002833 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002834 }
2835
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002836 private void loadGlobalProxy() {
2837 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002838 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2839 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2840 String exclList = Settings.Global.getString(res,
2841 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002842 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2843 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002844 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002845 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002846 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002847 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002848 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002849 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002850 if (!proxyProperties.isValid()) {
2851 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2852 return;
2853 }
2854
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002855 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002856 mGlobalProxy = proxyProperties;
2857 }
2858 }
2859 }
2860
Jason Monk207900c2014-04-25 15:00:09 -04002861 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002862 // this information is already available as a world read/writable jvm property
2863 // so this API change wouldn't have a benifit. It also breaks the passing
2864 // of proxy info to all the JVMs.
2865 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002866 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002867 return mGlobalProxy;
2868 }
2869 }
2870
Jason Monk207900c2014-04-25 15:00:09 -04002871 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002872 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002873 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002874 proxy = null;
2875 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002876 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002877 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002878 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002879 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002880 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2881 return;
2882 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002883
2884 // This call could be coming from the PacManager, containing the port of the local
2885 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2886 // global (to get the correct local port), and send a broadcast.
2887 // TODO: Switch PacManager to have its own message to send back rather than
2888 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002889 if ((mGlobalProxy != null) && (proxy != null)
2890 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002891 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2892 mGlobalProxy = proxy;
2893 sendProxyBroadcast(mGlobalProxy);
2894 return;
2895 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002896 mDefaultProxy = proxy;
2897
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002898 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002899 if (!mDefaultProxyDisabled) {
2900 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002901 }
2902 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002903 }
2904
Paul Jensene0bef712014-12-10 15:12:18 -05002905 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2906 // This method gets called when any network changes proxy, but the broadcast only ever contains
2907 // the default proxy (even if it hasn't changed).
2908 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2909 // world where an app might be bound to a non-default network.
2910 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2911 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2912 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2913
2914 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2915 sendProxyBroadcast(getDefaultProxy());
2916 }
2917 }
2918
Robert Greenwalt434203a2010-10-11 16:00:27 -07002919 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002920 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2921 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 if (!TextUtils.isEmpty(proxy)) {
2923 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002924 if (data.length == 0) {
2925 return;
2926 }
2927
Robert Greenwalt434203a2010-10-11 16:00:27 -07002928 String proxyHost = data[0];
2929 int proxyPort = 8080;
2930 if (data.length > 1) {
2931 try {
2932 proxyPort = Integer.parseInt(data[1]);
2933 } catch (NumberFormatException e) {
2934 return;
2935 }
2936 }
Jason Monk207900c2014-04-25 15:00:09 -04002937 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002938 setGlobalProxy(p);
2939 }
2940 }
2941
Jason Monk207900c2014-04-25 15:00:09 -04002942 private void sendProxyBroadcast(ProxyInfo proxy) {
2943 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002944 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002945 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002946 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002947 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2948 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002949 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002950 final long ident = Binder.clearCallingIdentity();
2951 try {
2952 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2953 } finally {
2954 Binder.restoreCallingIdentity(ident);
2955 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002956 }
2957
2958 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002959 final private HashMap<Uri, Integer> mUriEventMap;
2960 final private Context mContext;
2961 final private Handler mHandler;
2962
2963 SettingsObserver(Context context, Handler handler) {
2964 super(null);
2965 mUriEventMap = new HashMap<Uri, Integer>();
2966 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002967 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002968 }
2969
Erik Klineda4bfa82015-04-30 12:58:40 +09002970 void observe(Uri uri, int what) {
2971 mUriEventMap.put(uri, what);
2972 final ContentResolver resolver = mContext.getContentResolver();
2973 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002974 }
2975
2976 @Override
2977 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002978 Slog.wtf(TAG, "Should never be reached.");
2979 }
2980
2981 @Override
2982 public void onChange(boolean selfChange, Uri uri) {
2983 final Integer what = mUriEventMap.get(uri);
2984 if (what != null) {
2985 mHandler.obtainMessage(what.intValue()).sendToTarget();
2986 } else {
2987 loge("No matching event to send for URI=" + uri);
2988 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002989 }
2990 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002991
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002992 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002993 Slog.d(TAG, s);
2994 }
2995
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002996 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002997 Slog.e(TAG, s);
2998 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002999
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003000 private static <T> T checkNotNull(T value, String message) {
3001 if (value == null) {
3002 throw new NullPointerException(message);
3003 }
3004 return value;
3005 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003006
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003007 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003008 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003009 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3010 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3011 *
3012 * @param oldPackage Package name of the application which currently controls VPN, which will
3013 * be replaced. If there is no such application, this should should either be
3014 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3015 * @param newPackage Package name of the application which should gain control of VPN, or
3016 * {@code null} to disable.
3017 * @param userId User for whom to prepare the new VPN.
3018 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003019 * @hide
3020 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003021 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003022 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3023 int userId) {
3024 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003025 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003026
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003027 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003028 Vpn vpn = mVpns.get(userId);
3029 if (vpn != null) {
3030 return vpn.prepare(oldPackage, newPackage);
3031 } else {
3032 return false;
3033 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003034 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003035 }
3036
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003037 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003038 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3039 * This method is used by system-privileged apps.
3040 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3041 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3042 *
3043 * @param packageName The package for which authorization state should change.
3044 * @param userId User for whom {@code packageName} is installed.
3045 * @param authorized {@code true} if this app should be able to start a VPN connection without
3046 * explicit user approval, {@code false} if not.
3047 *
Jeff Davidson05542602014-08-11 14:07:27 -07003048 * @hide
3049 */
3050 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003051 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3052 enforceCrossUserPermission(userId);
3053
Jeff Davidson05542602014-08-11 14:07:27 -07003054 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003055 Vpn vpn = mVpns.get(userId);
3056 if (vpn != null) {
3057 vpn.setPackageAuthorization(packageName, authorized);
3058 }
Jeff Davidson05542602014-08-11 14:07:27 -07003059 }
3060 }
3061
3062 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003063 * Configure a TUN interface and return its file descriptor. Parameters
3064 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003065 * and not available in ConnectivityManager. Permissions are checked in
3066 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003067 * @hide
3068 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003069 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003070 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003071 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003072 int user = UserHandle.getUserId(Binder.getCallingUid());
3073 synchronized(mVpns) {
3074 return mVpns.get(user).establish(config);
3075 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003076 }
3077
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003078 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003079 * Start legacy VPN, controlling native daemons as needed. Creates a
3080 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003081 */
3082 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003083 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003084 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003085 final LinkProperties egress = getActiveLinkProperties();
3086 if (egress == null) {
3087 throw new IllegalStateException("Missing active network connection");
3088 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003089 int user = UserHandle.getUserId(Binder.getCallingUid());
3090 synchronized(mVpns) {
3091 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3092 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003093 }
3094
3095 /**
3096 * Return the information of the ongoing legacy VPN. This method is used
3097 * by VpnSettings and not available in ConnectivityManager. Permissions
3098 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003099 */
3100 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003101 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3102 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003103 if (mLockdownEnabled) {
3104 return null;
3105 }
3106
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003107 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003108 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003109 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003110 }
3111
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003112 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003113 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3114 * and not available in ConnectivityManager.
3115 */
3116 @Override
3117 public VpnInfo[] getAllVpnInfo() {
3118 enforceConnectivityInternalPermission();
3119 if (mLockdownEnabled) {
3120 return new VpnInfo[0];
3121 }
3122
3123 synchronized(mVpns) {
3124 List<VpnInfo> infoList = new ArrayList<>();
3125 for (int i = 0; i < mVpns.size(); i++) {
3126 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3127 if (info != null) {
3128 infoList.add(info);
3129 }
3130 }
3131 return infoList.toArray(new VpnInfo[infoList.size()]);
3132 }
3133 }
3134
3135 /**
3136 * @return VPN information for accounting, or null if we can't retrieve all required
3137 * information, e.g primary underlying iface.
3138 */
3139 @Nullable
3140 private VpnInfo createVpnInfo(Vpn vpn) {
3141 VpnInfo info = vpn.getVpnInfo();
3142 if (info == null) {
3143 return null;
3144 }
3145 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3146 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3147 // the underlyingNetworks list.
3148 if (underlyingNetworks == null) {
3149 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3150 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3151 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3152 }
3153 } else if (underlyingNetworks.length > 0) {
3154 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3155 if (linkProperties != null) {
3156 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3157 }
3158 }
3159 return info.primaryUnderlyingIface == null ? null : info;
3160 }
3161
3162 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003163 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3164 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003165 * Permissions are checked in Vpn class.
3166 * @hide
3167 */
3168 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003169 public VpnConfig getVpnConfig(int userId) {
3170 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003171 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003172 Vpn vpn = mVpns.get(userId);
3173 if (vpn != null) {
3174 return vpn.getVpnConfig();
3175 } else {
3176 return null;
3177 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003178 }
3179 }
3180
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003181 @Override
3182 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003183 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3184 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3185 return false;
3186 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003187
3188 // Tear down existing lockdown if profile was removed
3189 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3190 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003191 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3192 final VpnProfile profile = VpnProfile.decode(
3193 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003194 if (profile == null) {
3195 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3196 setLockdownTracker(null);
3197 return true;
3198 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003199 int user = UserHandle.getUserId(Binder.getCallingUid());
3200 synchronized(mVpns) {
3201 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3202 profile));
3203 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003204 } else {
3205 setLockdownTracker(null);
3206 }
3207
3208 return true;
3209 }
3210
3211 /**
3212 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3213 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3214 */
3215 private void setLockdownTracker(LockdownVpnTracker tracker) {
3216 // Shutdown any existing tracker
3217 final LockdownVpnTracker existing = mLockdownTracker;
3218 mLockdownTracker = null;
3219 if (existing != null) {
3220 existing.shutdown();
3221 }
3222
3223 try {
3224 if (tracker != null) {
3225 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003226 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003227 mLockdownTracker = tracker;
3228 mLockdownTracker.init();
3229 } else {
3230 mNetd.setFirewallEnabled(false);
3231 }
3232 } catch (RemoteException e) {
3233 // ignored; NMS lives inside system_server
3234 }
3235 }
3236
3237 private void throwIfLockdownEnabled() {
3238 if (mLockdownEnabled) {
3239 throw new IllegalStateException("Unavailable in lockdown mode");
3240 }
3241 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003242
Robin Lee244ce8e2016-01-05 18:03:46 +00003243 /**
3244 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3245 *
3246 * @return {@code false} in case of errors; {@code true} otherwise.
3247 */
3248 private boolean updateAlwaysOnVpn(int user) {
3249 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3250 if (lockdownPackage == null) {
3251 return true;
3252 }
3253
3254 // Create an intent to start the VPN service declared in the app's manifest.
3255 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3256 serviceIntent.setPackage(lockdownPackage);
3257
3258 try {
3259 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3260 } catch (RuntimeException e) {
3261 return false;
3262 }
3263 }
3264
3265 @Override
3266 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3267 enforceConnectivityInternalPermission();
3268 enforceCrossUserPermission(userId);
3269
3270 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3271 if (LockdownVpnTracker.isEnabled()) {
3272 return false;
3273 }
3274
3275 // If the current VPN package is the same as the new one, this is a no-op
3276 final String oldPackage = getAlwaysOnVpnPackage(userId);
3277 if (TextUtils.equals(oldPackage, packageName)) {
3278 return true;
3279 }
3280
3281 synchronized (mVpns) {
3282 Vpn vpn = mVpns.get(userId);
3283 if (vpn == null) {
3284 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3285 return false;
3286 }
3287 if (!vpn.setAlwaysOnPackage(packageName)) {
3288 return false;
3289 }
3290 if (!updateAlwaysOnVpn(userId)) {
3291 vpn.setAlwaysOnPackage(null);
3292 return false;
3293 }
3294 }
3295 return true;
3296 }
3297
3298 @Override
3299 public String getAlwaysOnVpnPackage(int userId) {
3300 enforceConnectivityInternalPermission();
3301 enforceCrossUserPermission(userId);
3302
3303 synchronized (mVpns) {
3304 Vpn vpn = mVpns.get(userId);
3305 if (vpn == null) {
3306 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3307 return null;
3308 }
3309 return vpn.getAlwaysOnPackage();
3310 }
3311 }
3312
Wink Savilleab9321d2013-06-29 21:10:57 -07003313 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003314 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003315 // TODO: Remove? Any reason to trigger a provisioning check?
3316 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003317 }
3318
3319 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003320 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003321
Paul Jensen89e0f092014-09-15 15:59:36 -04003322 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003323 if (DBG) {
3324 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003325 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003326 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003327 Intent intent = new Intent(action);
3328 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003329 // Concatenate the range of types onto the range of NetIDs.
3330 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003331 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003332 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003333 }
3334
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003335 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003336 * Show or hide network provisioning notifications.
3337 *
3338 * We use notifications for two purposes: to notify that a network requires sign in
3339 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3340 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3341 * particular network we can display the notification type that was most recently requested.
3342 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3343 * might first display NO_INTERNET, and then when the captive portal check completes, display
3344 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003345 *
3346 * @param id an identifier that uniquely identifies this notification. This must match
3347 * between show and hide calls. We use the NetID value but for legacy callers
3348 * we concatenate the range of types with the range of NetIDs.
3349 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003350 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003351 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3352 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003353 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003354 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3355 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003356 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003357 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003358
3359 Resources r = Resources.getSystem();
3360 NotificationManager notificationManager = (NotificationManager) mContext
3361 .getSystemService(Context.NOTIFICATION_SERVICE);
3362
3363 if (visible) {
3364 CharSequence title;
3365 CharSequence details;
3366 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003367 if (notifyType == NotificationType.NO_INTERNET &&
3368 networkType == ConnectivityManager.TYPE_WIFI) {
3369 title = r.getString(R.string.wifi_no_internet, 0);
3370 details = r.getString(R.string.wifi_no_internet_detailed);
3371 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3372 } else if (notifyType == NotificationType.SIGN_IN) {
3373 switch (networkType) {
3374 case ConnectivityManager.TYPE_WIFI:
3375 title = r.getString(R.string.wifi_available_sign_in, 0);
3376 details = r.getString(R.string.network_available_sign_in_detailed,
3377 extraInfo);
3378 icon = R.drawable.stat_notify_wifi_in_range;
3379 break;
3380 case ConnectivityManager.TYPE_MOBILE:
3381 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3382 title = r.getString(R.string.network_available_sign_in, 0);
3383 // TODO: Change this to pull from NetworkInfo once a printable
3384 // name has been added to it
3385 details = mTelephonyManager.getNetworkOperatorName();
3386 icon = R.drawable.stat_notify_rssi_in_range;
3387 break;
3388 default:
3389 title = r.getString(R.string.network_available_sign_in, 0);
3390 details = r.getString(R.string.network_available_sign_in_detailed,
3391 extraInfo);
3392 icon = R.drawable.stat_notify_rssi_in_range;
3393 break;
3394 }
3395 } else {
3396 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3397 + getNetworkTypeName(networkType));
3398 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003399 }
3400
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003401 Notification notification = new Notification.Builder(mContext)
3402 .setWhen(0)
3403 .setSmallIcon(icon)
3404 .setAutoCancel(true)
3405 .setTicker(title)
3406 .setColor(mContext.getColor(
3407 com.android.internal.R.color.system_notification_accent_color))
3408 .setContentTitle(title)
3409 .setContentText(details)
3410 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003411 .setLocalOnly(true)
3412 .setPriority(highPriority ?
3413 Notification.PRIORITY_HIGH :
3414 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003415 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003416 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003417 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003418
Wink Saville948282b2013-08-29 08:55:16 -07003419 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003420 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003421 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003422 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003423 npe.printStackTrace();
3424 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003425 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003426 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003427 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003428 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003429 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003430 npe.printStackTrace();
3431 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003432 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003433 }
3434
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003435 /** Location to an updatable file listing carrier provisioning urls.
3436 * An example:
3437 *
3438 * <?xml version="1.0" encoding="utf-8"?>
3439 * <provisioningUrls>
3440 * <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 -07003441 * </provisioningUrls>
3442 */
3443 private static final String PROVISIONING_URL_PATH =
3444 "/data/misc/radio/provisioning_urls.xml";
3445 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003446
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003447 /** XML tag for root element. */
3448 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3449 /** XML tag for individual url */
3450 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003451 /** XML attribute for mcc */
3452 private static final String ATTR_MCC = "mcc";
3453 /** XML attribute for mnc */
3454 private static final String ATTR_MNC = "mnc";
3455
Paul Jensen434dde82015-06-11 09:43:30 -04003456 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003457 FileReader fileReader = null;
3458 XmlPullParser parser = null;
3459 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003460
3461 try {
3462 fileReader = new FileReader(mProvisioningUrlFile);
3463 parser = Xml.newPullParser();
3464 parser.setInput(fileReader);
3465 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3466
3467 while (true) {
3468 XmlUtils.nextElement(parser);
3469
3470 String element = parser.getName();
3471 if (element == null) break;
3472
Paul Jensen434dde82015-06-11 09:43:30 -04003473 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003474 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3475 try {
3476 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3477 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3478 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3479 parser.next();
3480 if (parser.getEventType() == XmlPullParser.TEXT) {
3481 return parser.getText();
3482 }
3483 }
3484 }
3485 } catch (NumberFormatException e) {
3486 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3487 }
3488 }
3489 }
3490 return null;
3491 } catch (FileNotFoundException e) {
3492 loge("Carrier Provisioning Urls file not found");
3493 } catch (XmlPullParserException e) {
3494 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3495 } catch (IOException e) {
3496 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3497 } finally {
3498 if (fileReader != null) {
3499 try {
3500 fileReader.close();
3501 } catch (IOException e) {}
3502 }
3503 }
3504 return null;
3505 }
3506
Wink Saville42d4f082013-07-20 20:31:59 -07003507 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003508 public String getMobileProvisioningUrl() {
3509 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003510 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003511 if (TextUtils.isEmpty(url)) {
3512 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003513 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003514 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003515 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003516 }
Wink Saville8cf35602013-07-10 23:00:07 -07003517 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003518 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003519 String phoneNumber = mTelephonyManager.getLine1Number();
3520 if (TextUtils.isEmpty(phoneNumber)) {
3521 phoneNumber = "0000000000";
3522 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003523 url = String.format(url,
3524 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3525 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003526 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003527 }
3528
Wink Savilleab9321d2013-06-29 21:10:57 -07003529 return url;
3530 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003531
Wink Saville948282b2013-08-29 08:55:16 -07003532 @Override
3533 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003534 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003535 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003536 final long ident = Binder.clearCallingIdentity();
3537 try {
3538 setProvNotificationVisible(visible, networkType, action);
3539 } finally {
3540 Binder.restoreCallingIdentity(ident);
3541 }
Wink Saville948282b2013-08-29 08:55:16 -07003542 }
Wink Saville7788c612013-08-29 14:57:08 -07003543
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003544 @Override
3545 public void setAirplaneMode(boolean enable) {
3546 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003547 final long ident = Binder.clearCallingIdentity();
3548 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003549 final ContentResolver cr = mContext.getContentResolver();
3550 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3551 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3552 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003553 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003554 } finally {
3555 Binder.restoreCallingIdentity(ident);
3556 }
3557 }
3558
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003559 private void onUserStart(int userId) {
3560 synchronized(mVpns) {
3561 Vpn userVpn = mVpns.get(userId);
3562 if (userVpn != null) {
3563 loge("Starting user already has a VPN");
3564 return;
3565 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003566 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003567 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003568 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003569 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3570 updateLockdownVpn();
3571 } else {
3572 updateAlwaysOnVpn(userId);
3573 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003574 }
3575
3576 private void onUserStop(int userId) {
3577 synchronized(mVpns) {
3578 Vpn userVpn = mVpns.get(userId);
3579 if (userVpn == null) {
3580 loge("Stopping user has no VPN");
3581 return;
3582 }
3583 mVpns.delete(userId);
3584 }
3585 }
3586
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003587 private void onUserAdded(int userId) {
3588 synchronized(mVpns) {
3589 final int vpnsSize = mVpns.size();
3590 for (int i = 0; i < vpnsSize; i++) {
3591 Vpn vpn = mVpns.valueAt(i);
3592 vpn.onUserAdded(userId);
3593 }
3594 }
3595 }
3596
3597 private void onUserRemoved(int userId) {
3598 synchronized(mVpns) {
3599 final int vpnsSize = mVpns.size();
3600 for (int i = 0; i < vpnsSize; i++) {
3601 Vpn vpn = mVpns.valueAt(i);
3602 vpn.onUserRemoved(userId);
3603 }
3604 }
3605 }
3606
Robin Lee9a5f4852015-12-17 11:42:22 +00003607 private void onUserPresent(int userId) {
3608 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3609 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3610 updateLockdownVpn();
3611 } else {
3612 updateAlwaysOnVpn(userId);
3613 }
3614 }
3615
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003616 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3617 @Override
3618 public void onReceive(Context context, Intent intent) {
3619 final String action = intent.getAction();
3620 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3621 if (userId == UserHandle.USER_NULL) return;
3622
3623 if (Intent.ACTION_USER_STARTING.equals(action)) {
3624 onUserStart(userId);
3625 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3626 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003627 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3628 onUserAdded(userId);
3629 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3630 onUserRemoved(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003631 } else if (Intent.ACTION_USER_PRESENT.equals(action)) {
3632 onUserPresent(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003633 }
3634 }
3635 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003636
Robert Greenwalta67be032014-05-16 15:49:14 -07003637 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3638 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003639 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3640 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003641
Robert Greenwalta67be032014-05-16 15:49:14 -07003642 private static class NetworkFactoryInfo {
3643 public final String name;
3644 public final Messenger messenger;
3645 public final AsyncChannel asyncChannel;
3646
3647 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3648 this.name = name;
3649 this.messenger = messenger;
3650 this.asyncChannel = asyncChannel;
3651 }
3652 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003653
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003654 /**
3655 * Tracks info about the requester.
3656 * Also used to notice when the calling process dies so we can self-expire
3657 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003658 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3659 static final boolean REQUEST = true;
3660 static final boolean LISTEN = false;
3661
3662 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003663 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003664 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003665 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003666 final int mPid;
3667 final int mUid;
3668 final Messenger messenger;
3669 final boolean isRequest;
3670
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003671 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3672 request = r;
3673 mPendingIntent = pi;
3674 messenger = null;
3675 mBinder = null;
3676 mPid = getCallingPid();
3677 mUid = getCallingUid();
3678 this.isRequest = isRequest;
3679 }
3680
Robert Greenwalt9258c642014-03-26 16:47:06 -07003681 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3682 super();
3683 messenger = m;
3684 request = r;
3685 mBinder = binder;
3686 mPid = getCallingPid();
3687 mUid = getCallingUid();
3688 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003689 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003690
3691 try {
3692 mBinder.linkToDeath(this, 0);
3693 } catch (RemoteException e) {
3694 binderDied();
3695 }
3696 }
3697
3698 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003699 if (mBinder != null) {
3700 mBinder.unlinkToDeath(this, 0);
3701 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003702 }
3703
3704 public void binderDied() {
3705 log("ConnectivityService NetworkRequestInfo binderDied(" +
3706 request + ", " + mBinder + ")");
3707 releaseNetworkRequest(request);
3708 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003709
3710 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003711 return (isRequest ? "Request" : "Listen") +
3712 " from uid/pid:" + mUid + "/" + mPid +
3713 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003714 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003715 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003716 }
3717
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003718 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3719 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3720 if (badCapability != null) {
3721 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003722 }
3723 }
3724
Erik Kline9d598e12015-07-13 16:37:51 +09003725 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003726 final SortedSet<Integer> thresholds = new TreeSet();
3727 synchronized (nai) {
3728 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3729 if (nri.request.networkCapabilities.hasSignalStrength() &&
3730 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3731 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3732 }
3733 }
3734 }
Erik Kline9d598e12015-07-13 16:37:51 +09003735 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003736 }
3737
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003738 private void updateSignalStrengthThresholds(
3739 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3740 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003741 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003742 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3743
3744 // TODO: Switch to VDBG.
3745 if (DBG) {
3746 String detail;
3747 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3748 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3749 } else {
3750 detail = reason;
3751 }
3752 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3753 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3754 }
3755
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003756 nai.asyncChannel.sendMessage(
3757 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003758 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003759 }
3760
Robert Greenwalt9258c642014-03-26 16:47:06 -07003761 @Override
3762 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003763 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003764 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003765 enforceNetworkRequestPermissions(networkCapabilities);
3766 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003767 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003768
Robert Greenwalt6078b502014-06-11 16:05:07 -07003769 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003770 throw new IllegalArgumentException("Bad timeout specified");
3771 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003772
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003773 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3774 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003775 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3776 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003777 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003778
3779 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003780 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003781 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003782 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003783 }
3784 return networkRequest;
3785 }
3786
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003787 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003788 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003789 enforceConnectivityInternalPermission();
3790 } else {
3791 enforceChangePermission();
3792 }
3793 }
3794
fenglub15e72b2015-03-20 11:29:56 -07003795 @Override
fengludb571472015-04-21 17:12:05 -07003796 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003797 enforceAccessPermission();
3798 NetworkAgentInfo nai = null;
3799 if (network == null) {
3800 return false;
3801 }
3802 synchronized (mNetworkForNetId) {
3803 nai = mNetworkForNetId.get(network.netId);
3804 }
3805 if (nai != null) {
3806 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3807 return true;
3808 }
3809 return false;
3810 }
3811
3812
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003813 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3814 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003815 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003816 final int uidRules;
3817 final int uid = Binder.getCallingUid();
3818 synchronized(mRulesLock) {
3819 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3820 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003821 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003822 // we could silently fail or we can filter the available nets to only give
3823 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003824 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003825 }
3826 }
3827 }
3828
Robert Greenwalt9258c642014-03-26 16:47:06 -07003829 @Override
3830 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3831 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003832 checkNotNull(operation, "PendingIntent cannot be null.");
3833 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3834 enforceNetworkRequestPermissions(networkCapabilities);
3835 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003836 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003837
3838 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3839 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003840 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3841 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003842 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003843 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3844 nri));
3845 return networkRequest;
3846 }
3847
Jeremy Joslin79294842014-12-03 17:15:28 -08003848 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3849 mHandler.sendMessageDelayed(
3850 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3851 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3852 }
3853
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003854 @Override
3855 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003856 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003857 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3858 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003859 }
3860
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003861 // In order to implement the compatibility measure for pre-M apps that call
3862 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3863 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3864 // This ensures it has permission to do so.
3865 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3866 if (nc == null) {
3867 return false;
3868 }
3869 int[] transportTypes = nc.getTransportTypes();
3870 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3871 return false;
3872 }
3873 try {
3874 mContext.enforceCallingOrSelfPermission(
3875 android.Manifest.permission.ACCESS_WIFI_STATE,
3876 "ConnectivityService");
3877 } catch (SecurityException e) {
3878 return false;
3879 }
3880 return true;
3881 }
3882
Robert Greenwalt9258c642014-03-26 16:47:06 -07003883 @Override
3884 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3885 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003886 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3887 enforceAccessPermission();
3888 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003889
Erik Kline7523eb32015-07-09 18:24:03 +09003890 NetworkRequest networkRequest = new NetworkRequest(
3891 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003892 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3893 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003894 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003895
3896 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3897 return networkRequest;
3898 }
3899
3900 @Override
3901 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3902 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003903 checkNotNull(operation, "PendingIntent cannot be null.");
3904 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3905 enforceAccessPermission();
3906 }
3907
Erik Kline7523eb32015-07-09 18:24:03 +09003908 NetworkRequest networkRequest = new NetworkRequest(
3909 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003910 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3911 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003912 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003913
3914 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003915 }
3916
3917 @Override
3918 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003919 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3920 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003921 }
3922
3923 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003924 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003925 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003926 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3927 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003928 }
3929
Robert Greenwalta67be032014-05-16 15:49:14 -07003930 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003931 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003932 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3933 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3934 }
3935
3936 @Override
3937 public void unregisterNetworkFactory(Messenger messenger) {
3938 enforceConnectivityInternalPermission();
3939 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3940 }
3941
3942 private void handleUnregisterNetworkFactory(Messenger messenger) {
3943 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3944 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003945 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003946 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003947 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003948 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003949 }
3950
Robert Greenwalt7b816022014-04-18 15:25:25 -07003951 /**
3952 * NetworkAgentInfo supporting a request by requestId.
3953 * These have already been vetted (their Capabilities satisfy the request)
3954 * and the are the highest scored network available.
3955 * the are keyed off the Requests requestId.
3956 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003957 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003958 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3959 new SparseArray<NetworkAgentInfo>();
3960
Paul Jensen31a94f42015-02-13 14:18:39 -05003961 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3962 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003963 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3964 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003965 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3966 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3967 // there may not be a strict 1:1 correlation between the two.
3968 @GuardedBy("mNetworkForNetId")
3969 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003970
Robert Greenwalt7b816022014-04-18 15:25:25 -07003971 // NetworkAgentInfo keyed off its connecting messenger
3972 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003973 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003974 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3975 new HashMap<Messenger, NetworkAgentInfo>();
3976
Paul Jensen2c311d62014-11-17 12:34:51 -05003977 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003978 private final NetworkRequest mDefaultRequest;
3979
Erik Klineda4bfa82015-04-30 12:58:40 +09003980 // Request used to optionally keep mobile data active even when higher
3981 // priority networks like Wi-Fi are active.
3982 private final NetworkRequest mDefaultMobileDataRequest;
3983
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003984 private NetworkAgentInfo getDefaultNetwork() {
3985 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3986 }
3987
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003988 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003989 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003990 }
3991
Paul Jensen31a94f42015-02-13 14:18:39 -05003992 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003993 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003994 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003995 enforceConnectivityInternalPermission();
3996
Paul Jensen2c311d62014-11-17 12:34:51 -05003997 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3998 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04003999 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004000 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4001 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004002 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004003 synchronized (this) {
4004 nai.networkMonitor.systemReady = mSystemReady;
4005 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004006 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004007 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004008 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004009 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004010 }
4011
4012 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4013 if (VDBG) log("Got NetworkAgent Messenger");
4014 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004015 synchronized (mNetworkForNetId) {
4016 mNetworkForNetId.put(na.network.netId, na);
4017 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004018 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4019 NetworkInfo networkInfo = na.networkInfo;
4020 na.networkInfo = null;
4021 updateNetworkInfo(na, networkInfo);
4022 }
4023
4024 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4025 LinkProperties newLp = networkAgent.linkProperties;
4026 int netId = networkAgent.network.netId;
4027
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004028 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4029 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004030 if (networkAgent.clatd != null) {
4031 networkAgent.clatd.fixupLinkProperties(oldLp);
4032 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004033
Paul Jensen992f2522014-04-28 10:33:11 -04004034 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004035 updateMtu(newLp, oldLp);
4036 // TODO - figure out what to do for clat
4037// for (LinkProperties lp : newLp.getStackedLinks()) {
4038// updateMtu(lp, null);
4039// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004040 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004041
Lorenzo Colitti93155b32015-05-14 22:12:36 +09004042 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
4043 // In L, we used it only when the network had Internet access but provided no DNS servers.
4044 // For now, just disable it, and if disabling it doesn't break things, remove it.
4045 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
4046 // NET_CAPABILITY_INTERNET);
4047 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004048 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004049 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
4050
Paul Jensen3b759822014-05-13 11:44:01 -04004051 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004052 if (isDefaultNetwork(networkAgent)) {
4053 handleApplyDefaultProxy(newLp.getHttpProxy());
4054 } else {
4055 updateProxy(newLp, oldLp, networkAgent);
4056 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004057 // TODO - move this check to cover the whole function
4058 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08004059 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004060 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4061 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004062
4063 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004064 }
4065
Lorenzo Colitti95439462014-10-09 13:44:48 +09004066 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4067 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4068 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004069
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004070 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004071 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4072 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004073 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004074 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004075 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004076 }
Paul Jensen992f2522014-04-28 10:33:11 -04004077
4078 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4079 CompareResult<String> interfaceDiff = new CompareResult<String>();
4080 if (oldLp != null) {
4081 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4082 } else if (newLp != null) {
4083 interfaceDiff.added = newLp.getAllInterfaceNames();
4084 }
4085 for (String iface : interfaceDiff.added) {
4086 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004087 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004088 mNetd.addInterfaceToNetwork(iface, netId);
4089 } catch (Exception e) {
4090 loge("Exception adding interface: " + e);
4091 }
4092 }
4093 for (String iface : interfaceDiff.removed) {
4094 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004095 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004096 mNetd.removeInterfaceFromNetwork(iface, netId);
4097 } catch (Exception e) {
4098 loge("Exception removing interface: " + e);
4099 }
4100 }
4101 }
4102
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004103 /**
4104 * Have netd update routes from oldLp to newLp.
4105 * @return true if routes changed between oldLp and newLp
4106 */
4107 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004108 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4109 if (oldLp != null) {
4110 routeDiff = oldLp.compareAllRoutes(newLp);
4111 } else if (newLp != null) {
4112 routeDiff.added = newLp.getAllRoutes();
4113 }
4114
4115 // add routes before removing old in case it helps with continuous connectivity
4116
4117 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4118 for (RouteInfo route : routeDiff.added) {
4119 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004120 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004121 try {
4122 mNetd.addRoute(netId, route);
4123 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004124 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4125 loge("Exception in addRoute for non-gateway: " + e);
4126 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004127 }
4128 }
4129 for (RouteInfo route : routeDiff.added) {
4130 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004131 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004132 try {
4133 mNetd.addRoute(netId, route);
4134 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004135 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4136 loge("Exception in addRoute for gateway: " + e);
4137 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004138 }
4139 }
4140
4141 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004142 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004143 try {
4144 mNetd.removeRoute(netId, route);
4145 } catch (Exception e) {
4146 loge("Exception in removeRoute: " + e);
4147 }
4148 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004149 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004150 }
Erik Kline41368502015-06-17 13:19:54 +09004151
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004152 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4153 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004154 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004155 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004156 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004157 dnses = new ArrayList();
4158 dnses.add(mDefaultDns);
4159 if (DBG) {
4160 loge("no dns provided for netId " + netId + ", so using defaults");
4161 }
4162 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004163 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004164 try {
4165 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4166 newLp.getDomains());
4167 } catch (Exception e) {
4168 loge("Exception in setDnsServersForNetwork: " + e);
4169 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004170 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004171 if (defaultNai != null && defaultNai.network.netId == netId) {
4172 setDefaultDnsSystemProperties(dnses);
4173 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004174 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004175 } else if (flush) {
4176 try {
4177 mNetd.flushNetworkDnsCache(netId);
4178 } catch (Exception e) {
4179 loge("Exception in flushNetworkDnsCache: " + e);
4180 }
4181 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004182 }
4183 }
4184
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004185 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4186 int last = 0;
4187 for (InetAddress dns : dnses) {
4188 ++last;
4189 String key = "net.dns" + last;
4190 String value = dns.getHostAddress();
4191 SystemProperties.set(key, value);
4192 }
4193 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4194 String key = "net.dns" + i;
4195 SystemProperties.set(key, "");
4196 }
4197 mNumDnsEntries = last;
4198 }
4199
Paul Jensen3d194ea2015-06-16 14:27:36 -04004200 /**
4201 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4202 * augmented with any stateful capabilities implied from {@code networkAgent}
4203 * (e.g., validated status and captive portal status).
4204 *
Paul Jensene0988542015-06-25 15:30:08 -04004205 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004206 * @param networkCapabilities the new network capabilities.
4207 */
Paul Jensene0988542015-06-25 15:30:08 -04004208 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004209 // Don't modify caller's NetworkCapabilities.
4210 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004211 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004212 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4213 } else {
4214 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4215 }
Paul Jensene0988542015-06-25 15:30:08 -04004216 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004217 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4218 } else {
4219 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4220 }
Paul Jensene0988542015-06-25 15:30:08 -04004221 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4222 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004223 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4224 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4225 try {
4226 mNetd.setNetworkPermission(nai.network.netId,
4227 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4228 null : NetworkManagementService.PERMISSION_SYSTEM);
4229 } catch (RemoteException e) {
4230 loge("Exception in setNetworkPermission: " + e);
4231 }
4232 }
Paul Jensene0988542015-06-25 15:30:08 -04004233 synchronized (nai) {
4234 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004235 }
Paul Jensene0988542015-06-25 15:30:08 -04004236 rematchAllNetworksAndRequests(nai, oldScore);
4237 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004238 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004239 }
4240
Paul Jensenc8b9a742014-09-30 15:37:41 -04004241 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4242 for (int i = 0; i < nai.networkRequests.size(); i++) {
4243 NetworkRequest nr = nai.networkRequests.valueAt(i);
4244 // Don't send listening requests to factories. b/17393458
4245 if (!isRequest(nr)) continue;
4246 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4247 }
4248 }
4249
Robert Greenwalt7b816022014-04-18 15:25:25 -07004250 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4251 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004252 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004253 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4254 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004255 }
4256 }
4257
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004258 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4259 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004260 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004261 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004262 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4263 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004264 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004265 sendIntent(nri.mPendingIntent, intent);
4266 }
4267 // else not handled
4268 }
4269
4270 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4271 mPendingIntentWakeLock.acquire();
4272 try {
4273 if (DBG) log("Sending " + pendingIntent);
4274 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4275 } catch (PendingIntent.CanceledException e) {
4276 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4277 mPendingIntentWakeLock.release();
4278 releasePendingNetworkRequest(pendingIntent);
4279 }
4280 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4281 }
4282
4283 @Override
4284 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4285 String resultData, Bundle resultExtras) {
4286 if (DBG) log("Finished sending " + pendingIntent);
4287 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004288 // Release with a delay so the receiving client has an opportunity to put in its
4289 // own request.
4290 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004291 }
4292
Robert Greenwalt9258c642014-03-26 16:47:06 -07004293 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004294 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004295 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004296 Bundle bundle = new Bundle();
4297 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4298 new NetworkRequest(nri.request));
4299 Message msg = Message.obtain();
4300 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4301 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4302 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4303 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004304 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004305 case ConnectivityManager.CALLBACK_LOSING: {
4306 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4307 break;
4308 }
4309 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4310 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4311 new NetworkCapabilities(networkAgent.networkCapabilities));
4312 break;
4313 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004314 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004315 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4316 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004317 break;
4318 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004319 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004320 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004321 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004322 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004323 if (VDBG) {
4324 log("sending notification " + notifyTypeToName(notificationType) +
4325 " for " + nri.request);
4326 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004327 nri.messenger.send(msg);
4328 } catch (RemoteException e) {
4329 // may occur naturally in the race of binder death.
4330 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4331 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004332 }
4333
Paul Jensenc8b9a742014-09-30 15:37:41 -04004334 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4335 for (int i = 0; i < nai.networkRequests.size(); i++) {
4336 NetworkRequest nr = nai.networkRequests.valueAt(i);
4337 // Ignore listening requests.
4338 if (!isRequest(nr)) continue;
4339 loge("Dead network still had at least " + nr);
4340 break;
4341 }
4342 nai.asyncChannel.disconnect();
4343 }
4344
Robert Greenwalt7b816022014-04-18 15:25:25 -07004345 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4346 if (oldNetwork == null) {
4347 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4348 return;
4349 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004350 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4351 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004352 }
4353
Paul Jensen27b02b72014-07-14 12:03:33 -04004354 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004355 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004356 setupDataActivityTracking(newNetwork);
4357 try {
4358 mNetd.setDefaultNetId(newNetwork.network.netId);
4359 } catch (Exception e) {
4360 loge("Exception setting default network :" + e);
4361 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004362 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004363 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004364 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004365 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004366 }
4367
Paul Jensen2161a8e2014-09-11 11:00:39 -04004368 // Handles a network appearing or improving its score.
4369 //
4370 // - Evaluates all current NetworkRequests that can be
4371 // satisfied by newNetwork, and reassigns to newNetwork
4372 // any such requests for which newNetwork is the best.
4373 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004374 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004375 // needed. A network is needed if it is the best network for
4376 // one or more NetworkRequests, or if it is a VPN.
4377 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004378 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004379 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004380 //
4381 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4382 // networks that have no chance (i.e. even if validated)
4383 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004384 //
4385 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4386 // it does not remove NetworkRequests that other Networks could better satisfy.
4387 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4388 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4389 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004390 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004391 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004392 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4393 // performed to tear down unvalidated networks that have no chance (i.e. even if
4394 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004395 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004396 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004397 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004398 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004399 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004400 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004401 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004402 // Find and migrate to this Network any NetworkRequests for
4403 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004404 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004405 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004406 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004407 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004408 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4409 final boolean satisfies = newNetwork.satisfies(nri.request);
4410 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004411 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004412 log("Network " + newNetwork.name() + " was already satisfying" +
4413 " request " + nri.request.requestId + ". No change.");
4414 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004415 keep = true;
4416 continue;
4417 }
4418
4419 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004420 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004421 if (satisfies) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004422 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004423 // This is not a request, it's a callback listener.
4424 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004425 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004426 continue;
4427 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004428
Robert Greenwalt7b816022014-04-18 15:25:25 -07004429 // next check if it's better than any current network we're using for
4430 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004431 if (VDBG) {
4432 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004433 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4434 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004435 }
4436 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004437 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004438 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004439 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004440 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004441 currentNetwork.networkRequests.remove(nri.request.requestId);
4442 currentNetwork.networkLingered.add(nri.request);
4443 affectedNetworks.add(currentNetwork);
4444 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004445 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004446 }
Paul Jensen573a0352015-01-08 10:49:34 -05004447 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004448 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004449 if (!newNetwork.addRequest(nri.request)) {
4450 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4451 }
4452 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004453 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004454 // Tell NetworkFactories about the new score, so they can stop
4455 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004456 // TODO - this could get expensive if we have alot of requests for this
4457 // network. Think about if there is a way to reduce this. Push
4458 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004459 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004460 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004461 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004462 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004463 }
4464 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004465 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4466 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4467 // mark it as no longer satisfying "nri". Because networks are processed by
4468 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4469 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4470 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4471 // This means this code doesn't have to handle the case where "currentNetwork" no
4472 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4473 if (DBG) {
4474 log("Network " + newNetwork.name() + " stopped satisfying" +
4475 " request " + nri.request.requestId);
4476 }
4477 newNetwork.networkRequests.remove(nri.request.requestId);
4478 if (currentNetwork == newNetwork) {
4479 mNetworkForRequestId.remove(nri.request.requestId);
4480 sendUpdatedScoreToFactories(nri.request, 0);
4481 } else {
4482 if (nri.isRequest == true) {
4483 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4484 newNetwork.name() +
4485 " without updating mNetworkForRequestId or factories!");
4486 }
4487 }
4488 // TODO: technically, sending CALLBACK_LOST here is
4489 // incorrect if nri is a request (not a listen) and there
4490 // is a replacement network currently connected that can
4491 // satisfy it. However, the only capability that can both
4492 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4493 // so this code is only incorrect for a network that loses
4494 // the TRUSTED capability, which is a rare case.
4495 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004496 }
4497 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004498 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004499 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004500 if (nai.lingering) {
4501 // Already lingered. Nothing to do. This can only happen if "nai" is in
4502 // "affectedNetworks" twice. The reasoning being that to get added to
4503 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4504 // (i.e. not lingered) so it could have only been lingered by this loop.
4505 // unneeded(nai) will be false and we'll call unlinger() below which would
4506 // be bad, so handle it here.
4507 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004508 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004509 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004510 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004511 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004512 }
4513 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004514 if (isNewDefault) {
4515 // Notify system services that this network is up.
4516 makeDefault(newNetwork);
4517 synchronized (ConnectivityService.this) {
4518 // have a new default network, release the transition wakelock in
4519 // a second if it's held. The second pause is to allow apps
4520 // to reconnect over the new network
4521 if (mNetTransitionWakeLock.isHeld()) {
4522 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4523 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4524 mNetTransitionWakeLockSerialNumber, 0),
4525 1000);
4526 }
4527 }
4528 }
4529
4530 // do this after the default net is switched, but
4531 // before LegacyTypeTracker sends legacy broadcasts
4532 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4533
4534 if (isNewDefault) {
4535 // Maintain the illusion: since the legacy API only
4536 // understands one network at a time, we must pretend
4537 // that the current default network disconnected before
4538 // the new one connected.
4539 if (oldDefaultNetwork != null) {
4540 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4541 oldDefaultNetwork, true);
4542 }
4543 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4544 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4545 notifyLockdownVpn(newNetwork);
4546 }
4547
Robert Greenwalt7b816022014-04-18 15:25:25 -07004548 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004549 // Notify battery stats service about this network, both the normal
4550 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004551 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004552 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004553 final IBatteryStats bs = BatteryStatsService.getService();
4554 final int type = newNetwork.networkInfo.getType();
4555
4556 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4557 bs.noteNetworkInterfaceType(baseIface, type);
4558 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4559 final String stackedIface = stacked.getInterfaceName();
4560 bs.noteNetworkInterfaceType(stackedIface, type);
4561 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4562 }
4563 } catch (RemoteException ignored) {
4564 }
4565
Robert Greenwalt152ed372014-12-17 17:19:53 -08004566 // This has to happen after the notifyNetworkCallbacks as that tickles each
4567 // ConnectivityManager instance so that legacy requests correctly bind dns
4568 // requests to this network. The legacy users are listening for this bcast
4569 // and will generally do a dns request so they can ensureRouteToHost and if
4570 // they do that before the callbacks happen they'll use the default network.
4571 //
4572 // TODO: Is there still a race here? We send the broadcast
4573 // after sending the callback, but if the app can receive the
4574 // broadcast before the callback, it might still break.
4575 //
4576 // This *does* introduce a race where if the user uses the new api
4577 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4578 // they may get old info. Reverse this after the old startUsing api is removed.
4579 // This is on top of the multiple intent sequencing referenced in the todo above.
4580 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4581 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4582 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4583 // legacy type tracker filters out repeat adds
4584 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4585 }
4586 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004587
4588 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4589 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4590 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4591 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4592 if (newNetwork.isVPN()) {
4593 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4594 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004595 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004596 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4597 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004598 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004599 if (DBG) log("Reaping " + nai.name());
4600 teardownUnneededNetwork(nai);
4601 }
4602 }
4603 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004604 }
4605
Paul Jensen1c7ba022015-06-16 14:27:36 -04004606 /**
4607 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4608 * being disconnected.
4609 * @param changed If only one Network's score or capabilities have been modified since the last
4610 * time this function was called, pass this Network in this argument, otherwise pass
4611 * null.
4612 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4613 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4614 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4615 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4616 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004617 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004618 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004619 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4620 // to avoid the slowness. It is not simply enough to process just "changed", for
4621 // example in the case where "changed"'s score decreases and another network should begin
4622 // satifying a NetworkRequest that "changed" currently satisfies.
4623
4624 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4625 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4626 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004627 if (changed != null && oldScore < changed.getCurrentScore()) {
4628 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004629 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004630 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4631 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4632 // Rematch higher scoring networks first to prevent requests first matching a lower
4633 // scoring network and then a higher scoring network, which could produce multiple
4634 // callbacks and inadvertently unlinger networks.
4635 Arrays.sort(nais);
4636 for (NetworkAgentInfo nai : nais) {
4637 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004638 // Only reap the last time through the loop. Reaping before all rematching
4639 // is complete could incorrectly teardown a network that hasn't yet been
4640 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004641 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004642 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004643 }
4644 }
4645 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004646
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004647 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004648 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004649 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004650 // For now only update icons for default connection.
4651 // TODO: Update WiFi and cellular icons separately. b/17237507
4652 if (!isDefaultNetwork(nai)) return;
4653
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004654 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004655 // Don't repeat publish.
4656 if (newInetCondition == mDefaultInetConditionPublished) return;
4657
4658 mDefaultInetConditionPublished = newInetCondition;
4659 sendInetConditionBroadcast(nai.networkInfo);
4660 }
4661
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004662 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4663 if (mLockdownTracker != null) {
4664 if (nai != null && nai.isVPN()) {
4665 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4666 } else {
4667 mLockdownTracker.onNetworkInfoChanged();
4668 }
4669 }
4670 }
4671
Robert Greenwalt7b816022014-04-18 15:25:25 -07004672 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4673 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004674 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004675 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004676 synchronized (networkAgent) {
4677 oldInfo = networkAgent.networkInfo;
4678 networkAgent.networkInfo = newInfo;
4679 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004680 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004681
4682 if (oldInfo != null && oldInfo.getState() == state) {
4683 if (VDBG) log("ignoring duplicate network state non-change");
4684 return;
4685 }
4686 if (DBG) {
4687 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4688 (oldInfo == null ? "null" : oldInfo.getState()) +
4689 " to " + state);
4690 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004691
Paul Jenseneec75412014-08-04 12:21:19 -04004692 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004693 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004694 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004695 if (networkAgent.isVPN()) {
4696 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004697 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4698 (networkAgent.networkMisc == null ||
4699 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004700 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004701 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4702 networkAgent.networkCapabilities.hasCapability(
4703 NET_CAPABILITY_NOT_RESTRICTED) ?
4704 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004705 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004706 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004707 loge("Error creating network " + networkAgent.network.netId + ": "
4708 + e.getMessage());
4709 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004710 }
Paul Jenseneec75412014-08-04 12:21:19 -04004711 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004712 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004713 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004714
Paul Jensenca8f16a2014-05-09 12:47:55 -04004715 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004716 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004717
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004718 if (networkAgent.isVPN()) {
4719 // Temporarily disable the default proxy (not global).
4720 synchronized (mProxyLock) {
4721 if (!mDefaultProxyDisabled) {
4722 mDefaultProxyDisabled = true;
4723 if (mGlobalProxy == null && mDefaultProxy != null) {
4724 sendProxyBroadcast(null);
4725 }
4726 }
4727 }
4728 // TODO: support proxy per network.
4729 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004730
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004731 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4732 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4733 // capabilities, so it only needs to be done once on initial connect, not every time the
4734 // network's capabilities change. Note that we do this before rematching the network,
4735 // so we could decide to tear it down immediately afterwards. That's fine though - on
4736 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4737 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004738 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004739
Paul Jensen2161a8e2014-09-11 11:00:39 -04004740 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004741 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004742
4743 // This has to happen after matching the requests, because callbacks are just requests.
4744 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004745 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004746 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004747 if (networkAgent.isVPN()) {
4748 synchronized (mProxyLock) {
4749 if (mDefaultProxyDisabled) {
4750 mDefaultProxyDisabled = false;
4751 if (mGlobalProxy == null && mDefaultProxy != null) {
4752 sendProxyBroadcast(mDefaultProxy);
4753 }
4754 }
4755 }
4756 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004757 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4758 state == NetworkInfo.State.SUSPENDED) {
4759 // going into or coming out of SUSPEND: rescore and notify
4760 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004761 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004762 }
4763 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4764 ConnectivityManager.CALLBACK_SUSPENDED :
4765 ConnectivityManager.CALLBACK_RESUMED));
4766 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004767 }
4768 }
4769
Robert Greenwaltac96c522014-06-03 16:43:57 -07004770 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4771 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004772 if (score < 0) {
4773 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4774 "). Bumping score to min of 0");
4775 score = 0;
4776 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004777
Paul Jensen2161a8e2014-09-11 11:00:39 -04004778 final int oldScore = nai.getCurrentScore();
4779 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004780
Paul Jensen85cf78e2015-06-25 13:25:07 -04004781 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004782
Paul Jensenc8b9a742014-09-30 15:37:41 -04004783 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004784 }
4785
Robert Greenwalt9258c642014-03-26 16:47:06 -07004786 // notify only this one new request of the current state
4787 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4788 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4789 // TODO - read state from monitor to decide what to send.
4790// if (nai.networkMonitor.isLingering()) {
4791// notifyType = NetworkCallbacks.LOSING;
4792// } else if (nai.networkMonitor.isEvaluating()) {
4793// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4794// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004795 if (nri.mPendingIntent == null) {
4796 callCallbackForRequest(nri, nai, notifyType);
4797 } else {
4798 sendPendingIntentForRequest(nri, nai, notifyType);
4799 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004800 }
4801
Robert Greenwalt8d482522015-06-24 13:23:42 -07004802 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004803 // The NetworkInfo we actually send out has no bearing on the real
4804 // state of affairs. For example, if the default connection is mobile,
4805 // and a request for HIPRI has just gone away, we need to pretend that
4806 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4807 // the state to DISCONNECTED, even though the network is of type MOBILE
4808 // and is still connected.
4809 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4810 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004811 if (state != DetailedState.DISCONNECTED) {
4812 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004813 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004814 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004815 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004816 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4817 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4818 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4819 if (info.isFailover()) {
4820 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4821 nai.networkInfo.setFailover(false);
4822 }
4823 if (info.getReason() != null) {
4824 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4825 }
4826 if (info.getExtraInfo() != null) {
4827 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4828 }
4829 NetworkAgentInfo newDefaultAgent = null;
4830 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004831 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004832 if (newDefaultAgent != null) {
4833 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4834 newDefaultAgent.networkInfo);
4835 } else {
4836 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4837 }
4838 }
4839 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4840 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004841 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004842 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004843 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004844 }
4845 }
4846 }
4847
Robert Greenwalt7b816022014-04-18 15:25:25 -07004848 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004849 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004850 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004851 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4852 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4853 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004854 if (nri.mPendingIntent == null) {
4855 callCallbackForRequest(nri, networkAgent, notifyType);
4856 } else {
4857 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4858 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004859 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004860 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004861
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004862 private String notifyTypeToName(int notifyType) {
4863 switch (notifyType) {
4864 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4865 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4866 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4867 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4868 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4869 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4870 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4871 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4872 }
4873 return "UNKNOWN";
4874 }
4875
Jeff Sharkey69736342014-12-08 14:50:12 -08004876 /**
4877 * Notify other system services that set of active ifaces has changed.
4878 */
4879 private void notifyIfacesChanged() {
4880 try {
4881 mStatsService.forceUpdateIfaces();
4882 } catch (Exception ignored) {
4883 }
4884 }
4885
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004886 @Override
4887 public boolean addVpnAddress(String address, int prefixLength) {
4888 throwIfLockdownEnabled();
4889 int user = UserHandle.getUserId(Binder.getCallingUid());
4890 synchronized (mVpns) {
4891 return mVpns.get(user).addAddress(address, prefixLength);
4892 }
4893 }
4894
4895 @Override
4896 public boolean removeVpnAddress(String address, int prefixLength) {
4897 throwIfLockdownEnabled();
4898 int user = UserHandle.getUserId(Binder.getCallingUid());
4899 synchronized (mVpns) {
4900 return mVpns.get(user).removeAddress(address, prefixLength);
4901 }
4902 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004903
4904 @Override
4905 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4906 throwIfLockdownEnabled();
4907 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004908 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004909 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004910 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004911 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004912 if (success) {
4913 notifyIfacesChanged();
4914 }
4915 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004916 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004917
4918 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08004919 public String getCaptivePortalServerUrl() {
4920 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
4921 }
4922
4923 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004924 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4925 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4926 enforceKeepalivePermission();
4927 mKeepaliveTracker.startNattKeepalive(
4928 getNetworkAgentInfoForNetwork(network),
4929 intervalSeconds, messenger, binder,
4930 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4931 }
4932
4933 @Override
4934 public void stopKeepalive(Network network, int slot) {
4935 mHandler.sendMessage(mHandler.obtainMessage(
4936 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4937 }
4938
4939 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07004940 public void factoryReset() {
4941 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004942
4943 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4944 return;
4945 }
4946
Robin Lee3b3dd942015-05-12 18:14:58 +01004947 final int userId = UserHandle.getCallingUserId();
4948
Stuart Scottf1fb3972015-04-02 18:00:02 -07004949 // Turn airplane mode off
4950 setAirplaneMode(false);
4951
Stuart Scotte3e314d2015-04-20 14:07:45 -07004952 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4953 // Untether
4954 for (String tether : getTetheredIfaces()) {
4955 untether(tether);
4956 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004957 }
4958
Stuart Scotte3e314d2015-04-20 14:07:45 -07004959 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4960 // Turn VPN off
4961 VpnConfig vpnConfig = getVpnConfig(userId);
4962 if (vpnConfig != null) {
4963 if (vpnConfig.legacy) {
4964 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4965 } else {
4966 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4967 // in the future without user intervention.
4968 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004969
Stuart Scotte3e314d2015-04-20 14:07:45 -07004970 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4971 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004972 }
4973 }
4974 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004975
4976 @VisibleForTesting
4977 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4978 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4979 return new NetworkMonitor(context, handler, nai, defaultRequest);
4980 }
4981
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004982}