blob: 2bb93709f69d91c3999e9e587698f9a4b9b3035c [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);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700756 mContext.registerReceiverAsUser(
757 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900758
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700759 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700760 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700761 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700762 } catch (RemoteException e) {
763 loge("Error registering observer :" + e);
764 }
765
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700766 if (DBG) {
767 mInetLog = new ArrayList();
768 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700769
Erik Klineda4bfa82015-04-30 12:58:40 +0900770 mSettingsObserver = new SettingsObserver(mContext, mHandler);
771 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800772
John Spurlockbf991a82013-06-24 14:20:23 -0400773 mDataConnectionStats = new DataConnectionStats(mContext);
774 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400775
Jason Monkdecd2952013-10-10 14:02:51 -0400776 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700777
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400778 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900779
780 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700782
Erik Klineda4bfa82015-04-30 12:58:40 +0900783 private NetworkRequest createInternetRequestForTransport(int transportType) {
784 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900785 netCap.addCapability(NET_CAPABILITY_INTERNET);
786 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900787 if (transportType > -1) {
788 netCap.addTransportType(transportType);
789 }
790 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
791 }
792
793 private void handleMobileDataAlwaysOn() {
794 final boolean enable = (Settings.Global.getInt(
795 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
796 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
797 if (enable == isEnabled) {
798 return; // Nothing to do.
799 }
800
801 if (enable) {
802 handleRegisterNetworkRequest(new NetworkRequestInfo(
803 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
804 } else {
805 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
806 }
807 }
808
809 private void registerSettingsCallbacks() {
810 // Watch for global HTTP proxy changes.
811 mSettingsObserver.observe(
812 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
813 EVENT_APPLY_GLOBAL_HTTP_PROXY);
814
815 // Watch for whether or not to keep mobile data always on.
816 mSettingsObserver.observe(
817 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
818 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
819 }
820
Robert Greenwalt34524f02014-05-18 16:22:10 -0700821 private synchronized int nextNetworkRequestId() {
822 return mNextNetworkRequestId++;
823 }
824
Paul Jensen67b0b072015-06-10 11:22:17 -0400825 @VisibleForTesting
826 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400827 synchronized (mNetworkForNetId) {
828 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
829 int netId = mNextNetId;
830 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
831 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500832 if (!mNetIdInUse.get(netId)) {
833 mNetIdInUse.put(netId, true);
834 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400835 }
836 }
837 }
838 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700839 }
840
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841 private NetworkState getFilteredNetworkState(int networkType, int uid) {
842 NetworkInfo info = null;
843 LinkProperties lp = null;
844 NetworkCapabilities nc = null;
845 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800846 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847
848 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
849 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
850 if (nai != null) {
851 synchronized (nai) {
852 info = new NetworkInfo(nai.networkInfo);
853 lp = new LinkProperties(nai.linkProperties);
854 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400855 // Network objects are outwardly immutable so there is no point to duplicating.
856 // Duplicating also precludes sharing socket factories and connection pools.
857 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800858 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859 }
860 info.setType(networkType);
861 } else {
862 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
863 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
864 info.setIsAvailable(true);
865 lp = new LinkProperties();
866 nc = new NetworkCapabilities();
867 network = null;
868 }
869 info = getFilteredNetworkInfo(info, lp, uid);
870 }
871
Jeff Sharkey32566012014-12-02 18:30:14 -0800872 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400873 }
874
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800875 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
876 if (network == null) {
877 return null;
878 }
879 synchronized (mNetworkForNetId) {
880 return mNetworkForNetId.get(network.netId);
881 }
882 };
883
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900884 private Network[] getVpnUnderlyingNetworks(int uid) {
885 if (!mLockdownEnabled) {
886 int user = UserHandle.getUserId(uid);
887 synchronized (mVpns) {
888 Vpn vpn = mVpns.get(user);
889 if (vpn != null && vpn.appliesToUid(uid)) {
890 return vpn.getUnderlyingNetworks();
891 }
892 }
893 }
894 return null;
895 }
896
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800897 private NetworkState getUnfilteredActiveNetworkState(int uid) {
898 NetworkInfo info = null;
899 LinkProperties lp = null;
900 NetworkCapabilities nc = null;
901 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800902 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800903
Paul Jensen85cf78e2015-06-25 13:25:07 -0400904 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800905
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900906 final Network[] networks = getVpnUnderlyingNetworks(uid);
907 if (networks != null) {
908 // getUnderlyingNetworks() returns:
909 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
910 // empty array => the VPN explicitly said "no default network".
911 // non-empty array => the VPN specified one or more default networks; we use the
912 // first one.
913 if (networks.length > 0) {
914 nai = getNetworkAgentInfoForNetwork(networks[0]);
915 } else {
916 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800917 }
918 }
919
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800920 if (nai != null) {
921 synchronized (nai) {
922 info = new NetworkInfo(nai.networkInfo);
923 lp = new LinkProperties(nai.linkProperties);
924 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400925 // Network objects are outwardly immutable so there is no point to duplicating.
926 // Duplicating also precludes sharing socket factories and connection pools.
927 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800928 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800929 }
930 }
931
Jeff Sharkey32566012014-12-02 18:30:14 -0800932 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400933 }
934
935 /**
936 * Check if UID should be blocked from using the network with the given LinkProperties.
937 */
938 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700939 final boolean networkCostly;
940 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700941
Robert Greenwalt12e67352014-05-13 21:41:06 -0700942 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700943 synchronized (mRulesLock) {
944 networkCostly = mMeteredIfaces.contains(iface);
945 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700946 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700947
Jeff Sharkeydc988062015-09-14 10:09:47 -0700948 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700949 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700950 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
951 return true;
952 } else {
953 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700954 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700955 }
956
957 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700958 * Return a filtered {@link NetworkInfo}, potentially marked
959 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800960 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700961 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800962 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
963 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400964 // network is blocked; clone and override state
965 info = new NetworkInfo(info);
966 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900967 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900968 log("returning Blocked NetworkInfo for ifname=" +
969 lp.getInterfaceName() + ", uid=" + uid);
970 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700971 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800972 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700973 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900974 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700975 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700976 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700977 }
978
979 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 * Return NetworkInfo for the active (i.e., connected) network interface.
981 * It is assumed that at most one network is active at a time. If more
982 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700983 * @return the info for the active network, or {@code null} if none is
984 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700986 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700988 enforceAccessPermission();
989 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800990 NetworkState state = getUnfilteredActiveNetworkState(uid);
991 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993
Paul Jensen31a94f42015-02-13 14:18:39 -0500994 @Override
995 public Network getActiveNetwork() {
996 enforceAccessPermission();
997 final int uid = Binder.getCallingUid();
998 final int user = UserHandle.getUserId(uid);
999 int vpnNetId = NETID_UNSET;
1000 synchronized (mVpns) {
1001 final Vpn vpn = mVpns.get(user);
1002 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1003 }
1004 NetworkAgentInfo nai;
1005 if (vpnNetId != NETID_UNSET) {
1006 synchronized (mNetworkForNetId) {
1007 nai = mNetworkForNetId.get(vpnNetId);
1008 }
1009 if (nai != null) return nai.network;
1010 }
1011 nai = getDefaultNetwork();
1012 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1013 return nai != null ? nai.network : null;
1014 }
1015
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001016 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1017 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 final int uid = Binder.getCallingUid();
1019 NetworkState state = getUnfilteredActiveNetworkState(uid);
1020 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001021 }
1022
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001023 @Override
1024 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1025 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001026 NetworkState state = getUnfilteredActiveNetworkState(uid);
1027 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001028 }
1029
1030 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 public NetworkInfo getNetworkInfo(int networkType) {
1032 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001034 if (getVpnUnderlyingNetworks(uid) != null) {
1035 // A VPN is active, so we may need to return one of its underlying networks. This
1036 // information is not available in LegacyTypeTracker, so we have to get it from
1037 // getUnfilteredActiveNetworkState.
1038 NetworkState state = getUnfilteredActiveNetworkState(uid);
1039 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1040 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1041 }
1042 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001043 NetworkState state = getFilteredNetworkState(networkType, uid);
1044 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 @Override
1048 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1049 enforceAccessPermission();
1050 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001051 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001052 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1053 if (nai != null) {
1054 synchronized (nai) {
1055 info = new NetworkInfo(nai.networkInfo);
1056 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 }
1058 }
1059 return info;
1060 }
1061
1062 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 public NetworkInfo[] getAllNetworkInfo() {
1064 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001065 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001066 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1067 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001068 NetworkInfo info = getNetworkInfo(networkType);
1069 if (info != null) {
1070 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001073 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001076 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001077 public Network getNetworkForType(int networkType) {
1078 enforceAccessPermission();
1079 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001080 NetworkState state = getFilteredNetworkState(networkType, uid);
1081 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1082 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001083 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001084 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001085 }
1086
1087 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001088 public Network[] getAllNetworks() {
1089 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001090 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001091 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001092 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001093 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001094 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001095 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001096 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001097 }
1098
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001099 @Override
1100 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1101 // The basic principle is: if an app's traffic could possibly go over a
1102 // network, without the app doing anything multinetwork-specific,
1103 // (hence, by "default"), then include that network's capabilities in
1104 // the array.
1105 //
1106 // In the normal case, app traffic only goes over the system's default
1107 // network connection, so that's the only network returned.
1108 //
1109 // With a VPN in force, some app traffic may go into the VPN, and thus
1110 // over whatever underlying networks the VPN specifies, while other app
1111 // traffic may go over the system default network (e.g.: a split-tunnel
1112 // VPN, or an app disallowed by the VPN), so the set of networks
1113 // returned includes the VPN's underlying networks and the system
1114 // default.
1115 enforceAccessPermission();
1116
1117 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1118
1119 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001120 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001121 if (nc != null) {
1122 result.put(nai.network, nc);
1123 }
1124
1125 if (!mLockdownEnabled) {
1126 synchronized (mVpns) {
1127 Vpn vpn = mVpns.get(userId);
1128 if (vpn != null) {
1129 Network[] networks = vpn.getUnderlyingNetworks();
1130 if (networks != null) {
1131 for (Network network : networks) {
1132 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001133 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001134 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001135 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001136 }
1137 }
1138 }
1139 }
1140 }
1141 }
1142
1143 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1144 out = result.values().toArray(out);
1145 return out;
1146 }
1147
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001148 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001149 public boolean isNetworkSupported(int networkType) {
1150 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001151 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001152 }
1153
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001154 /**
1155 * Return LinkProperties for the active (i.e., connected) default
1156 * network interface. It is assumed that at most one default network
1157 * is active at a time. If more than one is active, it is indeterminate
1158 * which will be returned.
1159 * @return the ip properties for the active network, or {@code null} if
1160 * none is active
1161 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001163 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001164 enforceAccessPermission();
1165 final int uid = Binder.getCallingUid();
1166 NetworkState state = getUnfilteredActiveNetworkState(uid);
1167 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001168 }
1169
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001170 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001171 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001172 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001173 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1174 if (nai != null) {
1175 synchronized (nai) {
1176 return new LinkProperties(nai.linkProperties);
1177 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001178 }
1179 return null;
1180 }
1181
Robert Greenwalt12e67352014-05-13 21:41:06 -07001182 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001183 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001184 public LinkProperties getLinkProperties(Network network) {
1185 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 if (nai != null) {
1188 synchronized (nai) {
1189 return new LinkProperties(nai.linkProperties);
1190 }
1191 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001192 return null;
1193 }
1194
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001195 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001196 if (nai != null) {
1197 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001198 if (nai.networkCapabilities != null) {
1199 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001200 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001201 }
1202 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001203 return null;
1204 }
1205
1206 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001207 public NetworkCapabilities getNetworkCapabilities(Network network) {
1208 enforceAccessPermission();
1209 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1210 }
1211
1212 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001213 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001214 // Require internal since we're handing out IMSI details
1215 enforceConnectivityInternalPermission();
1216
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001217 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001218 for (Network network : getAllNetworks()) {
1219 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1220 if (nai != null) {
1221 synchronized (nai) {
1222 final String subscriberId = (nai.networkMisc != null)
1223 ? nai.networkMisc.subscriberId : null;
1224 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1225 nai.networkCapabilities, network, subscriberId, null));
1226 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001227 }
1228 }
1229 return result.toArray(new NetworkState[result.size()]);
1230 }
1231
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001232 @Override
1233 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1234 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001235 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001236 final long token = Binder.clearCallingIdentity();
1237 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001238 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1239 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001240 try {
1241 return mPolicyManager.getNetworkQuotaInfo(state);
1242 } catch (RemoteException e) {
1243 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001244 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001245 return null;
1246 } finally {
1247 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001248 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001249 }
1250
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001251 @Override
1252 public boolean isActiveNetworkMetered() {
1253 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001254 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001255 final long token = Binder.clearCallingIdentity();
1256 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001257 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001258 } finally {
1259 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001260 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001261 }
1262
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001263 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1264 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1265 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001266 try {
1267 return mPolicyManager.isNetworkMetered(state);
1268 } catch (RemoteException e) {
1269 }
1270 }
1271 return false;
1272 }
1273
Jeff Sharkey216c1812012-08-05 14:29:23 -07001274 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1275 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001276 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001277 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001278 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001279 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001280 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001281
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001282 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 * Ensure that a network route exists to deliver traffic to the specified
1284 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001285 * @param networkType the type of the network over which traffic to the
1286 * specified host is to be routed
1287 * @param hostAddress the IP address of the host to which the route is
1288 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 * @return {@code true} on success, {@code false} on failure
1290 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001291 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001293 if (mProtectedNetworks.contains(networkType)) {
1294 enforceConnectivityInternalPermission();
1295 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001296
Chad Brubakerc0234532014-02-14 13:24:29 -08001297 InetAddress addr;
1298 try {
1299 addr = InetAddress.getByAddress(hostAddress);
1300 } catch (UnknownHostException e) {
1301 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1302 return false;
1303 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001306 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 return false;
1308 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001309
1310 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1311 if (nai == null) {
1312 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1313 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1314 } else {
1315 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1316 }
1317 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001318 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001319
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001320 DetailedState netState;
1321 synchronized (nai) {
1322 netState = nai.networkInfo.getDetailedState();
1323 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001324
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001325 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001326 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001327 log("requestRouteToHostAddress on down network "
1328 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001329 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001330 }
1331 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001333
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001334 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001335 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001336 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001337 LinkProperties lp;
1338 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001339 synchronized (nai) {
1340 lp = nai.linkProperties;
1341 netId = nai.network.netId;
1342 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001343 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001344 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1345 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001346 } finally {
1347 Binder.restoreCallingIdentity(token);
1348 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001349 }
1350
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001351 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001352 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001353 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001354 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001355 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001356 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001357 if (bestRoute.getGateway().equals(addr)) {
1358 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001359 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001360 } else {
1361 // if we will connect to this through another route, add a direct route
1362 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001363 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001364 }
1365 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001366 if (DBG) log("Adding legacy route " + bestRoute +
1367 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001368 try {
1369 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1370 } catch (Exception e) {
1371 // never crash - catch them all
1372 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001373 return false;
1374 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001375 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
1377
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001378 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1379 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001380 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001381 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001382 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001383 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001384 }
1385
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001386 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001387 // skip update when we've already applied rules
1388 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1389 if (oldRules == uidRules) return;
1390
1391 mUidRules.put(uid, uidRules);
1392 }
1393
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001394 // TODO: notify UID when it has requested targeted updates
1395 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001396
1397 @Override
1398 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001399 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001400 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001401 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001402 }
1403
1404 synchronized (mRulesLock) {
1405 mMeteredIfaces.clear();
1406 for (String iface : meteredIfaces) {
1407 mMeteredIfaces.add(iface);
1408 }
1409 }
1410 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001411
1412 @Override
1413 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1414 // caller is NPMS, since we only register with them
1415 if (LOGD_RULES) {
1416 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1417 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001418 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001419 };
1420
Robin Lee3b3dd942015-05-12 18:14:58 +01001421 /**
1422 * Require that the caller is either in the same user or has appropriate permission to interact
1423 * across users.
1424 *
1425 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1426 */
1427 private void enforceCrossUserPermission(int userId) {
1428 if (userId == UserHandle.getCallingUserId()) {
1429 // Not a cross-user call.
1430 return;
1431 }
1432 mContext.enforceCallingOrSelfPermission(
1433 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1434 "ConnectivityService");
1435 }
1436
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001437 private void enforceInternetPermission() {
1438 mContext.enforceCallingOrSelfPermission(
1439 android.Manifest.permission.INTERNET,
1440 "ConnectivityService");
1441 }
1442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001444 mContext.enforceCallingOrSelfPermission(
1445 android.Manifest.permission.ACCESS_NETWORK_STATE,
1446 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
1448
1449 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001450 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 }
1452
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001453 private void enforceTetherAccessPermission() {
1454 mContext.enforceCallingOrSelfPermission(
1455 android.Manifest.permission.ACCESS_NETWORK_STATE,
1456 "ConnectivityService");
1457 }
1458
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001459 private void enforceConnectivityInternalPermission() {
1460 mContext.enforceCallingOrSelfPermission(
1461 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1462 "ConnectivityService");
1463 }
1464
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001465 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001466 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001467 }
1468
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001469 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001470 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001471 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001472 }
1473
1474 private void sendInetConditionBroadcast(NetworkInfo info) {
1475 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1476 }
1477
Wink Saville628b0852011-08-04 15:01:58 -07001478 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001479 if (mLockdownTracker != null) {
1480 info = mLockdownTracker.augmentNetworkInfo(info);
1481 }
1482
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001483 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001484 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001485 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 if (info.isFailover()) {
1487 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1488 info.setFailover(false);
1489 }
1490 if (info.getReason() != null) {
1491 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1492 }
1493 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001494 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1495 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001497 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001498 return intent;
1499 }
1500
1501 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1502 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1503 }
1504
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001505 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001506 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1507 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1508 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001509 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001510 final long ident = Binder.clearCallingIdentity();
1511 try {
1512 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1513 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1514 } finally {
1515 Binder.restoreCallingIdentity(ident);
1516 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001517 }
1518
Mike Lockwood0f79b542009-08-14 14:18:49 -04001519 private void sendStickyBroadcast(Intent intent) {
1520 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001521 if (!mSystemReady) {
1522 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001523 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001524 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001525 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001526 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001527 }
1528
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001529 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001530 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001531 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001532 final NetworkInfo ni = intent.getParcelableExtra(
1533 ConnectivityManager.EXTRA_NETWORK_INFO);
1534 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1535 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1536 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001537 } else {
1538 BroadcastOptions opts = BroadcastOptions.makeBasic();
1539 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1540 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001541 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001542 final IBatteryStats bs = BatteryStatsService.getService();
1543 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001544 bs.noteConnectivityChanged(intent.getIntExtra(
1545 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1546 ni != null ? ni.getState().toString() : "?");
1547 } catch (RemoteException e) {
1548 }
1549 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001550 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001551 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001552 } finally {
1553 Binder.restoreCallingIdentity(ident);
1554 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001555 }
1556 }
1557
1558 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001559 loadGlobalProxy();
1560
Mike Lockwood0f79b542009-08-14 14:18:49 -04001561 synchronized(this) {
1562 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001563 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001564 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001565 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001566 }
1567 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001568 // load the global proxy at startup
1569 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001570
Robin Lee244ce8e2016-01-05 18:03:46 +00001571 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1572 // for user to unlock device too.
1573 updateLockdownVpn();
1574 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1575 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.ALL, filter, null, null);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001576
Erik Klineda4bfa82015-04-30 12:58:40 +09001577 // Configure whether mobile data is always on.
1578 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1579
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001580 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001581
1582 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001583 }
1584
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001585 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1586 @Override
1587 public void onReceive(Context context, Intent intent) {
Robin Lee244ce8e2016-01-05 18:03:46 +00001588 // User that sent this intent = user that was just unlocked
1589 final int unlockedUser = getSendingUserId();
1590
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001591 // Try creating lockdown tracker, since user present usually means
1592 // unlocked keystore.
Robin Lee244ce8e2016-01-05 18:03:46 +00001593 if (mUserManager.getUserInfo(unlockedUser).isPrimary() &&
1594 LockdownVpnTracker.isEnabled()) {
1595 updateLockdownVpn();
1596 } else {
1597 updateAlwaysOnVpn(unlockedUser);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001598 }
1599 }
1600 };
1601
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001602 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001603 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001604 *
1605 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001606 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001607 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001608 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1609 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001610
1611 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001612 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001613
Robert Greenwalt7b816022014-04-18 15:25:25 -07001614 if (networkAgent.networkCapabilities.hasTransport(
1615 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001616 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1617 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001618 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001619 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001620 } else if (networkAgent.networkCapabilities.hasTransport(
1621 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001622 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1623 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001624 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001625 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001626 } else {
1627 // do not track any other networks
1628 timeout = 0;
1629 }
1630
Robert Greenwalt7b816022014-04-18 15:25:25 -07001631 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001632 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001633 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001634 } catch (Exception e) {
1635 // You shall not crash!
1636 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001637 }
1638 }
1639 }
1640
1641 /**
1642 * Remove data activity tracking when network disconnects.
1643 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001644 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1645 final String iface = networkAgent.linkProperties.getInterfaceName();
1646 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001647
Robert Greenwalt7b816022014-04-18 15:25:25 -07001648 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1649 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001650 try {
1651 // the call fails silently if no idletimer setup for this interface
1652 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001653 } catch (Exception e) {
1654 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001655 }
1656 }
1657 }
1658
1659 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001660 * Reads the network specific MTU size from reources.
1661 * and set it on it's iface.
1662 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001663 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1664 final String iface = newLp.getInterfaceName();
1665 final int mtu = newLp.getMtu();
1666 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1667 if (VDBG) log("identical MTU - not setting");
1668 return;
1669 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001670
Robert Greenwalt43074032014-08-15 17:53:05 -07001671 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001672 loge("Unexpected mtu value: " + mtu + ", " + iface);
1673 return;
1674 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001675
w1997615afd812014-08-05 15:18:11 -07001676 // Cannot set MTU without interface name
1677 if (TextUtils.isEmpty(iface)) {
1678 loge("Setting MTU size with null iface.");
1679 return;
1680 }
1681
Robert Greenwalt7b816022014-04-18 15:25:25 -07001682 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001683 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001684 mNetd.setMtu(iface, mtu);
1685 } catch (Exception e) {
1686 Slog.e(TAG, "exception in setMtu()" + e);
1687 }
1688 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001689
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001690 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001691 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1692
1693 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001694 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001695 protected int getDefaultTcpRwnd() {
1696 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1697 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001698
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001699 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1700 if (isDefaultNetwork(nai) == false) {
1701 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001702 }
1703
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001704 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1705 String[] values = null;
1706 if (tcpBufferSizes != null) {
1707 values = tcpBufferSizes.split(",");
1708 }
1709
1710 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001711 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001712 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1713 values = tcpBufferSizes.split(",");
1714 }
1715
1716 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1717
1718 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001719 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001720
1721 final String prefix = "/sys/kernel/ipv4/tcp_";
1722 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1723 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1724 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1725 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1726 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1727 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1728 mCurrentTcpBufferSizes = tcpBufferSizes;
1729 } catch (IOException e) {
1730 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001731 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001732
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001733 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001734 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001735 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1736 if (rwndValue != 0) {
1737 SystemProperties.set(sysctlKey, rwndValue.toString());
1738 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001739 }
1740
Mattias Falk8b47b362011-08-23 14:15:13 +02001741 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001742 /*
1743 * Tell the VMs to toss their DNS caches
1744 */
1745 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1746 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001747 /*
1748 * Connectivity events can happen before boot has completed ...
1749 */
1750 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001751 final long ident = Binder.clearCallingIdentity();
1752 try {
1753 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1754 } finally {
1755 Binder.restoreCallingIdentity(ident);
1756 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001757 }
1758
Robert Greenwalt562cc542014-05-15 18:07:26 -07001759 @Override
1760 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001761 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1762 NETWORK_RESTORE_DELAY_PROP_NAME);
1763 if(restoreDefaultNetworkDelayStr != null &&
1764 restoreDefaultNetworkDelayStr.length() != 0) {
1765 try {
1766 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1767 } catch (NumberFormatException e) {
1768 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001769 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001770 // if the system property isn't set, use the value for the apn type
1771 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1772
1773 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1774 (mNetConfigs[networkType] != null)) {
1775 ret = mNetConfigs[networkType].restoreTime;
1776 }
1777 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001778 }
1779
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001780 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001781 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001782 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001783 }
1784 return false;
1785 }
1786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001788 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1789 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001790 if (mContext.checkCallingOrSelfPermission(
1791 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001792 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001793 pw.println("Permission Denial: can't dump ConnectivityService " +
1794 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1795 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001796 return;
1797 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001798
Erik Kline379747a2015-06-05 17:47:34 +09001799 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001800 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001801 final long DIAG_TIME_MS = 5000;
1802 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1803 // Start gathering diagnostic information.
1804 netDiags.add(new NetworkDiagnostics(
1805 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001806 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001807 DIAG_TIME_MS));
1808 }
1809
1810 for (NetworkDiagnostics netDiag : netDiags) {
1811 pw.println();
1812 netDiag.waitForMeasurements();
1813 netDiag.dump(pw);
1814 }
1815
1816 return;
1817 }
1818
Lorenzo Colittie3805462015-06-03 11:18:24 +09001819 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001820 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001821 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001822 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001823 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001824 pw.println();
1825
Paul Jensen85cf78e2015-06-25 13:25:07 -04001826 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001827 pw.print("Active default network: ");
1828 if (defaultNai == null) {
1829 pw.println("none");
1830 } else {
1831 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001833 pw.println();
1834
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001835 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001836 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001837 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1838 pw.println(nai.toString());
1839 pw.increaseIndent();
1840 pw.println("Requests:");
1841 pw.increaseIndent();
1842 for (int i = 0; i < nai.networkRequests.size(); i++) {
1843 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001844 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001845 pw.decreaseIndent();
1846 pw.println("Lingered:");
1847 pw.increaseIndent();
1848 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1849 pw.decreaseIndent();
1850 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001851 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001852 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001853 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001854
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001855 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001856 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001857 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1858 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001859 }
1860 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001861 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001862
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001863 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001864
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001865 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001866 pw.print("mNetTransitionWakeLock: currently " +
1867 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1868 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1869 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1870 } else {
1871 pw.println(", last requested never");
1872 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001873 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001874
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001875 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001876 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001877
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001878 pw.println();
1879 mKeepaliveTracker.dump(pw);
1880
Lorenzo Colittie3805462015-06-03 11:18:24 +09001881 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001882 pw.println();
1883 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001884 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001885 for(int i = 0; i < mInetLog.size(); i++) {
1886 pw.println(mInetLog.get(i));
1887 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001888 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001889 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001890
1891 if (argsContain(args, "--short") == false) {
1892 pw.println();
1893 synchronized (mValidationLogs) {
1894 pw.println("mValidationLogs (most recent first):");
1895 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1896 pw.println(p.first);
1897 pw.increaseIndent();
1898 p.second.dump(fd, pw, args);
1899 pw.decreaseIndent();
1900 }
1901 }
Erik Kline7523eb32015-07-09 18:24:03 +09001902
1903 pw.println();
1904 pw.println("mNetworkRequestInfoLogs (most recent first):");
1905 pw.increaseIndent();
1906 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1907 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001908 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001909 }
1910
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001911 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001912 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001913 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001914 if (officialNai != null && officialNai.equals(nai)) return true;
1915 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001916 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001917 " - " + nai);
1918 }
1919 return false;
1920 }
1921
Paul Jensenc8b9a742014-09-30 15:37:41 -04001922 private boolean isRequest(NetworkRequest request) {
1923 return mNetworkRequests.get(request).isRequest;
1924 }
1925
Robert Greenwalt42acef32009-08-12 16:08:25 -07001926 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001927 private class NetworkStateTrackerHandler extends Handler {
1928 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001929 super(looper);
1930 }
1931
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001932 @Override
1933 public void handleMessage(Message msg) {
1934 NetworkInfo info;
1935 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001936 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001937 handleAsyncChannelHalfConnect(msg);
1938 break;
1939 }
1940 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1941 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1942 if (nai != null) nai.asyncChannel.disconnect();
1943 break;
1944 }
1945 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1946 handleAsyncChannelDisconnected(msg);
1947 break;
1948 }
1949 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1950 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1951 if (nai == null) {
1952 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1953 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001954 final NetworkCapabilities networkCapabilities =
1955 (NetworkCapabilities)msg.obj;
1956 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1957 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001958 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001959 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001960 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1961 networkCapabilities)) {
1962 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1963 + nai.networkCapabilities + " -> " + networkCapabilities);
1964 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001965 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001966 }
1967 break;
1968 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001969 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1970 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1971 if (nai == null) {
1972 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1973 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001974 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001975 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001976 "; created=" + nai.created);
1977 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001978 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001979 synchronized (nai) {
1980 nai.linkProperties = (LinkProperties)msg.obj;
1981 }
Paul Jenseneec75412014-08-04 12:21:19 -04001982 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001983 }
1984 break;
1985 }
1986 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1987 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1988 if (nai == null) {
1989 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1990 break;
1991 }
1992 info = (NetworkInfo) msg.obj;
1993 updateNetworkInfo(nai, info);
1994 break;
1995 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001996 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1997 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1998 if (nai == null) {
1999 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
2000 break;
2001 }
2002 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002003 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002004 break;
2005 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002006 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
2007 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2008 if (nai == null) {
2009 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
2010 break;
2011 }
2012 try {
2013 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002014 } catch (Exception e) {
2015 // Never crash!
2016 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002017 }
2018 break;
2019 }
2020 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2021 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2022 if (nai == null) {
2023 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2024 break;
2025 }
2026 try {
2027 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002028 } catch (Exception e) {
2029 // Never crash!
2030 loge("Exception in removeVpnUidRanges: " + e);
2031 }
2032 break;
2033 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002034 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2035 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2036 if (nai == null) {
2037 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2038 break;
2039 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002040 if (nai.created && !nai.networkMisc.explicitlySelected) {
2041 loge("ERROR: created network explicitly selected.");
2042 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002043 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002044 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002045 break;
2046 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002047 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2048 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2049 if (nai == null) {
2050 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2051 break;
2052 }
2053 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2054 break;
2055 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002056 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002057 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002058 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2059 final boolean valid =
2060 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002061 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2062 if (valid != nai.lastValidated) {
2063 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002064 nai.lastValidated = valid;
2065 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002066 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002067 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2068 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002069 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002070 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002071 // Let the NetworkAgent know the state of its network
2072 nai.asyncChannel.sendMessage(
2073 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2074 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2075 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002076 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002077 break;
2078 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002079 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002080 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002081 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2082 handleLingerComplete(nai);
2083 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002084 break;
2085 }
Paul Jensen869868be2014-05-15 10:33:05 -04002086 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002087 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002088 final boolean visible = (msg.arg1 != 0);
2089 final NetworkAgentInfo nai;
2090 synchronized (mNetworkForNetId) {
2091 nai = mNetworkForNetId.get(netId);
2092 }
2093 // If captive portal status has changed, update capabilities.
2094 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2095 nai.lastCaptivePortalDetected = visible;
2096 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002097 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002098 }
2099 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002100 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002101 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002102 if (nai == null) {
2103 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2104 break;
2105 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002106 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002107 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2108 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002109 }
Paul Jensen869868be2014-05-15 10:33:05 -04002110 break;
2111 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002112 }
2113 }
2114 }
2115
Paul Jensen85cf78e2015-06-25 13:25:07 -04002116 private void linger(NetworkAgentInfo nai) {
2117 nai.lingering = true;
2118 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2119 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2120 }
2121
Paul Jensen0cc17322014-11-25 15:26:53 -05002122 // Cancel any lingering so the linger timeout doesn't teardown a network.
2123 // This should be called when a network begins satisfying a NetworkRequest.
2124 // Note: depending on what state the NetworkMonitor is in (e.g.,
2125 // if it's awaiting captive portal login, or if validation failed), this
2126 // may trigger a re-evaluation of the network.
2127 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002128 nai.networkLingered.clear();
2129 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002130 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002131 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002132 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2133 }
2134
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 private void handleAsyncChannelHalfConnect(Message msg) {
2136 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002137 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2139 if (VDBG) log("NetworkFactory connected");
2140 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002141 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002142 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002143 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002144 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002145 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002146 }
2147 } else {
2148 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002149 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 }
2151 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2152 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2153 if (VDBG) log("NetworkAgent connected");
2154 // A network agent has requested a connection. Establish the connection.
2155 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2156 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2157 } else {
2158 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002159 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002160 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002161 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002162 synchronized (mNetworkForNetId) {
2163 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002164 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002165 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002166 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002167 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002168 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002169 }
2170 }
2171 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002172
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 private void handleAsyncChannelDisconnected(Message msg) {
2174 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2175 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002176 if (DBG) {
2177 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2178 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002179 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002180 // TODO - if we move the logic to the network agent (have them disconnect
2181 // because they lost all their requests or because their score isn't good)
2182 // then they would disconnect organically, report their new state and then
2183 // disconnect the channel.
2184 if (nai.networkInfo.isConnected()) {
2185 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2186 null, null);
2187 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002188 final boolean wasDefault = isDefaultNetwork(nai);
2189 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002190 mDefaultInetConditionPublished = 0;
2191 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002192 notifyIfacesChanged();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002193 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2194 // by other networks that are already connected. Perhaps that can be done by
2195 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2196 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002197 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002198 mKeepaliveTracker.handleStopAllKeepalives(nai,
2199 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002200 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002201 mNetworkAgentInfos.remove(msg.replyTo);
2202 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002203 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002204 // Remove the NetworkAgent, but don't mark the netId as
2205 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002206 mNetworkForNetId.remove(nai.network.netId);
2207 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002208 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002209 for (int i = 0; i < nai.networkRequests.size(); i++) {
2210 NetworkRequest request = nai.networkRequests.valueAt(i);
2211 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2212 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2213 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002214 sendUpdatedScoreToFactories(request, 0);
2215 }
2216 }
2217 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2218 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002219 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002220 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002221 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002222 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002223 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002224 if (nai.created) {
2225 // Tell netd to clean up the configuration for this network
2226 // (routing rules, DNS, etc).
2227 // This may be slow as it requires a lot of netd shelling out to ip and
2228 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2229 // after we've rematched networks with requests which should make a potential
2230 // fallback network the default or requested a new network from the
2231 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2232 // long time.
2233 try {
2234 mNetd.removeNetwork(nai.network.netId);
2235 } catch (Exception e) {
2236 loge("Exception removing network: " + e);
2237 }
2238 }
2239 synchronized (mNetworkForNetId) {
2240 mNetIdInUse.delete(nai.network.netId);
2241 }
2242 } else {
2243 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2244 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002245 }
2246 }
2247
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002248 // If this method proves to be too slow then we can maintain a separate
2249 // pendingIntent => NetworkRequestInfo map.
2250 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2251 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2252 Intent intent = pendingIntent.getIntent();
2253 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2254 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2255 if (existingPendingIntent != null &&
2256 existingPendingIntent.getIntent().filterEquals(intent)) {
2257 return entry.getValue();
2258 }
2259 }
2260 return null;
2261 }
2262
2263 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2264 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2265
2266 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2267 if (existingRequest != null) { // remove the existing request.
2268 if (DBG) log("Replacing " + existingRequest.request + " with "
2269 + nri.request + " because their intents matched.");
2270 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2271 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002272 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002273 }
2274
Erik Klineda4bfa82015-04-30 12:58:40 +09002275 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002276 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002277 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002278 if (!nri.isRequest) {
2279 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002280 if (nri.request.networkCapabilities.hasSignalStrength() &&
2281 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2282 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002283 }
2284 }
2285 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002286 rematchAllNetworksAndRequests(null, 0);
2287 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2288 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002289 }
2290 }
2291
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002292 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2293 int callingUid) {
2294 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2295 if (nri != null) {
2296 handleReleaseNetworkRequest(nri.request, callingUid);
2297 }
2298 }
2299
Paul Jensen99364842014-12-09 11:43:45 -05002300 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002301 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2302 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002303 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002304 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002305 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2306 // If this Network is already the highest scoring Network for a request, or if
2307 // there is hope for it to become one if it validated, then it is needed.
2308 if (nri.isRequest && nai.satisfies(nri.request) &&
2309 (nai.networkRequests.get(nri.request.requestId) != null ||
2310 // Note that this catches two important cases:
2311 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2312 // is currently satisfying the request. This is desirable when
2313 // cellular ends up validating but WiFi does not.
2314 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002315 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002316 // WiFi ends up validating and out scoring cellular.
2317 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2318 nai.getCurrentScoreAsValidated())) {
2319 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002320 }
2321 }
Paul Jensene0988542015-06-25 15:30:08 -04002322 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002323 }
2324
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002325 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2326 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002327 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002328 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002329 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2330 return;
2331 }
2332 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002333 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002334 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002335 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002336 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002337 // Find all networks that are satisfying this request and remove the request
2338 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002339 // TODO - it's my understanding that for a request there is only a single
2340 // network satisfying it, so this loop is wasteful
2341 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002342 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2343 if (nai.networkRequests.get(nri.request.requestId) != null) {
2344 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002345 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002346 log(" Removing from current network " + nai.name() +
2347 ", leaving " + nai.networkRequests.size() +
2348 " requests.");
2349 }
Paul Jensen99364842014-12-09 11:43:45 -05002350 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002351 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002352 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002353 } else {
2354 // suspect there should only be one pass through here
2355 // but if any were kept do the check below
2356 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002357 }
2358 }
2359 }
2360
Robert Greenwalt51481852015-01-08 14:43:31 -08002361 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2362 if (nai != null) {
2363 mNetworkForRequestId.remove(nri.request.requestId);
2364 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002365 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002366 // that a network connected to serve it, even though the network was already
2367 // connected. Now that this request has gone away, we might have to pretend
2368 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002369 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002370 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2371 boolean doRemove = true;
2372 if (wasKept) {
2373 // check if any of the remaining requests for this network are for the
2374 // same legacy type - if so, don't remove the nai
2375 for (int i = 0; i < nai.networkRequests.size(); i++) {
2376 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2377 if (otherRequest.legacyType == nri.request.legacyType &&
2378 isRequest(otherRequest)) {
2379 if (DBG) log(" still have other legacy request - leaving");
2380 doRemove = false;
2381 }
2382 }
2383 }
2384
2385 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002386 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002387 }
2388 }
2389
Robert Greenwalta67be032014-05-16 15:49:14 -07002390 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002391 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2392 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002393 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002394 } else {
2395 // listens don't have a singular affectedNetwork. Check all networks to see
2396 // if this listen request applies and remove it.
2397 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2398 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002399 if (nri.request.networkCapabilities.hasSignalStrength() &&
2400 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2401 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002402 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002403 }
2404 }
2405 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2406 }
2407 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002408
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002409 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2410 enforceConnectivityInternalPermission();
2411 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2412 accept ? 1 : 0, always ? 1: 0, network));
2413 }
2414
2415 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2416 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2417 " accept=" + accept + " always=" + always);
2418
2419 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2420 if (nai == null) {
2421 // Nothing to do.
2422 return;
2423 }
2424
2425 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002426 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002427 return;
2428 }
2429
2430 if (!nai.networkMisc.explicitlySelected) {
2431 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2432 }
2433
2434 if (accept != nai.networkMisc.acceptUnvalidated) {
2435 int oldScore = nai.getCurrentScore();
2436 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002437 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002438 sendUpdatedScoreToFactories(nai);
2439 }
2440
2441 if (always) {
2442 nai.asyncChannel.sendMessage(
2443 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2444 }
2445
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002446 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002447 // Tell the NetworkAgent to not automatically reconnect to the network.
2448 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2449 // Teardown the nework.
2450 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002451 }
2452
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002453 }
2454
2455 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002456 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002457 mHandler.sendMessageDelayed(
2458 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2459 PROMPT_UNVALIDATED_DELAY_MS);
2460 }
2461
2462 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002463 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002464 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2465
2466 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2467 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002468 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002469 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002470 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2471 return;
2472 }
2473
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002474 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002475 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002476 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2477 intent.setClassName("com.android.settings",
2478 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002479
2480 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2481 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2482 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002483 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002484 }
2485
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002486 private class InternalHandler extends Handler {
2487 public InternalHandler(Looper looper) {
2488 super(looper);
2489 }
2490
2491 @Override
2492 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002493 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002494 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002495 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002496 String causedBy = null;
2497 synchronized (ConnectivityService.this) {
2498 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2499 mNetTransitionWakeLock.isHeld()) {
2500 mNetTransitionWakeLock.release();
2501 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002502 } else {
2503 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002504 }
2505 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002506 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2507 log("Failed to find a new network - expiring NetTransition Wakelock");
2508 } else {
2509 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2510 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002511 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002512 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002513 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002514 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002515 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002516 break;
2517 }
Jason Monkdecd2952013-10-10 14:02:51 -04002518 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002519 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002520 break;
2521 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002522 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002523 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2524 break;
2525 }
2526 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2527 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002528 break;
2529 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002530 case EVENT_REGISTER_NETWORK_AGENT: {
2531 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2532 break;
2533 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002534 case EVENT_REGISTER_NETWORK_REQUEST:
2535 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002536 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002537 break;
2538 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002539 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2540 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002541 handleRegisterNetworkRequestWithIntent(msg);
2542 break;
2543 }
2544 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2545 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2546 break;
2547 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002548 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002549 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002550 break;
2551 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002552 case EVENT_SET_ACCEPT_UNVALIDATED: {
2553 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2554 break;
2555 }
2556 case EVENT_PROMPT_UNVALIDATED: {
2557 handlePromptUnvalidated((Network) msg.obj);
2558 break;
2559 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002560 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2561 handleMobileDataAlwaysOn();
2562 break;
2563 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002564 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2565 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2566 mKeepaliveTracker.handleStartKeepalive(msg);
2567 break;
2568 }
2569 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2570 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2571 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2572 int slot = msg.arg1;
2573 int reason = msg.arg2;
2574 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2575 break;
2576 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002577 case EVENT_SYSTEM_READY: {
2578 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2579 nai.networkMonitor.systemReady = true;
2580 }
2581 break;
2582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 }
2584 }
2585 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002586
2587 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002588 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002589 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002590 if (isTetheringSupported()) {
2591 return mTethering.tether(iface);
2592 } else {
2593 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2594 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002595 }
2596
2597 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002598 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002599 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002600
2601 if (isTetheringSupported()) {
2602 return mTethering.untether(iface);
2603 } else {
2604 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2605 }
2606 }
2607
2608 // javadoc from interface
2609 public int getLastTetherError(String iface) {
2610 enforceTetherAccessPermission();
2611
2612 if (isTetheringSupported()) {
2613 return mTethering.getLastTetherError(iface);
2614 } else {
2615 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2616 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002617 }
2618
2619 // TODO - proper iface API for selection by property, inspection, etc
2620 public String[] getTetherableUsbRegexs() {
2621 enforceTetherAccessPermission();
2622 if (isTetheringSupported()) {
2623 return mTethering.getTetherableUsbRegexs();
2624 } else {
2625 return new String[0];
2626 }
2627 }
2628
2629 public String[] getTetherableWifiRegexs() {
2630 enforceTetherAccessPermission();
2631 if (isTetheringSupported()) {
2632 return mTethering.getTetherableWifiRegexs();
2633 } else {
2634 return new String[0];
2635 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002636 }
2637
Danica Chang6fdd0c62010-08-11 14:54:43 -07002638 public String[] getTetherableBluetoothRegexs() {
2639 enforceTetherAccessPermission();
2640 if (isTetheringSupported()) {
2641 return mTethering.getTetherableBluetoothRegexs();
2642 } else {
2643 return new String[0];
2644 }
2645 }
2646
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002647 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002648 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002649 if (isTetheringSupported()) {
2650 return mTethering.setUsbTethering(enable);
2651 } else {
2652 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2653 }
2654 }
2655
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002656 // TODO - move iface listing, queries, etc to new module
2657 // javadoc from interface
2658 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002659 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002660 return mTethering.getTetherableIfaces();
2661 }
2662
2663 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002664 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002665 return mTethering.getTetheredIfaces();
2666 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002667
Robert Greenwalt5a735062010-03-02 17:25:02 -08002668 public String[] getTetheringErroredIfaces() {
2669 enforceTetherAccessPermission();
2670 return mTethering.getErroredIfaces();
2671 }
2672
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002673 public String[] getTetheredDhcpRanges() {
2674 enforceConnectivityInternalPermission();
2675 return mTethering.getTetheredDhcpRanges();
2676 }
2677
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002678 // if ro.tether.denied = true we default to no tethering
2679 // gservices could set the secure setting to 1 though to enable it on a build where it
2680 // had previously been turned off.
2681 public boolean isTetheringSupported() {
2682 enforceTetherAccessPermission();
2683 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002684 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002685 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2686 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002687 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2688 mTethering.getTetherableWifiRegexs().length != 0 ||
2689 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2690 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002691 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002692
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002693 // Called when we lose the default network and have no replacement yet.
2694 // This will automatically be cleared after X seconds or a new default network
2695 // becomes CONNECTED, whichever happens first. The timer is started by the
2696 // first caller and not restarted by subsequent callers.
2697 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002698 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002699 synchronized (this) {
2700 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002701 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002702 mNetTransitionWakeLock.acquire();
2703 mNetTransitionWakeLockCausedBy = forWhom;
2704 }
2705 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002706 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002707 mNetTransitionWakeLockTimeout);
2708 return;
2709 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002710
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002711 // 100 percent is full good, 0 is full bad.
2712 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002713 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002714 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002715 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002716 }
2717
Paul Jensenbfd17b72015-04-07 12:43:13 -04002718 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002719 enforceAccessPermission();
2720 enforceInternetPermission();
2721
Paul Jensenbfd17b72015-04-07 12:43:13 -04002722 NetworkAgentInfo nai;
2723 if (network == null) {
2724 nai = getDefaultNetwork();
2725 } else {
2726 nai = getNetworkAgentInfoForNetwork(network);
2727 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002728 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2729 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2730 return;
2731 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002732 // Revalidate if the app report does not match our current validated state.
2733 if (hasConnectivity == nai.lastValidated) return;
2734 final int uid = Binder.getCallingUid();
2735 if (DBG) {
2736 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2737 ") by " + uid);
2738 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002739 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002740 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2741 // which isn't meant to work on uncreated networks.
2742 if (!nai.created) return;
2743
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002744 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002745
2746 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2747 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002748 }
2749
Paul Jensencee9b512015-05-06 07:32:40 -04002750 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002751 // this information is already available as a world read/writable jvm property
2752 // so this API change wouldn't have a benifit. It also breaks the passing
2753 // of proxy info to all the JVMs.
2754 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002755 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002756 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002757 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2758 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002759 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002760 }
2761
Paul Jensencee9b512015-05-06 07:32:40 -04002762 public ProxyInfo getProxyForNetwork(Network network) {
2763 if (network == null) return getDefaultProxy();
2764 final ProxyInfo globalProxy = getGlobalProxy();
2765 if (globalProxy != null) return globalProxy;
2766 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2767 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2768 // caller may not have.
2769 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2770 if (nai == null) return null;
2771 synchronized (nai) {
2772 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2773 if (proxyInfo == null) return null;
2774 return new ProxyInfo(proxyInfo);
2775 }
2776 }
2777
Paul Jensene0bef712014-12-10 15:12:18 -05002778 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2779 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2780 // proxy is null then there is no proxy in place).
2781 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2782 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2783 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2784 proxy = null;
2785 }
2786 return proxy;
2787 }
2788
2789 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2790 // better for determining if a new proxy broadcast is necessary:
2791 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2792 // avoid unnecessary broadcasts.
2793 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2794 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2795 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2796 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2797 // all set.
2798 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2799 a = canonicalizeProxyInfo(a);
2800 b = canonicalizeProxyInfo(b);
2801 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2802 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2803 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2804 }
2805
Jason Monk207900c2014-04-25 15:00:09 -04002806 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002807 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002808
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002809 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002810 if (proxyProperties == mGlobalProxy) return;
2811 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2812 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2813
2814 String host = "";
2815 int port = 0;
2816 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002817 String pacFileUrl = "";
2818 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002819 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002820 if (!proxyProperties.isValid()) {
2821 if (DBG)
2822 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2823 return;
2824 }
Jason Monk207900c2014-04-25 15:00:09 -04002825 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002826 host = mGlobalProxy.getHost();
2827 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002828 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002829 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002830 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002831 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002832 } else {
2833 mGlobalProxy = null;
2834 }
2835 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002836 final long token = Binder.clearCallingIdentity();
2837 try {
2838 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2839 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2840 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2841 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002842 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002843 } finally {
2844 Binder.restoreCallingIdentity(token);
2845 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002846
Jason Monkcf0f97a2014-10-02 15:39:38 -04002847 if (mGlobalProxy == null) {
2848 proxyProperties = mDefaultProxy;
2849 }
2850 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002852 }
2853
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002854 private void loadGlobalProxy() {
2855 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002856 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2857 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2858 String exclList = Settings.Global.getString(res,
2859 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002860 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2861 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002862 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002863 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002864 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002865 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002866 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002867 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002868 if (!proxyProperties.isValid()) {
2869 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2870 return;
2871 }
2872
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002873 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002874 mGlobalProxy = proxyProperties;
2875 }
2876 }
2877 }
2878
Jason Monk207900c2014-04-25 15:00:09 -04002879 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002880 // this information is already available as a world read/writable jvm property
2881 // so this API change wouldn't have a benifit. It also breaks the passing
2882 // of proxy info to all the JVMs.
2883 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002884 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002885 return mGlobalProxy;
2886 }
2887 }
2888
Jason Monk207900c2014-04-25 15:00:09 -04002889 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002890 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002891 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002892 proxy = null;
2893 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002894 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002895 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002896 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002897 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002898 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2899 return;
2900 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002901
2902 // This call could be coming from the PacManager, containing the port of the local
2903 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2904 // global (to get the correct local port), and send a broadcast.
2905 // TODO: Switch PacManager to have its own message to send back rather than
2906 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002907 if ((mGlobalProxy != null) && (proxy != null)
2908 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002909 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2910 mGlobalProxy = proxy;
2911 sendProxyBroadcast(mGlobalProxy);
2912 return;
2913 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002914 mDefaultProxy = proxy;
2915
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002916 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002917 if (!mDefaultProxyDisabled) {
2918 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002919 }
2920 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002921 }
2922
Paul Jensene0bef712014-12-10 15:12:18 -05002923 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2924 // This method gets called when any network changes proxy, but the broadcast only ever contains
2925 // the default proxy (even if it hasn't changed).
2926 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2927 // world where an app might be bound to a non-default network.
2928 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2929 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2930 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2931
2932 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2933 sendProxyBroadcast(getDefaultProxy());
2934 }
2935 }
2936
Robert Greenwalt434203a2010-10-11 16:00:27 -07002937 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002938 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2939 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002940 if (!TextUtils.isEmpty(proxy)) {
2941 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002942 if (data.length == 0) {
2943 return;
2944 }
2945
Robert Greenwalt434203a2010-10-11 16:00:27 -07002946 String proxyHost = data[0];
2947 int proxyPort = 8080;
2948 if (data.length > 1) {
2949 try {
2950 proxyPort = Integer.parseInt(data[1]);
2951 } catch (NumberFormatException e) {
2952 return;
2953 }
2954 }
Jason Monk207900c2014-04-25 15:00:09 -04002955 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002956 setGlobalProxy(p);
2957 }
2958 }
2959
Jason Monk207900c2014-04-25 15:00:09 -04002960 private void sendProxyBroadcast(ProxyInfo proxy) {
2961 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002962 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002963 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002964 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002965 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2966 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002967 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002968 final long ident = Binder.clearCallingIdentity();
2969 try {
2970 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2971 } finally {
2972 Binder.restoreCallingIdentity(ident);
2973 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002974 }
2975
2976 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002977 final private HashMap<Uri, Integer> mUriEventMap;
2978 final private Context mContext;
2979 final private Handler mHandler;
2980
2981 SettingsObserver(Context context, Handler handler) {
2982 super(null);
2983 mUriEventMap = new HashMap<Uri, Integer>();
2984 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002985 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002986 }
2987
Erik Klineda4bfa82015-04-30 12:58:40 +09002988 void observe(Uri uri, int what) {
2989 mUriEventMap.put(uri, what);
2990 final ContentResolver resolver = mContext.getContentResolver();
2991 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002992 }
2993
2994 @Override
2995 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002996 Slog.wtf(TAG, "Should never be reached.");
2997 }
2998
2999 @Override
3000 public void onChange(boolean selfChange, Uri uri) {
3001 final Integer what = mUriEventMap.get(uri);
3002 if (what != null) {
3003 mHandler.obtainMessage(what.intValue()).sendToTarget();
3004 } else {
3005 loge("No matching event to send for URI=" + uri);
3006 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003007 }
3008 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003009
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003010 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003011 Slog.d(TAG, s);
3012 }
3013
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003014 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003015 Slog.e(TAG, s);
3016 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003017
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003018 private static <T> T checkNotNull(T value, String message) {
3019 if (value == null) {
3020 throw new NullPointerException(message);
3021 }
3022 return value;
3023 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003024
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003025 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003026 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003027 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3028 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3029 *
3030 * @param oldPackage Package name of the application which currently controls VPN, which will
3031 * be replaced. If there is no such application, this should should either be
3032 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3033 * @param newPackage Package name of the application which should gain control of VPN, or
3034 * {@code null} to disable.
3035 * @param userId User for whom to prepare the new VPN.
3036 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003037 * @hide
3038 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003039 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003040 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3041 int userId) {
3042 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003043 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003044
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003045 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003046 Vpn vpn = mVpns.get(userId);
3047 if (vpn != null) {
3048 return vpn.prepare(oldPackage, newPackage);
3049 } else {
3050 return false;
3051 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003052 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003053 }
3054
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003055 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003056 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3057 * This method is used by system-privileged apps.
3058 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3059 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3060 *
3061 * @param packageName The package for which authorization state should change.
3062 * @param userId User for whom {@code packageName} is installed.
3063 * @param authorized {@code true} if this app should be able to start a VPN connection without
3064 * explicit user approval, {@code false} if not.
3065 *
Jeff Davidson05542602014-08-11 14:07:27 -07003066 * @hide
3067 */
3068 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003069 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3070 enforceCrossUserPermission(userId);
3071
Jeff Davidson05542602014-08-11 14:07:27 -07003072 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003073 Vpn vpn = mVpns.get(userId);
3074 if (vpn != null) {
3075 vpn.setPackageAuthorization(packageName, authorized);
3076 }
Jeff Davidson05542602014-08-11 14:07:27 -07003077 }
3078 }
3079
3080 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003081 * Configure a TUN interface and return its file descriptor. Parameters
3082 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003083 * and not available in ConnectivityManager. Permissions are checked in
3084 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003085 * @hide
3086 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003087 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003088 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003089 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003090 int user = UserHandle.getUserId(Binder.getCallingUid());
3091 synchronized(mVpns) {
3092 return mVpns.get(user).establish(config);
3093 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003094 }
3095
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003096 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003097 * Start legacy VPN, controlling native daemons as needed. Creates a
3098 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003099 */
3100 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003101 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003102 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003103 final LinkProperties egress = getActiveLinkProperties();
3104 if (egress == null) {
3105 throw new IllegalStateException("Missing active network connection");
3106 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003107 int user = UserHandle.getUserId(Binder.getCallingUid());
3108 synchronized(mVpns) {
3109 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3110 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003111 }
3112
3113 /**
3114 * Return the information of the ongoing legacy VPN. This method is used
3115 * by VpnSettings and not available in ConnectivityManager. Permissions
3116 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003117 */
3118 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003119 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3120 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003121 if (mLockdownEnabled) {
3122 return null;
3123 }
3124
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003125 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003126 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003127 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003128 }
3129
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003130 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003131 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3132 * and not available in ConnectivityManager.
3133 */
3134 @Override
3135 public VpnInfo[] getAllVpnInfo() {
3136 enforceConnectivityInternalPermission();
3137 if (mLockdownEnabled) {
3138 return new VpnInfo[0];
3139 }
3140
3141 synchronized(mVpns) {
3142 List<VpnInfo> infoList = new ArrayList<>();
3143 for (int i = 0; i < mVpns.size(); i++) {
3144 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3145 if (info != null) {
3146 infoList.add(info);
3147 }
3148 }
3149 return infoList.toArray(new VpnInfo[infoList.size()]);
3150 }
3151 }
3152
3153 /**
3154 * @return VPN information for accounting, or null if we can't retrieve all required
3155 * information, e.g primary underlying iface.
3156 */
3157 @Nullable
3158 private VpnInfo createVpnInfo(Vpn vpn) {
3159 VpnInfo info = vpn.getVpnInfo();
3160 if (info == null) {
3161 return null;
3162 }
3163 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3164 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3165 // the underlyingNetworks list.
3166 if (underlyingNetworks == null) {
3167 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3168 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3169 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3170 }
3171 } else if (underlyingNetworks.length > 0) {
3172 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3173 if (linkProperties != null) {
3174 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3175 }
3176 }
3177 return info.primaryUnderlyingIface == null ? null : info;
3178 }
3179
3180 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003181 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3182 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003183 * Permissions are checked in Vpn class.
3184 * @hide
3185 */
3186 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003187 public VpnConfig getVpnConfig(int userId) {
3188 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003189 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003190 Vpn vpn = mVpns.get(userId);
3191 if (vpn != null) {
3192 return vpn.getVpnConfig();
3193 } else {
3194 return null;
3195 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003196 }
3197 }
3198
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003199 @Override
3200 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003201 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3202 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3203 return false;
3204 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003205
3206 // Tear down existing lockdown if profile was removed
3207 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3208 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003209 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003210 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3211 return false;
3212 }
3213
3214 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3215 final VpnProfile profile = VpnProfile.decode(
3216 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003217 if (profile == null) {
3218 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3219 setLockdownTracker(null);
3220 return true;
3221 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003222 int user = UserHandle.getUserId(Binder.getCallingUid());
3223 synchronized(mVpns) {
3224 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3225 profile));
3226 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003227 } else {
3228 setLockdownTracker(null);
3229 }
3230
3231 return true;
3232 }
3233
3234 /**
3235 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3236 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3237 */
3238 private void setLockdownTracker(LockdownVpnTracker tracker) {
3239 // Shutdown any existing tracker
3240 final LockdownVpnTracker existing = mLockdownTracker;
3241 mLockdownTracker = null;
3242 if (existing != null) {
3243 existing.shutdown();
3244 }
3245
3246 try {
3247 if (tracker != null) {
3248 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003249 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003250 mLockdownTracker = tracker;
3251 mLockdownTracker.init();
3252 } else {
3253 mNetd.setFirewallEnabled(false);
3254 }
3255 } catch (RemoteException e) {
3256 // ignored; NMS lives inside system_server
3257 }
3258 }
3259
3260 private void throwIfLockdownEnabled() {
3261 if (mLockdownEnabled) {
3262 throw new IllegalStateException("Unavailable in lockdown mode");
3263 }
3264 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003265
Robin Lee244ce8e2016-01-05 18:03:46 +00003266 /**
3267 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3268 *
3269 * @return {@code false} in case of errors; {@code true} otherwise.
3270 */
3271 private boolean updateAlwaysOnVpn(int user) {
3272 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3273 if (lockdownPackage == null) {
3274 return true;
3275 }
3276
3277 // Create an intent to start the VPN service declared in the app's manifest.
3278 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3279 serviceIntent.setPackage(lockdownPackage);
3280
3281 try {
3282 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3283 } catch (RuntimeException e) {
3284 return false;
3285 }
3286 }
3287
3288 @Override
3289 public boolean setAlwaysOnVpnPackage(int userId, String packageName) {
3290 enforceConnectivityInternalPermission();
3291 enforceCrossUserPermission(userId);
3292
3293 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3294 if (LockdownVpnTracker.isEnabled()) {
3295 return false;
3296 }
3297
3298 // If the current VPN package is the same as the new one, this is a no-op
3299 final String oldPackage = getAlwaysOnVpnPackage(userId);
3300 if (TextUtils.equals(oldPackage, packageName)) {
3301 return true;
3302 }
3303
3304 synchronized (mVpns) {
3305 Vpn vpn = mVpns.get(userId);
3306 if (vpn == null) {
3307 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3308 return false;
3309 }
3310 if (!vpn.setAlwaysOnPackage(packageName)) {
3311 return false;
3312 }
3313 if (!updateAlwaysOnVpn(userId)) {
3314 vpn.setAlwaysOnPackage(null);
3315 return false;
3316 }
3317 }
3318 return true;
3319 }
3320
3321 @Override
3322 public String getAlwaysOnVpnPackage(int userId) {
3323 enforceConnectivityInternalPermission();
3324 enforceCrossUserPermission(userId);
3325
3326 synchronized (mVpns) {
3327 Vpn vpn = mVpns.get(userId);
3328 if (vpn == null) {
3329 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3330 return null;
3331 }
3332 return vpn.getAlwaysOnPackage();
3333 }
3334 }
3335
Wink Savilleab9321d2013-06-29 21:10:57 -07003336 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003337 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003338 // TODO: Remove? Any reason to trigger a provisioning check?
3339 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003340 }
3341
3342 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003343 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003344
Paul Jensen89e0f092014-09-15 15:59:36 -04003345 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003346 if (DBG) {
3347 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003348 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003349 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003350 Intent intent = new Intent(action);
3351 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003352 // Concatenate the range of types onto the range of NetIDs.
3353 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003354 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003355 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003356 }
3357
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003358 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003359 * Show or hide network provisioning notifications.
3360 *
3361 * We use notifications for two purposes: to notify that a network requires sign in
3362 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3363 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3364 * particular network we can display the notification type that was most recently requested.
3365 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3366 * might first display NO_INTERNET, and then when the captive portal check completes, display
3367 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003368 *
3369 * @param id an identifier that uniquely identifies this notification. This must match
3370 * between show and hide calls. We use the NetID value but for legacy callers
3371 * we concatenate the range of types with the range of NetIDs.
3372 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003373 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003374 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3375 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003376 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003377 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3378 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003379 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003380 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003381
3382 Resources r = Resources.getSystem();
3383 NotificationManager notificationManager = (NotificationManager) mContext
3384 .getSystemService(Context.NOTIFICATION_SERVICE);
3385
3386 if (visible) {
3387 CharSequence title;
3388 CharSequence details;
3389 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003390 if (notifyType == NotificationType.NO_INTERNET &&
3391 networkType == ConnectivityManager.TYPE_WIFI) {
3392 title = r.getString(R.string.wifi_no_internet, 0);
3393 details = r.getString(R.string.wifi_no_internet_detailed);
3394 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3395 } else if (notifyType == NotificationType.SIGN_IN) {
3396 switch (networkType) {
3397 case ConnectivityManager.TYPE_WIFI:
3398 title = r.getString(R.string.wifi_available_sign_in, 0);
3399 details = r.getString(R.string.network_available_sign_in_detailed,
3400 extraInfo);
3401 icon = R.drawable.stat_notify_wifi_in_range;
3402 break;
3403 case ConnectivityManager.TYPE_MOBILE:
3404 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3405 title = r.getString(R.string.network_available_sign_in, 0);
3406 // TODO: Change this to pull from NetworkInfo once a printable
3407 // name has been added to it
3408 details = mTelephonyManager.getNetworkOperatorName();
3409 icon = R.drawable.stat_notify_rssi_in_range;
3410 break;
3411 default:
3412 title = r.getString(R.string.network_available_sign_in, 0);
3413 details = r.getString(R.string.network_available_sign_in_detailed,
3414 extraInfo);
3415 icon = R.drawable.stat_notify_rssi_in_range;
3416 break;
3417 }
3418 } else {
3419 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3420 + getNetworkTypeName(networkType));
3421 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003422 }
3423
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003424 Notification notification = new Notification.Builder(mContext)
3425 .setWhen(0)
3426 .setSmallIcon(icon)
3427 .setAutoCancel(true)
3428 .setTicker(title)
3429 .setColor(mContext.getColor(
3430 com.android.internal.R.color.system_notification_accent_color))
3431 .setContentTitle(title)
3432 .setContentText(details)
3433 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003434 .setLocalOnly(true)
3435 .setPriority(highPriority ?
3436 Notification.PRIORITY_HIGH :
3437 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003438 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003439 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003440 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003441
Wink Saville948282b2013-08-29 08:55:16 -07003442 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003443 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003444 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003445 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003446 npe.printStackTrace();
3447 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003448 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003449 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003450 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003451 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003452 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003453 npe.printStackTrace();
3454 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003455 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003456 }
3457
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003458 /** Location to an updatable file listing carrier provisioning urls.
3459 * An example:
3460 *
3461 * <?xml version="1.0" encoding="utf-8"?>
3462 * <provisioningUrls>
3463 * <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 -07003464 * </provisioningUrls>
3465 */
3466 private static final String PROVISIONING_URL_PATH =
3467 "/data/misc/radio/provisioning_urls.xml";
3468 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003469
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003470 /** XML tag for root element. */
3471 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3472 /** XML tag for individual url */
3473 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003474 /** XML attribute for mcc */
3475 private static final String ATTR_MCC = "mcc";
3476 /** XML attribute for mnc */
3477 private static final String ATTR_MNC = "mnc";
3478
Paul Jensen434dde82015-06-11 09:43:30 -04003479 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003480 FileReader fileReader = null;
3481 XmlPullParser parser = null;
3482 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003483
3484 try {
3485 fileReader = new FileReader(mProvisioningUrlFile);
3486 parser = Xml.newPullParser();
3487 parser.setInput(fileReader);
3488 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3489
3490 while (true) {
3491 XmlUtils.nextElement(parser);
3492
3493 String element = parser.getName();
3494 if (element == null) break;
3495
Paul Jensen434dde82015-06-11 09:43:30 -04003496 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003497 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3498 try {
3499 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3500 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3501 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3502 parser.next();
3503 if (parser.getEventType() == XmlPullParser.TEXT) {
3504 return parser.getText();
3505 }
3506 }
3507 }
3508 } catch (NumberFormatException e) {
3509 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3510 }
3511 }
3512 }
3513 return null;
3514 } catch (FileNotFoundException e) {
3515 loge("Carrier Provisioning Urls file not found");
3516 } catch (XmlPullParserException e) {
3517 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3518 } catch (IOException e) {
3519 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3520 } finally {
3521 if (fileReader != null) {
3522 try {
3523 fileReader.close();
3524 } catch (IOException e) {}
3525 }
3526 }
3527 return null;
3528 }
3529
Wink Saville42d4f082013-07-20 20:31:59 -07003530 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003531 public String getMobileProvisioningUrl() {
3532 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003533 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003534 if (TextUtils.isEmpty(url)) {
3535 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003536 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003537 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003538 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003539 }
Wink Saville8cf35602013-07-10 23:00:07 -07003540 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003541 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003542 String phoneNumber = mTelephonyManager.getLine1Number();
3543 if (TextUtils.isEmpty(phoneNumber)) {
3544 phoneNumber = "0000000000";
3545 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003546 url = String.format(url,
3547 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3548 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003549 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003550 }
3551
Wink Savilleab9321d2013-06-29 21:10:57 -07003552 return url;
3553 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003554
Wink Saville948282b2013-08-29 08:55:16 -07003555 @Override
3556 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003557 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003558 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003559 final long ident = Binder.clearCallingIdentity();
3560 try {
3561 setProvNotificationVisible(visible, networkType, action);
3562 } finally {
3563 Binder.restoreCallingIdentity(ident);
3564 }
Wink Saville948282b2013-08-29 08:55:16 -07003565 }
Wink Saville7788c612013-08-29 14:57:08 -07003566
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003567 @Override
3568 public void setAirplaneMode(boolean enable) {
3569 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003570 final long ident = Binder.clearCallingIdentity();
3571 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003572 final ContentResolver cr = mContext.getContentResolver();
3573 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3574 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3575 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003576 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003577 } finally {
3578 Binder.restoreCallingIdentity(ident);
3579 }
3580 }
3581
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003582 private void onUserStart(int userId) {
3583 synchronized(mVpns) {
3584 Vpn userVpn = mVpns.get(userId);
3585 if (userVpn != null) {
3586 loge("Starting user already has a VPN");
3587 return;
3588 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003589 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003590 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003591 }
3592 }
3593
3594 private void onUserStop(int userId) {
3595 synchronized(mVpns) {
3596 Vpn userVpn = mVpns.get(userId);
3597 if (userVpn == null) {
3598 loge("Stopping user has no VPN");
3599 return;
3600 }
3601 mVpns.delete(userId);
3602 }
3603 }
3604
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003605 private void onUserAdded(int userId) {
3606 synchronized(mVpns) {
3607 final int vpnsSize = mVpns.size();
3608 for (int i = 0; i < vpnsSize; i++) {
3609 Vpn vpn = mVpns.valueAt(i);
3610 vpn.onUserAdded(userId);
3611 }
3612 }
3613 }
3614
3615 private void onUserRemoved(int userId) {
3616 synchronized(mVpns) {
3617 final int vpnsSize = mVpns.size();
3618 for (int i = 0; i < vpnsSize; i++) {
3619 Vpn vpn = mVpns.valueAt(i);
3620 vpn.onUserRemoved(userId);
3621 }
3622 }
3623 }
3624
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003625 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3626 @Override
3627 public void onReceive(Context context, Intent intent) {
3628 final String action = intent.getAction();
3629 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3630 if (userId == UserHandle.USER_NULL) return;
3631
3632 if (Intent.ACTION_USER_STARTING.equals(action)) {
3633 onUserStart(userId);
3634 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3635 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003636 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3637 onUserAdded(userId);
3638 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3639 onUserRemoved(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003640 }
3641 }
3642 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003643
Robert Greenwalta67be032014-05-16 15:49:14 -07003644 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3645 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003646 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3647 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003648
Robert Greenwalta67be032014-05-16 15:49:14 -07003649 private static class NetworkFactoryInfo {
3650 public final String name;
3651 public final Messenger messenger;
3652 public final AsyncChannel asyncChannel;
3653
3654 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3655 this.name = name;
3656 this.messenger = messenger;
3657 this.asyncChannel = asyncChannel;
3658 }
3659 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003660
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003661 /**
3662 * Tracks info about the requester.
3663 * Also used to notice when the calling process dies so we can self-expire
3664 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003665 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3666 static final boolean REQUEST = true;
3667 static final boolean LISTEN = false;
3668
3669 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003670 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003671 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003672 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003673 final int mPid;
3674 final int mUid;
3675 final Messenger messenger;
3676 final boolean isRequest;
3677
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003678 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3679 request = r;
3680 mPendingIntent = pi;
3681 messenger = null;
3682 mBinder = null;
3683 mPid = getCallingPid();
3684 mUid = getCallingUid();
3685 this.isRequest = isRequest;
3686 }
3687
Robert Greenwalt9258c642014-03-26 16:47:06 -07003688 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3689 super();
3690 messenger = m;
3691 request = r;
3692 mBinder = binder;
3693 mPid = getCallingPid();
3694 mUid = getCallingUid();
3695 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003696 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003697
3698 try {
3699 mBinder.linkToDeath(this, 0);
3700 } catch (RemoteException e) {
3701 binderDied();
3702 }
3703 }
3704
3705 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003706 if (mBinder != null) {
3707 mBinder.unlinkToDeath(this, 0);
3708 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003709 }
3710
3711 public void binderDied() {
3712 log("ConnectivityService NetworkRequestInfo binderDied(" +
3713 request + ", " + mBinder + ")");
3714 releaseNetworkRequest(request);
3715 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003716
3717 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003718 return (isRequest ? "Request" : "Listen") +
3719 " from uid/pid:" + mUid + "/" + mPid +
3720 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003721 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003722 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003723 }
3724
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003725 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3726 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3727 if (badCapability != null) {
3728 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003729 }
3730 }
3731
Erik Kline9d598e12015-07-13 16:37:51 +09003732 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003733 final SortedSet<Integer> thresholds = new TreeSet();
3734 synchronized (nai) {
3735 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3736 if (nri.request.networkCapabilities.hasSignalStrength() &&
3737 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3738 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3739 }
3740 }
3741 }
Erik Kline9d598e12015-07-13 16:37:51 +09003742 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003743 }
3744
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003745 private void updateSignalStrengthThresholds(
3746 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3747 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003748 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003749 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3750
3751 // TODO: Switch to VDBG.
3752 if (DBG) {
3753 String detail;
3754 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3755 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3756 } else {
3757 detail = reason;
3758 }
3759 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3760 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3761 }
3762
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003763 nai.asyncChannel.sendMessage(
3764 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003765 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003766 }
3767
Robert Greenwalt9258c642014-03-26 16:47:06 -07003768 @Override
3769 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003770 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003771 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003772 enforceNetworkRequestPermissions(networkCapabilities);
3773 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003774 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003775
Robert Greenwalt6078b502014-06-11 16:05:07 -07003776 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003777 throw new IllegalArgumentException("Bad timeout specified");
3778 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003779
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003780 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3781 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003782 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3783 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003784 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003785
3786 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003787 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003788 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003789 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003790 }
3791 return networkRequest;
3792 }
3793
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003794 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003795 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003796 enforceConnectivityInternalPermission();
3797 } else {
3798 enforceChangePermission();
3799 }
3800 }
3801
fenglub15e72b2015-03-20 11:29:56 -07003802 @Override
fengludb571472015-04-21 17:12:05 -07003803 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003804 enforceAccessPermission();
3805 NetworkAgentInfo nai = null;
3806 if (network == null) {
3807 return false;
3808 }
3809 synchronized (mNetworkForNetId) {
3810 nai = mNetworkForNetId.get(network.netId);
3811 }
3812 if (nai != null) {
3813 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3814 return true;
3815 }
3816 return false;
3817 }
3818
3819
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003820 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3821 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003822 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003823 final int uidRules;
3824 final int uid = Binder.getCallingUid();
3825 synchronized(mRulesLock) {
3826 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3827 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003828 if (uidRules != RULE_ALLOW_ALL) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003829 // we could silently fail or we can filter the available nets to only give
3830 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003831 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003832 }
3833 }
3834 }
3835
Robert Greenwalt9258c642014-03-26 16:47:06 -07003836 @Override
3837 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3838 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003839 checkNotNull(operation, "PendingIntent cannot be null.");
3840 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3841 enforceNetworkRequestPermissions(networkCapabilities);
3842 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003843 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003844
3845 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3846 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003847 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3848 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003849 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003850 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3851 nri));
3852 return networkRequest;
3853 }
3854
Jeremy Joslin79294842014-12-03 17:15:28 -08003855 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3856 mHandler.sendMessageDelayed(
3857 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3858 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3859 }
3860
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003861 @Override
3862 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003863 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003864 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3865 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003866 }
3867
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003868 // In order to implement the compatibility measure for pre-M apps that call
3869 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3870 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3871 // This ensures it has permission to do so.
3872 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3873 if (nc == null) {
3874 return false;
3875 }
3876 int[] transportTypes = nc.getTransportTypes();
3877 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3878 return false;
3879 }
3880 try {
3881 mContext.enforceCallingOrSelfPermission(
3882 android.Manifest.permission.ACCESS_WIFI_STATE,
3883 "ConnectivityService");
3884 } catch (SecurityException e) {
3885 return false;
3886 }
3887 return true;
3888 }
3889
Robert Greenwalt9258c642014-03-26 16:47:06 -07003890 @Override
3891 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3892 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003893 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3894 enforceAccessPermission();
3895 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003896
Erik Kline7523eb32015-07-09 18:24:03 +09003897 NetworkRequest networkRequest = new NetworkRequest(
3898 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003899 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3900 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003901 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003902
3903 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3904 return networkRequest;
3905 }
3906
3907 @Override
3908 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3909 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003910 checkNotNull(operation, "PendingIntent cannot be null.");
3911 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3912 enforceAccessPermission();
3913 }
3914
Erik Kline7523eb32015-07-09 18:24:03 +09003915 NetworkRequest networkRequest = new NetworkRequest(
3916 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003917 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3918 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003919 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003920
3921 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003922 }
3923
3924 @Override
3925 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003926 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3927 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003928 }
3929
3930 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003931 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003932 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003933 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3934 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003935 }
3936
Robert Greenwalta67be032014-05-16 15:49:14 -07003937 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003938 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003939 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3940 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3941 }
3942
3943 @Override
3944 public void unregisterNetworkFactory(Messenger messenger) {
3945 enforceConnectivityInternalPermission();
3946 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3947 }
3948
3949 private void handleUnregisterNetworkFactory(Messenger messenger) {
3950 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3951 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003952 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003953 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003954 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003955 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003956 }
3957
Robert Greenwalt7b816022014-04-18 15:25:25 -07003958 /**
3959 * NetworkAgentInfo supporting a request by requestId.
3960 * These have already been vetted (their Capabilities satisfy the request)
3961 * and the are the highest scored network available.
3962 * the are keyed off the Requests requestId.
3963 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003964 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003965 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3966 new SparseArray<NetworkAgentInfo>();
3967
Paul Jensen31a94f42015-02-13 14:18:39 -05003968 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3969 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003970 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3971 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003972 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3973 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3974 // there may not be a strict 1:1 correlation between the two.
3975 @GuardedBy("mNetworkForNetId")
3976 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003977
Robert Greenwalt7b816022014-04-18 15:25:25 -07003978 // NetworkAgentInfo keyed off its connecting messenger
3979 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003980 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003981 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3982 new HashMap<Messenger, NetworkAgentInfo>();
3983
Paul Jensen2c311d62014-11-17 12:34:51 -05003984 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003985 private final NetworkRequest mDefaultRequest;
3986
Erik Klineda4bfa82015-04-30 12:58:40 +09003987 // Request used to optionally keep mobile data active even when higher
3988 // priority networks like Wi-Fi are active.
3989 private final NetworkRequest mDefaultMobileDataRequest;
3990
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003991 private NetworkAgentInfo getDefaultNetwork() {
3992 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3993 }
3994
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003995 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003996 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003997 }
3998
Paul Jensen31a94f42015-02-13 14:18:39 -05003999 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004000 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004001 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004002 enforceConnectivityInternalPermission();
4003
Paul Jensen2c311d62014-11-17 12:34:51 -05004004 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4005 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004006 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004007 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4008 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004009 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004010 synchronized (this) {
4011 nai.networkMonitor.systemReady = mSystemReady;
4012 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004013 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004014 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004015 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004016 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004017 }
4018
4019 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4020 if (VDBG) log("Got NetworkAgent Messenger");
4021 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004022 synchronized (mNetworkForNetId) {
4023 mNetworkForNetId.put(na.network.netId, na);
4024 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004025 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4026 NetworkInfo networkInfo = na.networkInfo;
4027 na.networkInfo = null;
4028 updateNetworkInfo(na, networkInfo);
4029 }
4030
4031 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4032 LinkProperties newLp = networkAgent.linkProperties;
4033 int netId = networkAgent.network.netId;
4034
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004035 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4036 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004037 if (networkAgent.clatd != null) {
4038 networkAgent.clatd.fixupLinkProperties(oldLp);
4039 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004040
Paul Jensen992f2522014-04-28 10:33:11 -04004041 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004042 updateMtu(newLp, oldLp);
4043 // TODO - figure out what to do for clat
4044// for (LinkProperties lp : newLp.getStackedLinks()) {
4045// updateMtu(lp, null);
4046// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004047 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004048
Lorenzo Colitti93155b32015-05-14 22:12:36 +09004049 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
4050 // In L, we used it only when the network had Internet access but provided no DNS servers.
4051 // For now, just disable it, and if disabling it doesn't break things, remove it.
4052 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
4053 // NET_CAPABILITY_INTERNET);
4054 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004055 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004056 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
4057
Paul Jensen3b759822014-05-13 11:44:01 -04004058 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004059 if (isDefaultNetwork(networkAgent)) {
4060 handleApplyDefaultProxy(newLp.getHttpProxy());
4061 } else {
4062 updateProxy(newLp, oldLp, networkAgent);
4063 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004064 // TODO - move this check to cover the whole function
4065 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08004066 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004067 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4068 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004069
4070 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004071 }
4072
Lorenzo Colitti95439462014-10-09 13:44:48 +09004073 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4074 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4075 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004076
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004077 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004078 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4079 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004080 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004081 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004082 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004083 }
Paul Jensen992f2522014-04-28 10:33:11 -04004084
4085 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4086 CompareResult<String> interfaceDiff = new CompareResult<String>();
4087 if (oldLp != null) {
4088 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4089 } else if (newLp != null) {
4090 interfaceDiff.added = newLp.getAllInterfaceNames();
4091 }
4092 for (String iface : interfaceDiff.added) {
4093 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004094 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004095 mNetd.addInterfaceToNetwork(iface, netId);
4096 } catch (Exception e) {
4097 loge("Exception adding interface: " + e);
4098 }
4099 }
4100 for (String iface : interfaceDiff.removed) {
4101 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004102 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004103 mNetd.removeInterfaceFromNetwork(iface, netId);
4104 } catch (Exception e) {
4105 loge("Exception removing interface: " + e);
4106 }
4107 }
4108 }
4109
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004110 /**
4111 * Have netd update routes from oldLp to newLp.
4112 * @return true if routes changed between oldLp and newLp
4113 */
4114 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004115 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4116 if (oldLp != null) {
4117 routeDiff = oldLp.compareAllRoutes(newLp);
4118 } else if (newLp != null) {
4119 routeDiff.added = newLp.getAllRoutes();
4120 }
4121
4122 // add routes before removing old in case it helps with continuous connectivity
4123
4124 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4125 for (RouteInfo route : routeDiff.added) {
4126 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004127 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004128 try {
4129 mNetd.addRoute(netId, route);
4130 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004131 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4132 loge("Exception in addRoute for non-gateway: " + e);
4133 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004134 }
4135 }
4136 for (RouteInfo route : routeDiff.added) {
4137 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004138 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004139 try {
4140 mNetd.addRoute(netId, route);
4141 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004142 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4143 loge("Exception in addRoute for gateway: " + e);
4144 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004145 }
4146 }
4147
4148 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004149 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004150 try {
4151 mNetd.removeRoute(netId, route);
4152 } catch (Exception e) {
4153 loge("Exception in removeRoute: " + e);
4154 }
4155 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004156 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004157 }
Erik Kline41368502015-06-17 13:19:54 +09004158
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004159 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4160 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004161 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004162 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004163 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004164 dnses = new ArrayList();
4165 dnses.add(mDefaultDns);
4166 if (DBG) {
4167 loge("no dns provided for netId " + netId + ", so using defaults");
4168 }
4169 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004170 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004171 try {
4172 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4173 newLp.getDomains());
4174 } catch (Exception e) {
4175 loge("Exception in setDnsServersForNetwork: " + e);
4176 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004177 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004178 if (defaultNai != null && defaultNai.network.netId == netId) {
4179 setDefaultDnsSystemProperties(dnses);
4180 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004181 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004182 } else if (flush) {
4183 try {
4184 mNetd.flushNetworkDnsCache(netId);
4185 } catch (Exception e) {
4186 loge("Exception in flushNetworkDnsCache: " + e);
4187 }
4188 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004189 }
4190 }
4191
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004192 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4193 int last = 0;
4194 for (InetAddress dns : dnses) {
4195 ++last;
4196 String key = "net.dns" + last;
4197 String value = dns.getHostAddress();
4198 SystemProperties.set(key, value);
4199 }
4200 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4201 String key = "net.dns" + i;
4202 SystemProperties.set(key, "");
4203 }
4204 mNumDnsEntries = last;
4205 }
4206
Paul Jensen3d194ea2015-06-16 14:27:36 -04004207 /**
4208 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4209 * augmented with any stateful capabilities implied from {@code networkAgent}
4210 * (e.g., validated status and captive portal status).
4211 *
Paul Jensene0988542015-06-25 15:30:08 -04004212 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004213 * @param networkCapabilities the new network capabilities.
4214 */
Paul Jensene0988542015-06-25 15:30:08 -04004215 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004216 // Don't modify caller's NetworkCapabilities.
4217 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004218 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004219 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4220 } else {
4221 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4222 }
Paul Jensene0988542015-06-25 15:30:08 -04004223 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004224 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4225 } else {
4226 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4227 }
Paul Jensene0988542015-06-25 15:30:08 -04004228 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4229 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004230 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4231 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4232 try {
4233 mNetd.setNetworkPermission(nai.network.netId,
4234 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4235 null : NetworkManagementService.PERMISSION_SYSTEM);
4236 } catch (RemoteException e) {
4237 loge("Exception in setNetworkPermission: " + e);
4238 }
4239 }
Paul Jensene0988542015-06-25 15:30:08 -04004240 synchronized (nai) {
4241 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004242 }
Paul Jensene0988542015-06-25 15:30:08 -04004243 rematchAllNetworksAndRequests(nai, oldScore);
4244 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004245 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004246 }
4247
Paul Jensenc8b9a742014-09-30 15:37:41 -04004248 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4249 for (int i = 0; i < nai.networkRequests.size(); i++) {
4250 NetworkRequest nr = nai.networkRequests.valueAt(i);
4251 // Don't send listening requests to factories. b/17393458
4252 if (!isRequest(nr)) continue;
4253 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4254 }
4255 }
4256
Robert Greenwalt7b816022014-04-18 15:25:25 -07004257 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4258 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004259 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004260 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4261 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004262 }
4263 }
4264
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004265 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4266 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004267 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004268 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004269 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4270 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004271 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004272 sendIntent(nri.mPendingIntent, intent);
4273 }
4274 // else not handled
4275 }
4276
4277 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4278 mPendingIntentWakeLock.acquire();
4279 try {
4280 if (DBG) log("Sending " + pendingIntent);
4281 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4282 } catch (PendingIntent.CanceledException e) {
4283 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4284 mPendingIntentWakeLock.release();
4285 releasePendingNetworkRequest(pendingIntent);
4286 }
4287 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4288 }
4289
4290 @Override
4291 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4292 String resultData, Bundle resultExtras) {
4293 if (DBG) log("Finished sending " + pendingIntent);
4294 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004295 // Release with a delay so the receiving client has an opportunity to put in its
4296 // own request.
4297 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004298 }
4299
Robert Greenwalt9258c642014-03-26 16:47:06 -07004300 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004301 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004302 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004303 Bundle bundle = new Bundle();
4304 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4305 new NetworkRequest(nri.request));
4306 Message msg = Message.obtain();
4307 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4308 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4309 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4310 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004311 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004312 case ConnectivityManager.CALLBACK_LOSING: {
4313 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4314 break;
4315 }
4316 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4317 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4318 new NetworkCapabilities(networkAgent.networkCapabilities));
4319 break;
4320 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004321 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004322 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4323 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004324 break;
4325 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004326 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004327 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004328 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004329 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004330 if (VDBG) {
4331 log("sending notification " + notifyTypeToName(notificationType) +
4332 " for " + nri.request);
4333 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004334 nri.messenger.send(msg);
4335 } catch (RemoteException e) {
4336 // may occur naturally in the race of binder death.
4337 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4338 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339 }
4340
Paul Jensenc8b9a742014-09-30 15:37:41 -04004341 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4342 for (int i = 0; i < nai.networkRequests.size(); i++) {
4343 NetworkRequest nr = nai.networkRequests.valueAt(i);
4344 // Ignore listening requests.
4345 if (!isRequest(nr)) continue;
4346 loge("Dead network still had at least " + nr);
4347 break;
4348 }
4349 nai.asyncChannel.disconnect();
4350 }
4351
Robert Greenwalt7b816022014-04-18 15:25:25 -07004352 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4353 if (oldNetwork == null) {
4354 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4355 return;
4356 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004357 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4358 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004359 }
4360
Paul Jensen27b02b72014-07-14 12:03:33 -04004361 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004362 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004363 setupDataActivityTracking(newNetwork);
4364 try {
4365 mNetd.setDefaultNetId(newNetwork.network.netId);
4366 } catch (Exception e) {
4367 loge("Exception setting default network :" + e);
4368 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004369 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004370 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004371 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004372 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004373 }
4374
Paul Jensen2161a8e2014-09-11 11:00:39 -04004375 // Handles a network appearing or improving its score.
4376 //
4377 // - Evaluates all current NetworkRequests that can be
4378 // satisfied by newNetwork, and reassigns to newNetwork
4379 // any such requests for which newNetwork is the best.
4380 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004381 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004382 // needed. A network is needed if it is the best network for
4383 // one or more NetworkRequests, or if it is a VPN.
4384 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004385 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004386 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004387 //
4388 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4389 // networks that have no chance (i.e. even if validated)
4390 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004391 //
4392 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4393 // it does not remove NetworkRequests that other Networks could better satisfy.
4394 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4395 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4396 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004397 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004398 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004399 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4400 // performed to tear down unvalidated networks that have no chance (i.e. even if
4401 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004402 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004403 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004404 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004405 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004406 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004407 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004408 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004409 // Find and migrate to this Network any NetworkRequests for
4410 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004411 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004412 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004413 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004414 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004415 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4416 final boolean satisfies = newNetwork.satisfies(nri.request);
4417 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004418 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004419 log("Network " + newNetwork.name() + " was already satisfying" +
4420 " request " + nri.request.requestId + ". No change.");
4421 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004422 keep = true;
4423 continue;
4424 }
4425
4426 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004427 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004428 if (satisfies) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004429 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004430 // This is not a request, it's a callback listener.
4431 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004432 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004433 continue;
4434 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004435
Robert Greenwalt7b816022014-04-18 15:25:25 -07004436 // next check if it's better than any current network we're using for
4437 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004438 if (VDBG) {
4439 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004440 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4441 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004442 }
4443 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004444 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004445 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004446 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004447 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004448 currentNetwork.networkRequests.remove(nri.request.requestId);
4449 currentNetwork.networkLingered.add(nri.request);
4450 affectedNetworks.add(currentNetwork);
4451 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004452 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004453 }
Paul Jensen573a0352015-01-08 10:49:34 -05004454 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004455 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004456 if (!newNetwork.addRequest(nri.request)) {
4457 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4458 }
4459 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004460 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004461 // Tell NetworkFactories about the new score, so they can stop
4462 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004463 // TODO - this could get expensive if we have alot of requests for this
4464 // network. Think about if there is a way to reduce this. Push
4465 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004466 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004467 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004468 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004469 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004470 }
4471 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004472 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4473 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4474 // mark it as no longer satisfying "nri". Because networks are processed by
4475 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4476 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4477 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4478 // This means this code doesn't have to handle the case where "currentNetwork" no
4479 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4480 if (DBG) {
4481 log("Network " + newNetwork.name() + " stopped satisfying" +
4482 " request " + nri.request.requestId);
4483 }
4484 newNetwork.networkRequests.remove(nri.request.requestId);
4485 if (currentNetwork == newNetwork) {
4486 mNetworkForRequestId.remove(nri.request.requestId);
4487 sendUpdatedScoreToFactories(nri.request, 0);
4488 } else {
4489 if (nri.isRequest == true) {
4490 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4491 newNetwork.name() +
4492 " without updating mNetworkForRequestId or factories!");
4493 }
4494 }
4495 // TODO: technically, sending CALLBACK_LOST here is
4496 // incorrect if nri is a request (not a listen) and there
4497 // is a replacement network currently connected that can
4498 // satisfy it. However, the only capability that can both
4499 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4500 // so this code is only incorrect for a network that loses
4501 // the TRUSTED capability, which is a rare case.
4502 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004503 }
4504 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004505 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004506 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004507 if (nai.lingering) {
4508 // Already lingered. Nothing to do. This can only happen if "nai" is in
4509 // "affectedNetworks" twice. The reasoning being that to get added to
4510 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4511 // (i.e. not lingered) so it could have only been lingered by this loop.
4512 // unneeded(nai) will be false and we'll call unlinger() below which would
4513 // be bad, so handle it here.
4514 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004515 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004516 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004517 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004518 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004519 }
4520 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004521 if (isNewDefault) {
4522 // Notify system services that this network is up.
4523 makeDefault(newNetwork);
4524 synchronized (ConnectivityService.this) {
4525 // have a new default network, release the transition wakelock in
4526 // a second if it's held. The second pause is to allow apps
4527 // to reconnect over the new network
4528 if (mNetTransitionWakeLock.isHeld()) {
4529 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4530 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4531 mNetTransitionWakeLockSerialNumber, 0),
4532 1000);
4533 }
4534 }
4535 }
4536
4537 // do this after the default net is switched, but
4538 // before LegacyTypeTracker sends legacy broadcasts
4539 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4540
4541 if (isNewDefault) {
4542 // Maintain the illusion: since the legacy API only
4543 // understands one network at a time, we must pretend
4544 // that the current default network disconnected before
4545 // the new one connected.
4546 if (oldDefaultNetwork != null) {
4547 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4548 oldDefaultNetwork, true);
4549 }
4550 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4551 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4552 notifyLockdownVpn(newNetwork);
4553 }
4554
Robert Greenwalt7b816022014-04-18 15:25:25 -07004555 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004556 // Notify battery stats service about this network, both the normal
4557 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004558 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004559 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004560 final IBatteryStats bs = BatteryStatsService.getService();
4561 final int type = newNetwork.networkInfo.getType();
4562
4563 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4564 bs.noteNetworkInterfaceType(baseIface, type);
4565 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4566 final String stackedIface = stacked.getInterfaceName();
4567 bs.noteNetworkInterfaceType(stackedIface, type);
4568 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4569 }
4570 } catch (RemoteException ignored) {
4571 }
4572
Robert Greenwalt152ed372014-12-17 17:19:53 -08004573 // This has to happen after the notifyNetworkCallbacks as that tickles each
4574 // ConnectivityManager instance so that legacy requests correctly bind dns
4575 // requests to this network. The legacy users are listening for this bcast
4576 // and will generally do a dns request so they can ensureRouteToHost and if
4577 // they do that before the callbacks happen they'll use the default network.
4578 //
4579 // TODO: Is there still a race here? We send the broadcast
4580 // after sending the callback, but if the app can receive the
4581 // broadcast before the callback, it might still break.
4582 //
4583 // This *does* introduce a race where if the user uses the new api
4584 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4585 // they may get old info. Reverse this after the old startUsing api is removed.
4586 // This is on top of the multiple intent sequencing referenced in the todo above.
4587 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4588 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4589 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4590 // legacy type tracker filters out repeat adds
4591 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4592 }
4593 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004594
4595 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4596 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4597 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4598 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4599 if (newNetwork.isVPN()) {
4600 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4601 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004602 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004603 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4604 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004605 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004606 if (DBG) log("Reaping " + nai.name());
4607 teardownUnneededNetwork(nai);
4608 }
4609 }
4610 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004611 }
4612
Paul Jensen1c7ba022015-06-16 14:27:36 -04004613 /**
4614 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4615 * being disconnected.
4616 * @param changed If only one Network's score or capabilities have been modified since the last
4617 * time this function was called, pass this Network in this argument, otherwise pass
4618 * null.
4619 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4620 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4621 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4622 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4623 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004624 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004625 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004626 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4627 // to avoid the slowness. It is not simply enough to process just "changed", for
4628 // example in the case where "changed"'s score decreases and another network should begin
4629 // satifying a NetworkRequest that "changed" currently satisfies.
4630
4631 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4632 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4633 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004634 if (changed != null && oldScore < changed.getCurrentScore()) {
4635 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004636 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004637 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4638 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4639 // Rematch higher scoring networks first to prevent requests first matching a lower
4640 // scoring network and then a higher scoring network, which could produce multiple
4641 // callbacks and inadvertently unlinger networks.
4642 Arrays.sort(nais);
4643 for (NetworkAgentInfo nai : nais) {
4644 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004645 // Only reap the last time through the loop. Reaping before all rematching
4646 // is complete could incorrectly teardown a network that hasn't yet been
4647 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004648 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004649 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004650 }
4651 }
4652 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004653
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004654 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004655 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004656 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004657 // For now only update icons for default connection.
4658 // TODO: Update WiFi and cellular icons separately. b/17237507
4659 if (!isDefaultNetwork(nai)) return;
4660
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004661 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004662 // Don't repeat publish.
4663 if (newInetCondition == mDefaultInetConditionPublished) return;
4664
4665 mDefaultInetConditionPublished = newInetCondition;
4666 sendInetConditionBroadcast(nai.networkInfo);
4667 }
4668
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004669 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4670 if (mLockdownTracker != null) {
4671 if (nai != null && nai.isVPN()) {
4672 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4673 } else {
4674 mLockdownTracker.onNetworkInfoChanged();
4675 }
4676 }
4677 }
4678
Robert Greenwalt7b816022014-04-18 15:25:25 -07004679 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4680 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004681 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004682 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004683 synchronized (networkAgent) {
4684 oldInfo = networkAgent.networkInfo;
4685 networkAgent.networkInfo = newInfo;
4686 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004687 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004688
4689 if (oldInfo != null && oldInfo.getState() == state) {
4690 if (VDBG) log("ignoring duplicate network state non-change");
4691 return;
4692 }
4693 if (DBG) {
4694 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4695 (oldInfo == null ? "null" : oldInfo.getState()) +
4696 " to " + state);
4697 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004698
Paul Jenseneec75412014-08-04 12:21:19 -04004699 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004700 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004701 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004702 if (networkAgent.isVPN()) {
4703 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004704 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4705 (networkAgent.networkMisc == null ||
4706 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004707 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004708 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4709 networkAgent.networkCapabilities.hasCapability(
4710 NET_CAPABILITY_NOT_RESTRICTED) ?
4711 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004712 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004713 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004714 loge("Error creating network " + networkAgent.network.netId + ": "
4715 + e.getMessage());
4716 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004717 }
Paul Jenseneec75412014-08-04 12:21:19 -04004718 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004719 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004720 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004721
Paul Jensenca8f16a2014-05-09 12:47:55 -04004722 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004723 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004724
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004725 if (networkAgent.isVPN()) {
4726 // Temporarily disable the default proxy (not global).
4727 synchronized (mProxyLock) {
4728 if (!mDefaultProxyDisabled) {
4729 mDefaultProxyDisabled = true;
4730 if (mGlobalProxy == null && mDefaultProxy != null) {
4731 sendProxyBroadcast(null);
4732 }
4733 }
4734 }
4735 // TODO: support proxy per network.
4736 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004737
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004738 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4739 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4740 // capabilities, so it only needs to be done once on initial connect, not every time the
4741 // network's capabilities change. Note that we do this before rematching the network,
4742 // so we could decide to tear it down immediately afterwards. That's fine though - on
4743 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4744 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004745 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004746
Paul Jensen2161a8e2014-09-11 11:00:39 -04004747 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004748 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004749
4750 // This has to happen after matching the requests, because callbacks are just requests.
4751 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004752 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004753 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004754 if (networkAgent.isVPN()) {
4755 synchronized (mProxyLock) {
4756 if (mDefaultProxyDisabled) {
4757 mDefaultProxyDisabled = false;
4758 if (mGlobalProxy == null && mDefaultProxy != null) {
4759 sendProxyBroadcast(mDefaultProxy);
4760 }
4761 }
4762 }
4763 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004764 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4765 state == NetworkInfo.State.SUSPENDED) {
4766 // going into or coming out of SUSPEND: rescore and notify
4767 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004768 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004769 }
4770 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4771 ConnectivityManager.CALLBACK_SUSPENDED :
4772 ConnectivityManager.CALLBACK_RESUMED));
4773 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004774 }
4775 }
4776
Robert Greenwaltac96c522014-06-03 16:43:57 -07004777 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4778 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004779 if (score < 0) {
4780 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4781 "). Bumping score to min of 0");
4782 score = 0;
4783 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004784
Paul Jensen2161a8e2014-09-11 11:00:39 -04004785 final int oldScore = nai.getCurrentScore();
4786 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004787
Paul Jensen85cf78e2015-06-25 13:25:07 -04004788 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004789
Paul Jensenc8b9a742014-09-30 15:37:41 -04004790 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004791 }
4792
Robert Greenwalt9258c642014-03-26 16:47:06 -07004793 // notify only this one new request of the current state
4794 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4795 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4796 // TODO - read state from monitor to decide what to send.
4797// if (nai.networkMonitor.isLingering()) {
4798// notifyType = NetworkCallbacks.LOSING;
4799// } else if (nai.networkMonitor.isEvaluating()) {
4800// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4801// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004802 if (nri.mPendingIntent == null) {
4803 callCallbackForRequest(nri, nai, notifyType);
4804 } else {
4805 sendPendingIntentForRequest(nri, nai, notifyType);
4806 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004807 }
4808
Robert Greenwalt8d482522015-06-24 13:23:42 -07004809 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004810 // The NetworkInfo we actually send out has no bearing on the real
4811 // state of affairs. For example, if the default connection is mobile,
4812 // and a request for HIPRI has just gone away, we need to pretend that
4813 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4814 // the state to DISCONNECTED, even though the network is of type MOBILE
4815 // and is still connected.
4816 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4817 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004818 if (state != DetailedState.DISCONNECTED) {
4819 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004820 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004821 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004822 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004823 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4824 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4825 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4826 if (info.isFailover()) {
4827 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4828 nai.networkInfo.setFailover(false);
4829 }
4830 if (info.getReason() != null) {
4831 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4832 }
4833 if (info.getExtraInfo() != null) {
4834 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4835 }
4836 NetworkAgentInfo newDefaultAgent = null;
4837 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004838 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004839 if (newDefaultAgent != null) {
4840 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4841 newDefaultAgent.networkInfo);
4842 } else {
4843 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4844 }
4845 }
4846 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4847 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004848 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004849 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004850 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004851 }
4852 }
4853 }
4854
Robert Greenwalt7b816022014-04-18 15:25:25 -07004855 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004856 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004857 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004858 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4859 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4860 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004861 if (nri.mPendingIntent == null) {
4862 callCallbackForRequest(nri, networkAgent, notifyType);
4863 } else {
4864 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4865 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004866 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004867 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004868
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004869 private String notifyTypeToName(int notifyType) {
4870 switch (notifyType) {
4871 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4872 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4873 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4874 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4875 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4876 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4877 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4878 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4879 }
4880 return "UNKNOWN";
4881 }
4882
Jeff Sharkey69736342014-12-08 14:50:12 -08004883 /**
4884 * Notify other system services that set of active ifaces has changed.
4885 */
4886 private void notifyIfacesChanged() {
4887 try {
4888 mStatsService.forceUpdateIfaces();
4889 } catch (Exception ignored) {
4890 }
4891 }
4892
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004893 @Override
4894 public boolean addVpnAddress(String address, int prefixLength) {
4895 throwIfLockdownEnabled();
4896 int user = UserHandle.getUserId(Binder.getCallingUid());
4897 synchronized (mVpns) {
4898 return mVpns.get(user).addAddress(address, prefixLength);
4899 }
4900 }
4901
4902 @Override
4903 public boolean removeVpnAddress(String address, int prefixLength) {
4904 throwIfLockdownEnabled();
4905 int user = UserHandle.getUserId(Binder.getCallingUid());
4906 synchronized (mVpns) {
4907 return mVpns.get(user).removeAddress(address, prefixLength);
4908 }
4909 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004910
4911 @Override
4912 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4913 throwIfLockdownEnabled();
4914 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004915 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004916 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004917 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004918 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004919 if (success) {
4920 notifyIfacesChanged();
4921 }
4922 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004923 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004924
4925 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004926 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4927 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4928 enforceKeepalivePermission();
4929 mKeepaliveTracker.startNattKeepalive(
4930 getNetworkAgentInfoForNetwork(network),
4931 intervalSeconds, messenger, binder,
4932 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4933 }
4934
4935 @Override
4936 public void stopKeepalive(Network network, int slot) {
4937 mHandler.sendMessage(mHandler.obtainMessage(
4938 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4939 }
4940
4941 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07004942 public void factoryReset() {
4943 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004944
4945 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4946 return;
4947 }
4948
Robin Lee3b3dd942015-05-12 18:14:58 +01004949 final int userId = UserHandle.getCallingUserId();
4950
Stuart Scottf1fb3972015-04-02 18:00:02 -07004951 // Turn airplane mode off
4952 setAirplaneMode(false);
4953
Stuart Scotte3e314d2015-04-20 14:07:45 -07004954 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4955 // Untether
4956 for (String tether : getTetheredIfaces()) {
4957 untether(tether);
4958 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004959 }
4960
Stuart Scotte3e314d2015-04-20 14:07:45 -07004961 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4962 // Turn VPN off
4963 VpnConfig vpnConfig = getVpnConfig(userId);
4964 if (vpnConfig != null) {
4965 if (vpnConfig.legacy) {
4966 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4967 } else {
4968 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4969 // in the future without user intervention.
4970 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004971
Stuart Scotte3e314d2015-04-20 14:07:45 -07004972 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4973 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004974 }
4975 }
4976 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004977
4978 @VisibleForTesting
4979 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4980 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4981 return new NetworkMonitor(context, handler, nai, defaultRequest);
4982 }
4983
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004984}