blob: 7e0e8d4961db7fc584c3a0f01dfb8985ece8730d [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060032import static android.net.NetworkPolicyManager.RULE_ALLOW_METERED;
Felipe Lemed31a97f2016-05-06 14:53:50 -070033import static android.net.NetworkPolicyManager.MASK_METERED_NETWORKS;
34import static android.net.NetworkPolicyManager.MASK_ALL_NETWORKS;
Felipe Leme46c4fc32016-05-04 09:21:43 -070035import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070036import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070037import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060038import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070039import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060040
Wenchao Tongf5ea3402015-03-04 13:26:38 -080041import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080042import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.Notification;
44import android.app.NotificationManager;
45import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070046import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.content.ContentResolver;
48import android.content.Context;
49import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070050import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070052import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090053import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070054import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090056import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080057import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070058import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070059import android.net.INetworkPolicyListener;
60import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070061import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080062import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070063import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070064import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070065import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070067import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070069import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070070import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070071import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070072import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070073import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070074import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070075import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040076import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070077import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040078import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040079import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090080import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090081import android.net.metrics.NetworkEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080083import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070084import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040085import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070087import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070089import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Looper;
91import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070092import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070094import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070095import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080097import android.os.ResultReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070099import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400100import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700102import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700103import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700104import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700105import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600106import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700107import android.util.LocalLog;
108import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600109import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700110import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800111import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700112import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500113import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700115import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400119import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700121import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700123import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800124import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700125import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700126import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700127import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900128import com.android.internal.util.MessageUtils;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700129import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700130import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400131import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900132import com.android.server.connectivity.KeepaliveTracker;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900133import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700134import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600135import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400136import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400137import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700138import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800139import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700140import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700141import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700142import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600143
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700144import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700145
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700146import org.xmlpull.v1.XmlPullParser;
147import org.xmlpull.v1.XmlPullParserException;
148
149import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700151import java.io.FileNotFoundException;
152import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700153import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700155import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700156import java.net.InetAddress;
157import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700158import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700159import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700160import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700161import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700162import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700163import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700164import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700165import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700166import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600167import java.util.SortedSet;
168import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
170/**
171 * @hide
172 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800173public class ConnectivityService extends IConnectivityManager.Stub
174 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700175 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900177 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700178 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Jake Hamby786e71a2014-02-06 14:43:50 -0800180 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900181 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700182
Jeff Sharkey899223b2012-08-04 15:24:58 -0700183 // TODO: create better separation between radio types and network types
184
Robert Greenwalt42acef32009-08-12 16:08:25 -0700185 // how long to wait before switching back to a radio's default network
186 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
187 // system property that can override the above value
188 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
189 "android.telephony.apn-restore";
190
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900191 // How long to wait before putting up a "This network doesn't have an Internet connection,
192 // connect anyway?" dialog after the user selects a network that doesn't validate.
193 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
194
Jeremy Joslin79294842014-12-03 17:15:28 -0800195 // How long to delay to removal of a pending intent based request.
196 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
197 private final int mReleasePendingIntentDelayMs;
198
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800199 private Tethering mTethering;
200
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700201 private final PermissionMonitor mPermissionMonitor;
202
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700203 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700204
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700205 @GuardedBy("mVpns")
206 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700207
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700208 private boolean mLockdownEnabled;
209 private LockdownVpnTracker mLockdownTracker;
210
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700211 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
212 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700213 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600214 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700215 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700216 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600217 @GuardedBy("mRulesLock")
218 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
219 /** Flag indicating if background data is restricted. */
220 @GuardedBy("mRulesLock")
221 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222
Erik Klineda4bfa82015-04-30 12:58:40 +0900223 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700225 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700226 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800228 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
230 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700231 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700233 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800234 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700235 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700236
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700237 private String mCurrentTcpBufferSizes;
238
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700239 private static final int ENABLED = 1;
240 private static final int DISABLED = 0;
241
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900242 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
243 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class });
244
Paul Jensenb10e37f2014-11-25 12:33:08 -0500245 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400246 // Tear down networks that have no chance (e.g. even if validated) of becoming
247 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500248 // all networks have been rematched against all NetworkRequests.
249 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400250 // Don't reap networks. This should be passed when some networks have not yet been
251 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500252 DONT_REAP
253 };
254
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700255 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700256 * used internally to change our mobile data enabled flag
257 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700258 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700259
260 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700261 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700262 * from one net to another. Clear happens when we get a new
263 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
264 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700265 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700266 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700267
Robert Greenwalt434203a2010-10-11 16:00:27 -0700268 /**
269 * used internally to reload global proxy settings
270 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700271 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700272
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700273 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400274 * PAC manager has received new port.
275 */
276 private static final int EVENT_PROXY_HAS_CHANGED = 16;
277
Robert Greenwalte049c232014-04-11 15:53:27 -0700278 /**
279 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700280 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700281 */
282 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
283
Robert Greenwalt7b816022014-04-18 15:25:25 -0700284 /**
285 * used internally when registering NetworkAgents
286 * obj = Messenger
287 */
288 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
289
Robert Greenwalt9258c642014-03-26 16:47:06 -0700290 /**
291 * used to add a network request
292 * includes a NetworkRequestInfo
293 */
294 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
295
296 /**
297 * indicates a timeout period is over - check if we had a network yet or not
298 * and if not, call the timeout calback (but leave the request live until they
299 * cancel it.
300 * includes a NetworkRequestInfo
301 */
302 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
303
304 /**
305 * used to add a network listener - no request
306 * includes a NetworkRequestInfo
307 */
308 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
309
310 /**
311 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400312 * arg1 = UID of caller
313 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700314 */
315 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
316
Robert Greenwalta67be032014-05-16 15:49:14 -0700317 /**
318 * used internally when registering NetworkFactories
319 * obj = Messenger
320 */
321 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
322
Robert Greenwalt27711812014-06-25 16:45:57 -0700323 /**
324 * used internally to expire a wakelock when transitioning
325 * from one net to another. Expire happens when we fail to find
326 * a new network (typically after 1 minute) -
327 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
328 * a replacement network.
329 */
330 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
331
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700332 /**
333 * Used internally to indicate the system is ready.
334 */
335 private static final int EVENT_SYSTEM_READY = 25;
336
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800337 /**
338 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400339 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800340 */
341 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
342
343 /**
344 * used to remove a pending intent and its associated network request.
345 * arg1 = UID of caller
346 * obj = PendingIntent
347 */
348 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
349
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900350 /**
351 * used to specify whether a network should be used even if unvalidated.
352 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
353 * arg2 = whether to remember this choice in the future (1 or 0)
354 * obj = network
355 */
356 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
357
358 /**
359 * used to ask the user to confirm a connection to an unvalidated network.
360 * obj = network
361 */
362 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700363
Erik Klineda4bfa82015-04-30 12:58:40 +0900364 /**
365 * used internally to (re)configure mobile data always-on settings.
366 */
367 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
368
Paul Jensen694f2b82015-06-17 14:15:39 -0400369 /**
370 * used to add a network listener with a pending intent
371 * obj = NetworkRequestInfo
372 */
373 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
374
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900375 /** Handler thread used for both of the handlers below. */
376 @VisibleForTesting
377 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700378 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700379 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700380 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700381 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700382
Mike Lockwood0f79b542009-08-14 14:18:49 -0400383 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800384 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400385
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700386 private PowerManager.WakeLock mNetTransitionWakeLock;
387 private String mNetTransitionWakeLockCausedBy = "";
388 private int mNetTransitionWakeLockSerialNumber;
389 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800390 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700391
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700392 // used in DBG mode to track inet condition reports
393 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
394 private ArrayList mInetLog;
395
Robert Greenwalt434203a2010-10-11 16:00:27 -0700396 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400397 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700398 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700399 private boolean mDefaultProxyDisabled = false;
400
Robert Greenwalt434203a2010-10-11 16:00:27 -0700401 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400402 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700403
Jason Monk602b2322013-07-03 17:04:33 -0400404 private PacManager mPacManager = null;
405
Erik Klineda4bfa82015-04-30 12:58:40 +0900406 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700407
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400408 private UserManager mUserManager;
409
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700410 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700411 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700412
Robert Greenwalt50393202011-06-21 17:26:14 -0700413 // the set of network types that can only be enabled by system/sig apps
414 List mProtectedNetworks;
415
John Spurlockbf991a82013-06-24 14:20:23 -0400416 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700417
Wink Savilleab9321d2013-06-29 21:10:57 -0700418 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400419
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900420 private KeepaliveTracker mKeepaliveTracker;
421
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700422 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
423 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700424 private final static int MAX_NET_ID = 65535;
425 private int mNextNetId = MIN_NET_ID;
426
Robert Greenwalt34524f02014-05-18 16:22:10 -0700427 // sequence number of NetworkRequests
428 private int mNextNetworkRequestId = 1;
429
Erik Kline7523eb32015-07-09 18:24:03 +0900430 // NetworkRequest activity String log entries.
431 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
432 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
433
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700434 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
435 private static final int MAX_VALIDATION_LOGS = 10;
436 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
437 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
438
439 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
440 synchronized(mValidationLogs) {
441 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
442 mValidationLogs.removeLast();
443 }
444 mValidationLogs.addFirst(new Pair(network, log));
445 }
446 }
447
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700448 /**
449 * Implements support for the legacy "one network per network type" model.
450 *
451 * We used to have a static array of NetworkStateTrackers, one for each
452 * network type, but that doesn't work any more now that we can have,
453 * for example, more that one wifi network. This class stores all the
454 * NetworkAgentInfo objects that support a given type, but the legacy
455 * API will only see the first one.
456 *
457 * It serves two main purposes:
458 *
459 * 1. Provide information about "the network for a given type" (since this
460 * API only supports one).
461 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
462 * the first network for a given type changes, or if the default network
463 * changes.
464 */
465 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900466
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900467 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900468 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900469
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700470 /**
471 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
472 * Each list holds references to all NetworkAgentInfos that are used to
473 * satisfy requests for that network type.
474 *
475 * This array is built out at startup such that an unsupported network
476 * doesn't get an ArrayList instance, making this a tristate:
477 * unsupported, supported but not active and active.
478 *
479 * The actual lists are populated when we scan the network types that
480 * are supported on this device.
481 */
482 private ArrayList<NetworkAgentInfo> mTypeLists[];
483
484 public LegacyTypeTracker() {
485 mTypeLists = (ArrayList<NetworkAgentInfo>[])
486 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
487 }
488
489 public void addSupportedType(int type) {
490 if (mTypeLists[type] != null) {
491 throw new IllegalStateException(
492 "legacy list for type " + type + "already initialized");
493 }
494 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
495 }
496
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700497 public boolean isTypeSupported(int type) {
498 return isNetworkTypeValid(type) && mTypeLists[type] != null;
499 }
500
501 public NetworkAgentInfo getNetworkForType(int type) {
502 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
503 return mTypeLists[type].get(0);
504 } else {
505 return null;
506 }
507 }
508
Robert Greenwalt8d482522015-06-24 13:23:42 -0700509 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900510 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900511 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700512 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900514 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515 }
516 }
517
518 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 public void add(int type, NetworkAgentInfo nai) {
520 if (!isTypeSupported(type)) {
521 return; // Invalid network type.
522 }
523 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
524
525 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
526 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700527 return;
528 }
529
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900530 list.add(nai);
531
532 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 final boolean isDefaultNetwork = isDefaultNetwork(nai);
534 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700535 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
536 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700537 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538 }
539
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900541 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900542 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
543 if (list == null || list.isEmpty()) {
544 return;
545 }
546
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900547 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548
549 if (!list.remove(nai)) {
550 return;
551 }
552
Robert Greenwalt8d482522015-06-24 13:23:42 -0700553 final DetailedState state = DetailedState.DISCONNECTED;
554
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900555 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700556 maybeLogBroadcast(nai, state, type, wasDefault);
557 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900558 }
559
560 if (!list.isEmpty() && wasFirstNetwork) {
561 if (DBG) log("Other network available for type " + type +
562 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900563 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700564 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
565 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900566 }
567 }
568
569 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900570 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
571 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900573 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574 }
575 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700576
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 // send out another legacy broadcast - currently only used for suspend/unsuspend
578 // toggle
579 public void update(NetworkAgentInfo nai) {
580 final boolean isDefault = isDefaultNetwork(nai);
581 final DetailedState state = nai.networkInfo.getDetailedState();
582 for (int type = 0; type < mTypeLists.length; type++) {
583 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700584 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700585 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700586 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700587 maybeLogBroadcast(nai, state, type, isDefault);
588 sendLegacyNetworkBroadcast(nai, state, type);
589 }
590 }
591 }
592
Lorenzo Colittia793a672014-07-31 23:20:17 +0900593 private String naiToString(NetworkAgentInfo nai) {
594 String name = (nai != null) ? nai.name() : "null";
595 String state = (nai.networkInfo != null) ?
596 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
597 "???/???";
598 return name + " " + state;
599 }
600
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700601 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900602 pw.println("mLegacyTypeTracker:");
603 pw.increaseIndent();
604 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700605 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900606 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700607 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900608 pw.println();
609 pw.println("Current state:");
610 pw.increaseIndent();
611 for (int type = 0; type < mTypeLists.length; type++) {
612 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
613 for (NetworkAgentInfo nai : mTypeLists[type]) {
614 pw.println(type + " " + naiToString(nai));
615 }
616 }
617 pw.decreaseIndent();
618 pw.decreaseIndent();
619 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700620 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700621 }
622 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
623
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900624 @VisibleForTesting
625 protected HandlerThread createHandlerThread() {
626 return new HandlerThread("ConnectivityServiceThread");
627 }
628
Jeff Sharkey899223b2012-08-04 15:24:58 -0700629 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700630 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800631 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800632
Erik Klineda4bfa82015-04-30 12:58:40 +0900633 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900634 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
Erik Kline371c7b72016-03-22 17:04:20 +0900635 new Binder(), NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +0900636 mNetworkRequests.put(mDefaultRequest, defaultNRI);
637 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900638
639 mDefaultMobileDataRequest = createInternetRequestForTransport(
640 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700641
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900642 mHandlerThread = createHandlerThread();
643 mHandlerThread.start();
644 mHandler = new InternalHandler(mHandlerThread.getLooper());
645 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700646
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800647 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800648 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
649 String id = Settings.Secure.getString(context.getContentResolver(),
650 Settings.Secure.ANDROID_ID);
651 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700652 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800653 SystemProperties.set("net.hostname", name);
654 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800655 }
656
Jeremy Joslin79294842014-12-03 17:15:28 -0800657 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
658 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
659
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700660 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700661 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800662 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700663 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700664 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700665 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700666
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700667 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600668 mPolicyManager.setConnectivityListener(mPolicyListener);
669 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700670 } catch (RemoteException e) {
671 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700672 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700673 }
674
675 final PowerManager powerManager = (PowerManager) context.getSystemService(
676 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700677 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
678 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
679 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800680 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700681
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700682 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700683
Wink Saville51f456f2013-04-23 14:26:51 -0700684 // TODO: What is the "correct" way to do determine if this is a wifi only device?
685 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
686 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700687 String[] naStrings = context.getResources().getStringArray(
688 com.android.internal.R.array.networkAttributes);
689 for (String naString : naStrings) {
690 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700691 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700692 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700693 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800694 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700695 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700696 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700697 }
Wink Saville51f456f2013-04-23 14:26:51 -0700698 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
699 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
700 n.type);
701 continue;
702 }
Wink Saville975c8482011-04-07 14:23:45 -0700703 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800704 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700705 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700706 continue;
707 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700708 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700709
Wink Saville975c8482011-04-07 14:23:45 -0700710 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700711 mNetworksDefined++;
712 } catch(Exception e) {
713 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700714 }
715 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700716
717 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
718 if (mNetConfigs[TYPE_VPN] == null) {
719 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
720 // don't need to add TYPE_VPN to mNetConfigs.
721 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
722 mNetworksDefined++; // used only in the log() statement below.
723 }
724
Wink Saville5e56bc52013-07-29 15:00:57 -0700725 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700726
Robert Greenwalt50393202011-06-21 17:26:14 -0700727 mProtectedNetworks = new ArrayList<Integer>();
728 int[] protectedNetworks = context.getResources().getIntArray(
729 com.android.internal.R.array.config_protectedNetworks);
730 for (int p : protectedNetworks) {
731 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
732 mProtectedNetworks.add(p);
733 } else {
734 if (DBG) loge("Ignoring protectedNetwork " + p);
735 }
736 }
737
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700738 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
739 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700740
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800741 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800742
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700743 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
744
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700745 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700746 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100747 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700748 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700749 intentFilter.addAction(Intent.ACTION_USER_ADDED);
750 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000751 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700752 mContext.registerReceiverAsUser(
753 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900754
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700755 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700756 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700757 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700758 } catch (RemoteException e) {
759 loge("Error registering observer :" + e);
760 }
761
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700762 if (DBG) {
763 mInetLog = new ArrayList();
764 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700765
Erik Klineda4bfa82015-04-30 12:58:40 +0900766 mSettingsObserver = new SettingsObserver(mContext, mHandler);
767 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800768
John Spurlockbf991a82013-06-24 14:20:23 -0400769 mDataConnectionStats = new DataConnectionStats(mContext);
770 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400771
Jason Monkdecd2952013-10-10 14:02:51 -0400772 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700773
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400774 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900775
776 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800777 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700778
Erik Klineda4bfa82015-04-30 12:58:40 +0900779 private NetworkRequest createInternetRequestForTransport(int transportType) {
780 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900781 netCap.addCapability(NET_CAPABILITY_INTERNET);
782 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900783 if (transportType > -1) {
784 netCap.addTransportType(transportType);
785 }
786 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
787 }
788
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900789 // Used only for testing.
790 // TODO: Delete this and either:
791 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
792 // changing ContentResolver to make registerContentObserver non-final).
793 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
794 // by subclassing SettingsObserver.
795 @VisibleForTesting
796 void updateMobileDataAlwaysOn() {
797 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
798 }
799
Erik Klineda4bfa82015-04-30 12:58:40 +0900800 private void handleMobileDataAlwaysOn() {
801 final boolean enable = (Settings.Global.getInt(
802 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
803 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
804 if (enable == isEnabled) {
805 return; // Nothing to do.
806 }
807
808 if (enable) {
809 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900810 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900811 } else {
812 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
813 }
814 }
815
816 private void registerSettingsCallbacks() {
817 // Watch for global HTTP proxy changes.
818 mSettingsObserver.observe(
819 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
820 EVENT_APPLY_GLOBAL_HTTP_PROXY);
821
822 // Watch for whether or not to keep mobile data always on.
823 mSettingsObserver.observe(
824 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
825 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
826 }
827
Robert Greenwalt34524f02014-05-18 16:22:10 -0700828 private synchronized int nextNetworkRequestId() {
829 return mNextNetworkRequestId++;
830 }
831
Paul Jensen67b0b072015-06-10 11:22:17 -0400832 @VisibleForTesting
833 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400834 synchronized (mNetworkForNetId) {
835 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
836 int netId = mNextNetId;
837 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
838 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500839 if (!mNetIdInUse.get(netId)) {
840 mNetIdInUse.put(netId, true);
841 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400842 }
843 }
844 }
845 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700846 }
847
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600848 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800849 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600850 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
851 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800852 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600853 state = nai.getNetworkState();
854 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800855 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600856 final NetworkInfo info = new NetworkInfo(networkType, 0,
857 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800858 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
859 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600860 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
861 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800862 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600863 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600864 return state;
865 } else {
866 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800867 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400868 }
869
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800870 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
871 if (network == null) {
872 return null;
873 }
874 synchronized (mNetworkForNetId) {
875 return mNetworkForNetId.get(network.netId);
876 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600877 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800878
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900879 private Network[] getVpnUnderlyingNetworks(int uid) {
880 if (!mLockdownEnabled) {
881 int user = UserHandle.getUserId(uid);
882 synchronized (mVpns) {
883 Vpn vpn = mVpns.get(user);
884 if (vpn != null && vpn.appliesToUid(uid)) {
885 return vpn.getUnderlyingNetworks();
886 }
887 }
888 }
889 return null;
890 }
891
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800892 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400893 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800894
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900895 final Network[] networks = getVpnUnderlyingNetworks(uid);
896 if (networks != null) {
897 // getUnderlyingNetworks() returns:
898 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
899 // empty array => the VPN explicitly said "no default network".
900 // non-empty array => the VPN specified one or more default networks; we use the
901 // first one.
902 if (networks.length > 0) {
903 nai = getNetworkAgentInfoForNetwork(networks[0]);
904 } else {
905 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800906 }
907 }
908
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800909 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600910 return nai.getNetworkState();
911 } else {
912 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800913 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400914 }
915
916 /**
917 * Check if UID should be blocked from using the network with the given LinkProperties.
918 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600919 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
920 boolean ignoreBlocked) {
921 // Networks aren't blocked when ignoring blocked status
922 if (ignoreBlocked) return false;
923 // Networks are never blocked for system services
924 if (uid < Process.FIRST_APPLICATION_UID) return false;
925
926 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700927 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700928
Robin Lee17e61832016-05-09 13:46:28 +0100929 synchronized (mVpns) {
930 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
931 if (vpn != null && vpn.isBlockingUid(uid)) {
932 return true;
933 }
934 }
935
Robert Greenwalt12e67352014-05-13 21:41:06 -0700936 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700937 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600938 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -0700939 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700940 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700941
Felipe Lemed31a97f2016-05-06 14:53:50 -0700942 boolean allowed = true;
943 // Check Data Saver Mode first...
944 if (networkMetered) {
945 if ((uidRules & RULE_REJECT_METERED) != 0) {
946 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
947 // Explicitly blacklisted.
948 allowed = false;
949 } else {
950 allowed = !mRestrictBackground
951 || (uidRules & RULE_ALLOW_METERED) != 0
952 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
953 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
954 + " mRestrictBackground=" + mRestrictBackground
955 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
956 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
957 + ": " + allowed);
958 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700959 }
Felipe Leme781ba142016-05-09 16:24:48 -0700960 // ...then power restrictions.
961 if (allowed) {
962 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -0700963 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -0700964 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -0700965 }
966 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700967 }
968
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900969 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
970 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
971 boolean removed = false;
972 boolean added = false;
973 synchronized (mBlockedAppUids) {
974 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
975 added = true;
976 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
977 removed = true;
978 }
979 }
980 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
981 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
982 }
983
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700984 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600985 * Apply any relevant filters to {@link NetworkState} for the given UID. For
986 * example, this may mark the network as {@link DetailedState#BLOCKED} based
987 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
988 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700989 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600990 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600991 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
992
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600993 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600994 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700995 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600996 if (mLockdownTracker != null) {
997 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700998 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600999
1000 // TODO: apply metered state closer to NetworkAgentInfo
1001 final long token = Binder.clearCallingIdentity();
1002 try {
1003 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1004 } catch (RemoteException e) {
1005 } finally {
1006 Binder.restoreCallingIdentity(token);
1007 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001008 }
1009
1010 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001011 * Return NetworkInfo for the active (i.e., connected) network interface.
1012 * It is assumed that at most one network is active at a time. If more
1013 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001014 * @return the info for the active network, or {@code null} if none is
1015 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001017 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 enforceAccessPermission();
1020 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001021 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001022 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001023 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1024 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001025 }
1026
Paul Jensen31a94f42015-02-13 14:18:39 -05001027 @Override
1028 public Network getActiveNetwork() {
1029 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001030 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001031 }
1032
1033 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001034 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001035 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001036 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001037 }
1038
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001039 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001040 final int user = UserHandle.getUserId(uid);
1041 int vpnNetId = NETID_UNSET;
1042 synchronized (mVpns) {
1043 final Vpn vpn = mVpns.get(user);
1044 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1045 }
1046 NetworkAgentInfo nai;
1047 if (vpnNetId != NETID_UNSET) {
1048 synchronized (mNetworkForNetId) {
1049 nai = mNetworkForNetId.get(vpnNetId);
1050 }
1051 if (nai != null) return nai.network;
1052 }
1053 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001054 if (nai != null
1055 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1056 nai = null;
1057 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001058 return nai != null ? nai.network : null;
1059 }
1060
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001061 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1062 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001063 final int uid = Binder.getCallingUid();
1064 NetworkState state = getUnfilteredActiveNetworkState(uid);
1065 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001066 }
1067
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001068 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001069 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001070 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001071 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001072 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001073 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001074 }
1075
1076 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 public NetworkInfo getNetworkInfo(int networkType) {
1078 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001079 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001080 if (getVpnUnderlyingNetworks(uid) != null) {
1081 // A VPN is active, so we may need to return one of its underlying networks. This
1082 // information is not available in LegacyTypeTracker, so we have to get it from
1083 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001084 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001085 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001086 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001087 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001088 }
1089 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001090 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001091 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001092 }
1093
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001094 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001095 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001096 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001097 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001098 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001099 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001100 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001101 return state.networkInfo;
1102 } else {
1103 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001104 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001105 }
1106
1107 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 public NetworkInfo[] getAllNetworkInfo() {
1109 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001110 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001111 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1112 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001113 NetworkInfo info = getNetworkInfo(networkType);
1114 if (info != null) {
1115 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001116 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001118 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001119 }
1120
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001121 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001122 public Network getNetworkForType(int networkType) {
1123 enforceAccessPermission();
1124 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001125 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1126 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001127 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001128 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001129 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001130 }
1131
1132 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001133 public Network[] getAllNetworks() {
1134 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001135 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001136 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001137 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001138 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001139 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001140 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001141 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001142 }
1143
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001144 @Override
1145 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1146 // The basic principle is: if an app's traffic could possibly go over a
1147 // network, without the app doing anything multinetwork-specific,
1148 // (hence, by "default"), then include that network's capabilities in
1149 // the array.
1150 //
1151 // In the normal case, app traffic only goes over the system's default
1152 // network connection, so that's the only network returned.
1153 //
1154 // With a VPN in force, some app traffic may go into the VPN, and thus
1155 // over whatever underlying networks the VPN specifies, while other app
1156 // traffic may go over the system default network (e.g.: a split-tunnel
1157 // VPN, or an app disallowed by the VPN), so the set of networks
1158 // returned includes the VPN's underlying networks and the system
1159 // default.
1160 enforceAccessPermission();
1161
1162 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1163
1164 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001165 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001166 if (nc != null) {
1167 result.put(nai.network, nc);
1168 }
1169
1170 if (!mLockdownEnabled) {
1171 synchronized (mVpns) {
1172 Vpn vpn = mVpns.get(userId);
1173 if (vpn != null) {
1174 Network[] networks = vpn.getUnderlyingNetworks();
1175 if (networks != null) {
1176 for (Network network : networks) {
1177 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001178 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001179 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001180 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001181 }
1182 }
1183 }
1184 }
1185 }
1186 }
1187
1188 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1189 out = result.values().toArray(out);
1190 return out;
1191 }
1192
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001193 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001194 public boolean isNetworkSupported(int networkType) {
1195 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001196 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001197 }
1198
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001199 /**
1200 * Return LinkProperties for the active (i.e., connected) default
1201 * network interface. It is assumed that at most one default network
1202 * is active at a time. If more than one is active, it is indeterminate
1203 * which will be returned.
1204 * @return the ip properties for the active network, or {@code null} if
1205 * none is active
1206 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001207 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001208 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001209 enforceAccessPermission();
1210 final int uid = Binder.getCallingUid();
1211 NetworkState state = getUnfilteredActiveNetworkState(uid);
1212 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001213 }
1214
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001215 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001216 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001217 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001218 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1219 if (nai != null) {
1220 synchronized (nai) {
1221 return new LinkProperties(nai.linkProperties);
1222 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001223 }
1224 return null;
1225 }
1226
Robert Greenwalt12e67352014-05-13 21:41:06 -07001227 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001228 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001229 public LinkProperties getLinkProperties(Network network) {
1230 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001231 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001232 if (nai != null) {
1233 synchronized (nai) {
1234 return new LinkProperties(nai.linkProperties);
1235 }
1236 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001237 return null;
1238 }
1239
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001240 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001241 if (nai != null) {
1242 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001243 if (nai.networkCapabilities != null) {
1244 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001245 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001246 }
1247 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001248 return null;
1249 }
1250
1251 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001252 public NetworkCapabilities getNetworkCapabilities(Network network) {
1253 enforceAccessPermission();
1254 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1255 }
1256
1257 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001258 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001259 // Require internal since we're handing out IMSI details
1260 enforceConnectivityInternalPermission();
1261
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001262 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001263 for (Network network : getAllNetworks()) {
1264 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1265 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001266 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001267 }
1268 }
1269 return result.toArray(new NetworkState[result.size()]);
1270 }
1271
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001272 @Override
1273 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1274 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001275 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001276 final long token = Binder.clearCallingIdentity();
1277 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001278 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1279 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001280 try {
1281 return mPolicyManager.getNetworkQuotaInfo(state);
1282 } catch (RemoteException e) {
1283 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001284 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001285 return null;
1286 } finally {
1287 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001288 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001289 }
1290
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001291 @Override
1292 public boolean isActiveNetworkMetered() {
1293 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001294
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001295 final NetworkInfo info = getActiveNetworkInfo();
1296 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001297 }
1298
Jeff Sharkey216c1812012-08-05 14:29:23 -07001299 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1300 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001301 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001302 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001303 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001304 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001305 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001306
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001307 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 * Ensure that a network route exists to deliver traffic to the specified
1309 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001310 * @param networkType the type of the network over which traffic to the
1311 * specified host is to be routed
1312 * @param hostAddress the IP address of the host to which the route is
1313 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 * @return {@code true} on success, {@code false} on failure
1315 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001316 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001317 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001318 if (mProtectedNetworks.contains(networkType)) {
1319 enforceConnectivityInternalPermission();
1320 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001321
Chad Brubakerc0234532014-02-14 13:24:29 -08001322 InetAddress addr;
1323 try {
1324 addr = InetAddress.getByAddress(hostAddress);
1325 } catch (UnknownHostException e) {
1326 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1327 return false;
1328 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001329
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001330 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001331 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 return false;
1333 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001334
1335 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1336 if (nai == null) {
1337 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1338 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1339 } else {
1340 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1341 }
1342 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001343 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001344
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001345 DetailedState netState;
1346 synchronized (nai) {
1347 netState = nai.networkInfo.getDetailedState();
1348 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001349
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001350 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001351 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001352 log("requestRouteToHostAddress on down network "
1353 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001354 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001355 }
1356 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001358
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001359 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001360 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001361 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001362 LinkProperties lp;
1363 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001364 synchronized (nai) {
1365 lp = nai.linkProperties;
1366 netId = nai.network.netId;
1367 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001368 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001369 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1370 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001371 } finally {
1372 Binder.restoreCallingIdentity(token);
1373 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001374 }
1375
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001376 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001377 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001378 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001379 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001380 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001381 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001382 if (bestRoute.getGateway().equals(addr)) {
1383 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001384 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001385 } else {
1386 // if we will connect to this through another route, add a direct route
1387 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001388 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001389 }
1390 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001391 if (DBG) log("Adding legacy route " + bestRoute +
1392 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001393 try {
1394 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1395 } catch (Exception e) {
1396 // never crash - catch them all
1397 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001398 return false;
1399 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001400 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001403 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1404 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001405 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001406 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001407 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001408 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001409 }
1410
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001411 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001412 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001413 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001414 if (oldRules == uidRules) return;
1415
Felipe Leme781ba142016-05-09 16:24:48 -07001416 if (uidRules == RULE_NONE) {
1417 mUidRules.delete(uid);
1418 } else {
1419 mUidRules.put(uid, uidRules);
1420 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001421 }
1422
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001423 // TODO: notify UID when it has requested targeted updates
1424 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001425
1426 @Override
1427 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001428 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001429 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001430 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001431 }
1432
1433 synchronized (mRulesLock) {
1434 mMeteredIfaces.clear();
1435 for (String iface : meteredIfaces) {
1436 mMeteredIfaces.add(iface);
1437 }
1438 }
1439 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001440
1441 @Override
1442 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1443 // caller is NPMS, since we only register with them
1444 if (LOGD_RULES) {
1445 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1446 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001447
1448 synchronized (mRulesLock) {
1449 mRestrictBackground = restrictBackground;
1450 }
1451
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001452 if (restrictBackground) {
1453 log("onRestrictBackgroundChanged(true): disabling tethering");
1454 mTethering.untetherAll();
1455 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001456 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001457
1458 @Override
1459 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1460 if (LOGD_RULES) {
1461 // caller is NPMS, since we only register with them
1462 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1463 + whitelisted + ")");
1464 }
1465 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001466 @Override
1467 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1468 if (LOGD_RULES) {
1469 // caller is NPMS, since we only register with them
1470 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1471 + blacklisted + ")");
1472 }
1473 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001474 };
1475
Robin Lee3b3dd942015-05-12 18:14:58 +01001476 /**
1477 * Require that the caller is either in the same user or has appropriate permission to interact
1478 * across users.
1479 *
1480 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1481 */
1482 private void enforceCrossUserPermission(int userId) {
1483 if (userId == UserHandle.getCallingUserId()) {
1484 // Not a cross-user call.
1485 return;
1486 }
1487 mContext.enforceCallingOrSelfPermission(
1488 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1489 "ConnectivityService");
1490 }
1491
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001492 private void enforceInternetPermission() {
1493 mContext.enforceCallingOrSelfPermission(
1494 android.Manifest.permission.INTERNET,
1495 "ConnectivityService");
1496 }
1497
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001498 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001499 mContext.enforceCallingOrSelfPermission(
1500 android.Manifest.permission.ACCESS_NETWORK_STATE,
1501 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001502 }
1503
1504 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001505 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001506 }
1507
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001508 private void enforceTetherAccessPermission() {
1509 mContext.enforceCallingOrSelfPermission(
1510 android.Manifest.permission.ACCESS_NETWORK_STATE,
1511 "ConnectivityService");
1512 }
1513
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001514 private void enforceConnectivityInternalPermission() {
1515 mContext.enforceCallingOrSelfPermission(
1516 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1517 "ConnectivityService");
1518 }
1519
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001520 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001521 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001522 }
1523
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001524 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001525 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001526 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001527 }
1528
1529 private void sendInetConditionBroadcast(NetworkInfo info) {
1530 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1531 }
1532
Wink Saville628b0852011-08-04 15:01:58 -07001533 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001534 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001535 info = new NetworkInfo(info);
1536 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001537 }
1538
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001539 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001540 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001541 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 if (info.isFailover()) {
1543 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1544 info.setFailover(false);
1545 }
1546 if (info.getReason() != null) {
1547 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1548 }
1549 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001550 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1551 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001553 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001554 return intent;
1555 }
1556
1557 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1558 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1559 }
1560
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001561 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001562 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1563 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1564 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001565 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001566 final long ident = Binder.clearCallingIdentity();
1567 try {
1568 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1569 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1570 } finally {
1571 Binder.restoreCallingIdentity(ident);
1572 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001573 }
1574
Mike Lockwood0f79b542009-08-14 14:18:49 -04001575 private void sendStickyBroadcast(Intent intent) {
1576 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001577 if (!mSystemReady) {
1578 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001579 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001580 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001581 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001582 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001583 }
1584
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001585 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001586 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001587 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001588 final NetworkInfo ni = intent.getParcelableExtra(
1589 ConnectivityManager.EXTRA_NETWORK_INFO);
1590 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1591 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1592 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001593 } else {
1594 BroadcastOptions opts = BroadcastOptions.makeBasic();
1595 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1596 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001597 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001598 final IBatteryStats bs = BatteryStatsService.getService();
1599 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001600 bs.noteConnectivityChanged(intent.getIntExtra(
1601 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1602 ni != null ? ni.getState().toString() : "?");
1603 } catch (RemoteException e) {
1604 }
1605 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001606 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001607 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001608 } finally {
1609 Binder.restoreCallingIdentity(ident);
1610 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001611 }
1612 }
1613
1614 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001615 loadGlobalProxy();
1616
Mike Lockwood0f79b542009-08-14 14:18:49 -04001617 synchronized(this) {
1618 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001619 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001620 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001621 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001622 }
1623 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001624 // load the global proxy at startup
1625 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001626
Robin Lee244ce8e2016-01-05 18:03:46 +00001627 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1628 // for user to unlock device too.
1629 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001630
Erik Klineda4bfa82015-04-30 12:58:40 +09001631 // Configure whether mobile data is always on.
1632 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1633
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001634 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001635
1636 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001640 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001641 *
1642 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001643 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001644 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1646 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001647
1648 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001649 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001650
Robert Greenwalt7b816022014-04-18 15:25:25 -07001651 if (networkAgent.networkCapabilities.hasTransport(
1652 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001653 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1654 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001655 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001656 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001657 } else if (networkAgent.networkCapabilities.hasTransport(
1658 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001659 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1660 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001661 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001662 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001663 } else {
1664 // do not track any other networks
1665 timeout = 0;
1666 }
1667
Robert Greenwalt7b816022014-04-18 15:25:25 -07001668 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001669 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001670 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001671 } catch (Exception e) {
1672 // You shall not crash!
1673 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001674 }
1675 }
1676 }
1677
1678 /**
1679 * Remove data activity tracking when network disconnects.
1680 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001681 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1682 final String iface = networkAgent.linkProperties.getInterfaceName();
1683 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001684
Robert Greenwalt7b816022014-04-18 15:25:25 -07001685 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1686 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001687 try {
1688 // the call fails silently if no idletimer setup for this interface
1689 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001690 } catch (Exception e) {
1691 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001692 }
1693 }
1694 }
1695
1696 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001697 * Reads the network specific MTU size from reources.
1698 * and set it on it's iface.
1699 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001700 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1701 final String iface = newLp.getInterfaceName();
1702 final int mtu = newLp.getMtu();
1703 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1704 if (VDBG) log("identical MTU - not setting");
1705 return;
1706 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001707
Robert Greenwalt43074032014-08-15 17:53:05 -07001708 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001709 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001710 return;
1711 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001712
w1997615afd812014-08-05 15:18:11 -07001713 // Cannot set MTU without interface name
1714 if (TextUtils.isEmpty(iface)) {
1715 loge("Setting MTU size with null iface.");
1716 return;
1717 }
1718
Robert Greenwalt7b816022014-04-18 15:25:25 -07001719 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001720 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001721 mNetd.setMtu(iface, mtu);
1722 } catch (Exception e) {
1723 Slog.e(TAG, "exception in setMtu()" + e);
1724 }
1725 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001726
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001727 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001728 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1729
1730 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001731 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001732 protected int getDefaultTcpRwnd() {
1733 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1734 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001735
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001736 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1737 if (isDefaultNetwork(nai) == false) {
1738 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001739 }
1740
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001741 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1742 String[] values = null;
1743 if (tcpBufferSizes != null) {
1744 values = tcpBufferSizes.split(",");
1745 }
1746
1747 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001748 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001749 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1750 values = tcpBufferSizes.split(",");
1751 }
1752
1753 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1754
1755 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001756 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001757
1758 final String prefix = "/sys/kernel/ipv4/tcp_";
1759 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1760 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1761 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1762 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1763 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1764 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1765 mCurrentTcpBufferSizes = tcpBufferSizes;
1766 } catch (IOException e) {
1767 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001768 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001769
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001770 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001771 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001772 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1773 if (rwndValue != 0) {
1774 SystemProperties.set(sysctlKey, rwndValue.toString());
1775 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001776 }
1777
Mattias Falk8b47b362011-08-23 14:15:13 +02001778 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001779 /*
1780 * Tell the VMs to toss their DNS caches
1781 */
1782 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1783 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001784 /*
1785 * Connectivity events can happen before boot has completed ...
1786 */
1787 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001788 final long ident = Binder.clearCallingIdentity();
1789 try {
1790 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1791 } finally {
1792 Binder.restoreCallingIdentity(ident);
1793 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001794 }
1795
Robert Greenwalt562cc542014-05-15 18:07:26 -07001796 @Override
1797 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001798 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1799 NETWORK_RESTORE_DELAY_PROP_NAME);
1800 if(restoreDefaultNetworkDelayStr != null &&
1801 restoreDefaultNetworkDelayStr.length() != 0) {
1802 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001803 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001804 } catch (NumberFormatException e) {
1805 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001806 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001807 // if the system property isn't set, use the value for the apn type
1808 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1809
1810 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1811 (mNetConfigs[networkType] != null)) {
1812 ret = mNetConfigs[networkType].restoreTime;
1813 }
1814 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001815 }
1816
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001817 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001818 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001819 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001820 }
1821 return false;
1822 }
1823
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001824 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1825 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1826 final long DIAG_TIME_MS = 5000;
1827 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1828 // Start gathering diagnostic information.
1829 netDiags.add(new NetworkDiagnostics(
1830 nai.network,
1831 new LinkProperties(nai.linkProperties), // Must be a copy.
1832 DIAG_TIME_MS));
1833 }
1834
1835 for (NetworkDiagnostics netDiag : netDiags) {
1836 pw.println();
1837 netDiag.waitForMeasurements();
1838 netDiag.dump(pw);
1839 }
1840 }
1841
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001842 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001843 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1844 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001845 if (mContext.checkCallingOrSelfPermission(
1846 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001847 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001848 pw.println("Permission Denial: can't dump ConnectivityService " +
1849 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1850 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001851 return;
1852 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001853
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001854 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001855 dumpNetworkDiagnostics(pw);
1856 return;
1857 }
Erik Kline379747a2015-06-05 17:47:34 +09001858
Lorenzo Colittie3805462015-06-03 11:18:24 +09001859 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001860 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001861 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001862 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001863 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001864 pw.println();
1865
Paul Jensen85cf78e2015-06-25 13:25:07 -04001866 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001867 pw.print("Active default network: ");
1868 if (defaultNai == null) {
1869 pw.println("none");
1870 } else {
1871 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001873 pw.println();
1874
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001875 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001876 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001877 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1878 pw.println(nai.toString());
1879 pw.increaseIndent();
1880 pw.println("Requests:");
1881 pw.increaseIndent();
1882 for (int i = 0; i < nai.networkRequests.size(); i++) {
1883 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001884 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001885 pw.decreaseIndent();
1886 pw.println("Lingered:");
1887 pw.increaseIndent();
1888 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1889 pw.decreaseIndent();
1890 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001891 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001892 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001893 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001894
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001895 pw.println("Metered Interfaces:");
1896 pw.increaseIndent();
1897 for (String value : mMeteredIfaces) {
1898 pw.println(value);
1899 }
1900 pw.decreaseIndent();
1901 pw.println();
1902
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001903 pw.print("Restrict background: ");
1904 pw.println(mRestrictBackground);
1905 pw.println();
1906
Felipe Leme46c4fc32016-05-04 09:21:43 -07001907 pw.println("Status for known UIDs:");
1908 pw.increaseIndent();
1909 final int size = mUidRules.size();
1910 for (int i = 0; i < size; i++) {
1911 final int uid = mUidRules.keyAt(i);
1912 pw.print("UID=");
1913 pw.print(uid);
1914 final int uidRules = mUidRules.get(uid, RULE_NONE);
1915 pw.print(" rules=");
1916 pw.print(uidRulesToString(uidRules));
1917 pw.println();
1918 }
1919 pw.println();
1920 pw.decreaseIndent();
1921
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001922 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001923 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001924 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1925 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001926 }
1927 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001928 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001929
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001930 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001931
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001932 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001933 pw.print("mNetTransitionWakeLock: currently " +
1934 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1935 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1936 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1937 } else {
1938 pw.println(", last requested never");
1939 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001940 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001941
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001942 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001943 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001944
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001945 pw.println();
1946 mKeepaliveTracker.dump(pw);
1947
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001948 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001949
Lorenzo Colittie3805462015-06-03 11:18:24 +09001950 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001951 pw.println();
1952 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001953 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001954 for(int i = 0; i < mInetLog.size(); i++) {
1955 pw.println(mInetLog.get(i));
1956 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001957 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001958 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001959
1960 if (argsContain(args, "--short") == false) {
1961 pw.println();
1962 synchronized (mValidationLogs) {
1963 pw.println("mValidationLogs (most recent first):");
1964 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1965 pw.println(p.first);
1966 pw.increaseIndent();
1967 p.second.dump(fd, pw, args);
1968 pw.decreaseIndent();
1969 }
1970 }
Erik Kline7523eb32015-07-09 18:24:03 +09001971
1972 pw.println();
1973 pw.println("mNetworkRequestInfoLogs (most recent first):");
1974 pw.increaseIndent();
1975 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1976 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001980 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001981 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001982 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001983 if (officialNai != null && officialNai.equals(nai)) return true;
1984 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001985 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001986 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001987 " - " + nai);
1988 }
1989 return false;
1990 }
1991
Paul Jensenc8b9a742014-09-30 15:37:41 -04001992 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001993 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001994 }
1995
Robert Greenwalt42acef32009-08-12 16:08:25 -07001996 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001997 private class NetworkStateTrackerHandler extends Handler {
1998 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001999 super(looper);
2000 }
2001
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002002 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002004 default:
2005 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002006 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002007 handleAsyncChannelHalfConnect(msg);
2008 break;
2009 }
2010 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2011 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2012 if (nai != null) nai.asyncChannel.disconnect();
2013 break;
2014 }
2015 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2016 handleAsyncChannelDisconnected(msg);
2017 break;
2018 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002019 }
2020 return true;
2021 }
2022
2023 private void maybeHandleNetworkAgentMessage(Message msg) {
2024 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2025 if (nai == null) {
2026 if (VDBG) {
2027 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2028 log(String.format("%s from unknown NetworkAgent", what));
2029 }
2030 return;
2031 }
2032
2033 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002034 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002035 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2036 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2037 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2038 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002039 }
Robin Lee585e2482016-05-01 23:00:00 +01002040 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002041 networkCapabilities)) {
2042 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2043 + nai.networkCapabilities + " -> " + networkCapabilities);
2044 }
2045 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002046 break;
2047 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002048 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002049 if (VDBG) {
2050 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002051 "; created=" + nai.created +
2052 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002053 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002054 LinkProperties oldLp = nai.linkProperties;
2055 synchronized (nai) {
2056 nai.linkProperties = (LinkProperties)msg.obj;
2057 }
Robin Lee585e2482016-05-01 23:00:00 +01002058 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002059 break;
2060 }
2061 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002062 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002063 updateNetworkInfo(nai, info);
2064 break;
2065 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002066 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002067 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002068 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002069 break;
2070 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002071 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002072 try {
2073 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002074 } catch (Exception e) {
2075 // Never crash!
2076 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002077 }
2078 break;
2079 }
2080 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002081 try {
2082 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002083 } catch (Exception e) {
2084 // Never crash!
2085 loge("Exception in removeVpnUidRanges: " + e);
2086 }
2087 break;
2088 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002089 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002090 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2091 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002092 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002093 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002094 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002095 break;
2096 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002097 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002098 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2099 break;
2100 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002101 }
2102 }
2103
2104 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2105 switch (msg.what) {
2106 default:
2107 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002108 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002109 final NetworkAgentInfo nai;
2110 synchronized (mNetworkForNetId) {
2111 nai = mNetworkForNetId.get(msg.arg2);
2112 }
2113 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002114 final boolean valid =
2115 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002116 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2117 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002118 if (valid != nai.lastValidated) {
2119 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002120 nai.lastValidated = valid;
2121 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002122 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002123 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2124 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002125 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002126 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002127 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002128 Bundle redirectUrlBundle = new Bundle();
2129 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002130 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002131 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002132 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002133 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002134 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 break;
2136 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002137 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002139 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002140 handleLingerComplete(nai);
2141 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002142 break;
2143 }
Paul Jensen869868be2014-05-15 10:33:05 -04002144 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002145 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002146 final boolean visible = (msg.arg1 != 0);
2147 final NetworkAgentInfo nai;
2148 synchronized (mNetworkForNetId) {
2149 nai = mNetworkForNetId.get(netId);
2150 }
2151 // If captive portal status has changed, update capabilities.
2152 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2153 nai.lastCaptivePortalDetected = visible;
2154 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002155 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002156 }
2157 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002158 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002159 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002160 if (nai == null) {
2161 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2162 break;
2163 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002164 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002165 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2166 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002167 }
Paul Jensen869868be2014-05-15 10:33:05 -04002168 break;
2169 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002170 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002171 return true;
2172 }
2173
2174 @Override
2175 public void handleMessage(Message msg) {
2176 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2177 maybeHandleNetworkAgentMessage(msg);
2178 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002179 }
2180 }
2181
Paul Jensen85cf78e2015-06-25 13:25:07 -04002182 private void linger(NetworkAgentInfo nai) {
2183 nai.lingering = true;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002184 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002185 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2186 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2187 }
2188
Paul Jensen0cc17322014-11-25 15:26:53 -05002189 // Cancel any lingering so the linger timeout doesn't teardown a network.
2190 // This should be called when a network begins satisfying a NetworkRequest.
2191 // Note: depending on what state the NetworkMonitor is in (e.g.,
2192 // if it's awaiting captive portal login, or if validation failed), this
2193 // may trigger a re-evaluation of the network.
2194 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002195 nai.networkLingered.clear();
2196 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002197 nai.lingering = false;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002198 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002199 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002200 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2201 }
2202
Robert Greenwalt7b816022014-04-18 15:25:25 -07002203 private void handleAsyncChannelHalfConnect(Message msg) {
2204 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002205 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002206 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2207 if (VDBG) log("NetworkFactory connected");
2208 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002209 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002210 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002211 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002212 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002213 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002214 }
2215 } else {
2216 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002217 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002218 }
2219 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2220 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2221 if (VDBG) log("NetworkAgent connected");
2222 // A network agent has requested a connection. Establish the connection.
2223 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2224 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2225 } else {
2226 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002227 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002228 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002229 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002230 synchronized (mNetworkForNetId) {
2231 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002232 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002233 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002234 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002235 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002236 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002237 }
2238 }
2239 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002240
Robert Greenwalt7b816022014-04-18 15:25:25 -07002241 private void handleAsyncChannelDisconnected(Message msg) {
2242 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2243 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002244 if (DBG) {
2245 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2246 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002247 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002248 // TODO - if we move the logic to the network agent (have them disconnect
2249 // because they lost all their requests or because their score isn't good)
2250 // then they would disconnect organically, report their new state and then
2251 // disconnect the channel.
2252 if (nai.networkInfo.isConnected()) {
2253 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2254 null, null);
2255 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002256 final boolean wasDefault = isDefaultNetwork(nai);
2257 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002258 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002259 // Log default network disconnection before required book-keeping.
2260 // Let rematchAllNetworksAndRequests() below record a new default network event
2261 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2262 // whose timestamps tell how long it takes to recover a default network.
2263 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002264 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002265 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002266 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2267 // by other networks that are already connected. Perhaps that can be done by
2268 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2269 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002270 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002271 mKeepaliveTracker.handleStopAllKeepalives(nai,
2272 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002273 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002274 mNetworkAgentInfos.remove(msg.replyTo);
2275 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002276 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002277 // Remove the NetworkAgent, but don't mark the netId as
2278 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002279 mNetworkForNetId.remove(nai.network.netId);
2280 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002281 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002282 for (int i = 0; i < nai.networkRequests.size(); i++) {
2283 NetworkRequest request = nai.networkRequests.valueAt(i);
2284 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2285 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2286 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002287 sendUpdatedScoreToFactories(request, 0);
2288 }
2289 }
2290 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2291 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002292 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002293 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002294 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002295 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002296 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002297 if (nai.created) {
2298 // Tell netd to clean up the configuration for this network
2299 // (routing rules, DNS, etc).
2300 // This may be slow as it requires a lot of netd shelling out to ip and
2301 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2302 // after we've rematched networks with requests which should make a potential
2303 // fallback network the default or requested a new network from the
2304 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2305 // long time.
2306 try {
2307 mNetd.removeNetwork(nai.network.netId);
2308 } catch (Exception e) {
2309 loge("Exception removing network: " + e);
2310 }
2311 }
2312 synchronized (mNetworkForNetId) {
2313 mNetIdInUse.delete(nai.network.netId);
2314 }
2315 } else {
2316 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2317 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002318 }
2319 }
2320
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002321 // If this method proves to be too slow then we can maintain a separate
2322 // pendingIntent => NetworkRequestInfo map.
2323 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2324 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2325 Intent intent = pendingIntent.getIntent();
2326 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2327 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2328 if (existingPendingIntent != null &&
2329 existingPendingIntent.getIntent().filterEquals(intent)) {
2330 return entry.getValue();
2331 }
2332 }
2333 return null;
2334 }
2335
2336 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2337 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2338
2339 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2340 if (existingRequest != null) { // remove the existing request.
2341 if (DBG) log("Replacing " + existingRequest.request + " with "
2342 + nri.request + " because their intents matched.");
2343 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2344 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002345 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002346 }
2347
Erik Klineda4bfa82015-04-30 12:58:40 +09002348 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002349 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002350 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002351 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002352 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002353 if (nri.request.networkCapabilities.hasSignalStrength() &&
2354 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2355 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002356 }
2357 }
2358 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002359 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002360 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002361 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002362 }
2363 }
2364
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002365 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2366 int callingUid) {
2367 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2368 if (nri != null) {
2369 handleReleaseNetworkRequest(nri.request, callingUid);
2370 }
2371 }
2372
Paul Jensen99364842014-12-09 11:43:45 -05002373 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002374 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2375 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002376 private boolean unneeded(NetworkAgentInfo nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002377 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002378 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2379 // If this Network is already the highest scoring Network for a request, or if
2380 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002381 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002382 (nai.networkRequests.get(nri.request.requestId) != null ||
2383 // Note that this catches two important cases:
2384 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2385 // is currently satisfying the request. This is desirable when
2386 // cellular ends up validating but WiFi does not.
2387 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002388 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002389 // WiFi ends up validating and out scoring cellular.
2390 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2391 nai.getCurrentScoreAsValidated())) {
2392 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002393 }
2394 }
Paul Jensene0988542015-06-25 15:30:08 -04002395 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002396 }
2397
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002398 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2399 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002400 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002401 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002402 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2403 return;
2404 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002405 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002406 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002407 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002408 synchronized (mUidToNetworkRequestCount) {
2409 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2410 if (requests < 1) {
2411 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2412 nri.mUid);
2413 } else if (requests == 1) {
2414 mUidToNetworkRequestCount.removeAt(
2415 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2416 } else {
2417 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2418 }
2419 }
Erik Kline7523eb32015-07-09 18:24:03 +09002420 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002421 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002422 // Find all networks that are satisfying this request and remove the request
2423 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002424 // TODO - it's my understanding that for a request there is only a single
2425 // network satisfying it, so this loop is wasteful
2426 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002427 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2428 if (nai.networkRequests.get(nri.request.requestId) != null) {
2429 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002430 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002431 log(" Removing from current network " + nai.name() +
2432 ", leaving " + nai.networkRequests.size() +
2433 " requests.");
2434 }
Paul Jensen99364842014-12-09 11:43:45 -05002435 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002436 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002437 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002438 } else {
2439 // suspect there should only be one pass through here
2440 // but if any were kept do the check below
2441 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002442 }
2443 }
2444 }
2445
Robert Greenwalt51481852015-01-08 14:43:31 -08002446 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2447 if (nai != null) {
2448 mNetworkForRequestId.remove(nri.request.requestId);
2449 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002450 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002451 // that a network connected to serve it, even though the network was already
2452 // connected. Now that this request has gone away, we might have to pretend
2453 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002454 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002455 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2456 boolean doRemove = true;
2457 if (wasKept) {
2458 // check if any of the remaining requests for this network are for the
2459 // same legacy type - if so, don't remove the nai
2460 for (int i = 0; i < nai.networkRequests.size(); i++) {
2461 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2462 if (otherRequest.legacyType == nri.request.legacyType &&
2463 isRequest(otherRequest)) {
2464 if (DBG) log(" still have other legacy request - leaving");
2465 doRemove = false;
2466 }
2467 }
2468 }
2469
2470 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002471 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002472 }
2473 }
2474
Robert Greenwalta67be032014-05-16 15:49:14 -07002475 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002476 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2477 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002478 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002479 } else {
2480 // listens don't have a singular affectedNetwork. Check all networks to see
2481 // if this listen request applies and remove it.
2482 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2483 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002484 if (nri.request.networkCapabilities.hasSignalStrength() &&
2485 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2486 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002487 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002488 }
2489 }
2490 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2491 }
2492 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002493
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002494 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2495 enforceConnectivityInternalPermission();
2496 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2497 accept ? 1 : 0, always ? 1: 0, network));
2498 }
2499
2500 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2501 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2502 " accept=" + accept + " always=" + always);
2503
2504 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2505 if (nai == null) {
2506 // Nothing to do.
2507 return;
2508 }
2509
2510 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002511 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002512 return;
2513 }
2514
2515 if (!nai.networkMisc.explicitlySelected) {
2516 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2517 }
2518
2519 if (accept != nai.networkMisc.acceptUnvalidated) {
2520 int oldScore = nai.getCurrentScore();
2521 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002522 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002523 sendUpdatedScoreToFactories(nai);
2524 }
2525
2526 if (always) {
2527 nai.asyncChannel.sendMessage(
2528 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2529 }
2530
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002531 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002532 // Tell the NetworkAgent to not automatically reconnect to the network.
2533 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2534 // Teardown the nework.
2535 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002536 }
2537
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002538 }
2539
2540 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002541 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002542 mHandler.sendMessageDelayed(
2543 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2544 PROMPT_UNVALIDATED_DELAY_MS);
2545 }
2546
2547 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002548 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002549 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2550
2551 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2552 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002553 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002554 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002555 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2556 return;
2557 }
2558
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002559 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002560 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002561 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2562 intent.setClassName("com.android.settings",
2563 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002564
2565 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2566 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2567 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002568 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002569 }
2570
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002571 private class InternalHandler extends Handler {
2572 public InternalHandler(Looper looper) {
2573 super(looper);
2574 }
2575
2576 @Override
2577 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002578 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002579 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002580 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002581 String causedBy = null;
2582 synchronized (ConnectivityService.this) {
2583 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2584 mNetTransitionWakeLock.isHeld()) {
2585 mNetTransitionWakeLock.release();
2586 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002587 } else {
2588 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002589 }
2590 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002591 if (VDBG) {
2592 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2593 log("Failed to find a new network - expiring NetTransition Wakelock");
2594 } else {
2595 log("NetTransition Wakelock (" +
2596 (causedBy == null ? "unknown" : causedBy) +
2597 " cleared because we found a replacement network");
2598 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002599 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002600 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002601 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002602 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002603 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002604 break;
2605 }
Jason Monkdecd2952013-10-10 14:02:51 -04002606 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002607 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002608 break;
2609 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002610 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002611 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2612 break;
2613 }
2614 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2615 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002616 break;
2617 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002618 case EVENT_REGISTER_NETWORK_AGENT: {
2619 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2620 break;
2621 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002622 case EVENT_REGISTER_NETWORK_REQUEST:
2623 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002624 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002625 break;
2626 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002627 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2628 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002629 handleRegisterNetworkRequestWithIntent(msg);
2630 break;
2631 }
2632 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2633 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2634 break;
2635 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002636 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002637 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002638 break;
2639 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002640 case EVENT_SET_ACCEPT_UNVALIDATED: {
2641 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2642 break;
2643 }
2644 case EVENT_PROMPT_UNVALIDATED: {
2645 handlePromptUnvalidated((Network) msg.obj);
2646 break;
2647 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002648 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2649 handleMobileDataAlwaysOn();
2650 break;
2651 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002652 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2653 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2654 mKeepaliveTracker.handleStartKeepalive(msg);
2655 break;
2656 }
2657 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2658 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2659 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2660 int slot = msg.arg1;
2661 int reason = msg.arg2;
2662 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2663 break;
2664 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002665 case EVENT_SYSTEM_READY: {
2666 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2667 nai.networkMonitor.systemReady = true;
2668 }
2669 break;
2670 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002671 }
2672 }
2673 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002674
2675 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002676 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002677 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002678 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002679 final int status = mTethering.tether(iface);
2680 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2681 try {
2682 mPolicyManager.onTetheringChanged(iface, true);
2683 } catch (RemoteException e) {
2684 }
2685 }
2686 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002687 } else {
2688 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2689 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002690 }
2691
2692 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002693 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002694 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002695
2696 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002697 final int status = mTethering.untether(iface);
2698 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2699 try {
2700 mPolicyManager.onTetheringChanged(iface, false);
2701 } catch (RemoteException e) {
2702 }
2703 }
2704 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002705 } else {
2706 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2707 }
2708 }
2709
2710 // javadoc from interface
2711 public int getLastTetherError(String iface) {
2712 enforceTetherAccessPermission();
2713
2714 if (isTetheringSupported()) {
2715 return mTethering.getLastTetherError(iface);
2716 } else {
2717 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2718 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002719 }
2720
2721 // TODO - proper iface API for selection by property, inspection, etc
2722 public String[] getTetherableUsbRegexs() {
2723 enforceTetherAccessPermission();
2724 if (isTetheringSupported()) {
2725 return mTethering.getTetherableUsbRegexs();
2726 } else {
2727 return new String[0];
2728 }
2729 }
2730
2731 public String[] getTetherableWifiRegexs() {
2732 enforceTetherAccessPermission();
2733 if (isTetheringSupported()) {
2734 return mTethering.getTetherableWifiRegexs();
2735 } else {
2736 return new String[0];
2737 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002738 }
2739
Danica Chang6fdd0c62010-08-11 14:54:43 -07002740 public String[] getTetherableBluetoothRegexs() {
2741 enforceTetherAccessPermission();
2742 if (isTetheringSupported()) {
2743 return mTethering.getTetherableBluetoothRegexs();
2744 } else {
2745 return new String[0];
2746 }
2747 }
2748
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002749 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002750 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002751 if (isTetheringSupported()) {
2752 return mTethering.setUsbTethering(enable);
2753 } else {
2754 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2755 }
2756 }
2757
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002758 // TODO - move iface listing, queries, etc to new module
2759 // javadoc from interface
2760 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002761 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002762 return mTethering.getTetherableIfaces();
2763 }
2764
2765 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002766 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002767 return mTethering.getTetheredIfaces();
2768 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002769
Robert Greenwalt5a735062010-03-02 17:25:02 -08002770 public String[] getTetheringErroredIfaces() {
2771 enforceTetherAccessPermission();
2772 return mTethering.getErroredIfaces();
2773 }
2774
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002775 public String[] getTetheredDhcpRanges() {
2776 enforceConnectivityInternalPermission();
2777 return mTethering.getTetheredDhcpRanges();
2778 }
2779
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002780 // if ro.tether.denied = true we default to no tethering
2781 // gservices could set the secure setting to 1 though to enable it on a build where it
2782 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002783 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002784 public boolean isTetheringSupported() {
2785 enforceTetherAccessPermission();
2786 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002787 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002788 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2789 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002790 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2791 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002792 mTethering.getTetherableWifiRegexs().length != 0 ||
2793 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2794 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002795 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002796
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002797 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002798 public void startTethering(int type, ResultReceiver receiver,
2799 boolean showProvisioningUi) {
2800 ConnectivityManager.enforceTetherChangePermission(mContext);
2801 if (!isTetheringSupported()) {
2802 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2803 return;
2804 }
2805 mTethering.startTethering(type, receiver, showProvisioningUi);
2806 }
2807
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002808 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002809 public void stopTethering(int type) {
2810 ConnectivityManager.enforceTetherChangePermission(mContext);
2811 mTethering.stopTethering(type);
2812 }
2813
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002814 // Called when we lose the default network and have no replacement yet.
2815 // This will automatically be cleared after X seconds or a new default network
2816 // becomes CONNECTED, whichever happens first. The timer is started by the
2817 // first caller and not restarted by subsequent callers.
2818 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002819 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002820 synchronized (this) {
2821 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002822 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002823 mNetTransitionWakeLock.acquire();
2824 mNetTransitionWakeLockCausedBy = forWhom;
2825 }
2826 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002827 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002828 mNetTransitionWakeLockTimeout);
2829 return;
2830 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002831
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002832 // 100 percent is full good, 0 is full bad.
2833 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002834 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002835 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002836 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002837 }
2838
Paul Jensenbfd17b72015-04-07 12:43:13 -04002839 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002840 enforceAccessPermission();
2841 enforceInternetPermission();
2842
Paul Jensenbfd17b72015-04-07 12:43:13 -04002843 NetworkAgentInfo nai;
2844 if (network == null) {
2845 nai = getDefaultNetwork();
2846 } else {
2847 nai = getNetworkAgentInfoForNetwork(network);
2848 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002849 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2850 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2851 return;
2852 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002853 // Revalidate if the app report does not match our current validated state.
2854 if (hasConnectivity == nai.lastValidated) return;
2855 final int uid = Binder.getCallingUid();
2856 if (DBG) {
2857 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2858 ") by " + uid);
2859 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002860 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002861 // Validating a network that has not yet connected could result in a call to
2862 // rematchNetworkAndRequests() which is not meant to work on such networks.
2863 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04002864
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002865 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002866
2867 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2868 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002869 }
2870
Paul Jensencee9b512015-05-06 07:32:40 -04002871 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002872 // this information is already available as a world read/writable jvm property
2873 // so this API change wouldn't have a benifit. It also breaks the passing
2874 // of proxy info to all the JVMs.
2875 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002876 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002877 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002878 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2879 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002880 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002881 }
2882
Paul Jensencee9b512015-05-06 07:32:40 -04002883 public ProxyInfo getProxyForNetwork(Network network) {
2884 if (network == null) return getDefaultProxy();
2885 final ProxyInfo globalProxy = getGlobalProxy();
2886 if (globalProxy != null) return globalProxy;
2887 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2888 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2889 // caller may not have.
2890 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2891 if (nai == null) return null;
2892 synchronized (nai) {
2893 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2894 if (proxyInfo == null) return null;
2895 return new ProxyInfo(proxyInfo);
2896 }
2897 }
2898
Paul Jensene0bef712014-12-10 15:12:18 -05002899 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2900 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2901 // proxy is null then there is no proxy in place).
2902 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2903 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2904 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2905 proxy = null;
2906 }
2907 return proxy;
2908 }
2909
2910 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2911 // better for determining if a new proxy broadcast is necessary:
2912 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2913 // avoid unnecessary broadcasts.
2914 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2915 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2916 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2917 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2918 // all set.
2919 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2920 a = canonicalizeProxyInfo(a);
2921 b = canonicalizeProxyInfo(b);
2922 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2923 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2924 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2925 }
2926
Jason Monk207900c2014-04-25 15:00:09 -04002927 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002928 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002929
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002930 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002931 if (proxyProperties == mGlobalProxy) return;
2932 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2933 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2934
2935 String host = "";
2936 int port = 0;
2937 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002938 String pacFileUrl = "";
2939 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002940 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002941 if (!proxyProperties.isValid()) {
2942 if (DBG)
2943 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2944 return;
2945 }
Jason Monk207900c2014-04-25 15:00:09 -04002946 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002947 host = mGlobalProxy.getHost();
2948 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002949 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002950 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002951 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002952 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002953 } else {
2954 mGlobalProxy = null;
2955 }
2956 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002957 final long token = Binder.clearCallingIdentity();
2958 try {
2959 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2960 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2961 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2962 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002963 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002964 } finally {
2965 Binder.restoreCallingIdentity(token);
2966 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002967
Jason Monkcf0f97a2014-10-02 15:39:38 -04002968 if (mGlobalProxy == null) {
2969 proxyProperties = mDefaultProxy;
2970 }
2971 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002972 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002973 }
2974
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002975 private void loadGlobalProxy() {
2976 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002977 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2978 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2979 String exclList = Settings.Global.getString(res,
2980 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002981 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2982 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002983 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002984 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002985 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002986 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002987 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002988 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002989 if (!proxyProperties.isValid()) {
2990 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2991 return;
2992 }
2993
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002994 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002995 mGlobalProxy = proxyProperties;
2996 }
2997 }
2998 }
2999
Jason Monk207900c2014-04-25 15:00:09 -04003000 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003001 // this information is already available as a world read/writable jvm property
3002 // so this API change wouldn't have a benifit. It also breaks the passing
3003 // of proxy info to all the JVMs.
3004 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003005 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003006 return mGlobalProxy;
3007 }
3008 }
3009
Jason Monk207900c2014-04-25 15:00:09 -04003010 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003011 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003012 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003013 proxy = null;
3014 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003015 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003016 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003017 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003018 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003019 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3020 return;
3021 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003022
3023 // This call could be coming from the PacManager, containing the port of the local
3024 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3025 // global (to get the correct local port), and send a broadcast.
3026 // TODO: Switch PacManager to have its own message to send back rather than
3027 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003028 if ((mGlobalProxy != null) && (proxy != null)
3029 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003030 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3031 mGlobalProxy = proxy;
3032 sendProxyBroadcast(mGlobalProxy);
3033 return;
3034 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003035 mDefaultProxy = proxy;
3036
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003037 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003038 if (!mDefaultProxyDisabled) {
3039 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003040 }
3041 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003042 }
3043
Paul Jensene0bef712014-12-10 15:12:18 -05003044 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3045 // This method gets called when any network changes proxy, but the broadcast only ever contains
3046 // the default proxy (even if it hasn't changed).
3047 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3048 // world where an app might be bound to a non-default network.
3049 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3050 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3051 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3052
3053 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3054 sendProxyBroadcast(getDefaultProxy());
3055 }
3056 }
3057
Robert Greenwalt434203a2010-10-11 16:00:27 -07003058 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003059 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3060 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003061 if (!TextUtils.isEmpty(proxy)) {
3062 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003063 if (data.length == 0) {
3064 return;
3065 }
3066
Robert Greenwalt434203a2010-10-11 16:00:27 -07003067 String proxyHost = data[0];
3068 int proxyPort = 8080;
3069 if (data.length > 1) {
3070 try {
3071 proxyPort = Integer.parseInt(data[1]);
3072 } catch (NumberFormatException e) {
3073 return;
3074 }
3075 }
Jason Monk207900c2014-04-25 15:00:09 -04003076 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003077 setGlobalProxy(p);
3078 }
3079 }
3080
Jason Monk207900c2014-04-25 15:00:09 -04003081 private void sendProxyBroadcast(ProxyInfo proxy) {
3082 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003083 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003084 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003085 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003086 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3087 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003088 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003089 final long ident = Binder.clearCallingIdentity();
3090 try {
3091 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3092 } finally {
3093 Binder.restoreCallingIdentity(ident);
3094 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003095 }
3096
3097 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003098 final private HashMap<Uri, Integer> mUriEventMap;
3099 final private Context mContext;
3100 final private Handler mHandler;
3101
3102 SettingsObserver(Context context, Handler handler) {
3103 super(null);
3104 mUriEventMap = new HashMap<Uri, Integer>();
3105 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003106 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003107 }
3108
Erik Klineda4bfa82015-04-30 12:58:40 +09003109 void observe(Uri uri, int what) {
3110 mUriEventMap.put(uri, what);
3111 final ContentResolver resolver = mContext.getContentResolver();
3112 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003113 }
3114
3115 @Override
3116 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003117 Slog.wtf(TAG, "Should never be reached.");
3118 }
3119
3120 @Override
3121 public void onChange(boolean selfChange, Uri uri) {
3122 final Integer what = mUriEventMap.get(uri);
3123 if (what != null) {
3124 mHandler.obtainMessage(what.intValue()).sendToTarget();
3125 } else {
3126 loge("No matching event to send for URI=" + uri);
3127 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003128 }
3129 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003130
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003131 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003132 Slog.d(TAG, s);
3133 }
3134
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003135 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003136 Slog.e(TAG, s);
3137 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003138
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003139 private static <T> T checkNotNull(T value, String message) {
3140 if (value == null) {
3141 throw new NullPointerException(message);
3142 }
3143 return value;
3144 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003145
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003146 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003147 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003148 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3149 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3150 *
3151 * @param oldPackage Package name of the application which currently controls VPN, which will
3152 * be replaced. If there is no such application, this should should either be
3153 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3154 * @param newPackage Package name of the application which should gain control of VPN, or
3155 * {@code null} to disable.
3156 * @param userId User for whom to prepare the new VPN.
3157 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003158 * @hide
3159 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003160 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003161 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3162 int userId) {
3163 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003164 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003165
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003166 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003167 Vpn vpn = mVpns.get(userId);
3168 if (vpn != null) {
3169 return vpn.prepare(oldPackage, newPackage);
3170 } else {
3171 return false;
3172 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003173 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003174 }
3175
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003176 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003177 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3178 * This method is used by system-privileged apps.
3179 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3180 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3181 *
3182 * @param packageName The package for which authorization state should change.
3183 * @param userId User for whom {@code packageName} is installed.
3184 * @param authorized {@code true} if this app should be able to start a VPN connection without
3185 * explicit user approval, {@code false} if not.
3186 *
Jeff Davidson05542602014-08-11 14:07:27 -07003187 * @hide
3188 */
3189 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003190 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3191 enforceCrossUserPermission(userId);
3192
Jeff Davidson05542602014-08-11 14:07:27 -07003193 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003194 Vpn vpn = mVpns.get(userId);
3195 if (vpn != null) {
3196 vpn.setPackageAuthorization(packageName, authorized);
3197 }
Jeff Davidson05542602014-08-11 14:07:27 -07003198 }
3199 }
3200
3201 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003202 * Configure a TUN interface and return its file descriptor. Parameters
3203 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003204 * and not available in ConnectivityManager. Permissions are checked in
3205 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003206 * @hide
3207 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003208 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003209 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003210 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003211 int user = UserHandle.getUserId(Binder.getCallingUid());
3212 synchronized(mVpns) {
3213 return mVpns.get(user).establish(config);
3214 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003215 }
3216
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003217 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003218 * Start legacy VPN, controlling native daemons as needed. Creates a
3219 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003220 */
3221 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003222 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003223 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003224 final LinkProperties egress = getActiveLinkProperties();
3225 if (egress == null) {
3226 throw new IllegalStateException("Missing active network connection");
3227 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003228 int user = UserHandle.getUserId(Binder.getCallingUid());
3229 synchronized(mVpns) {
3230 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3231 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003232 }
3233
3234 /**
3235 * Return the information of the ongoing legacy VPN. This method is used
3236 * by VpnSettings and not available in ConnectivityManager. Permissions
3237 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003238 */
3239 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003240 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3241 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003242
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003243 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003244 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003245 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003246 }
3247
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003248 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003249 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3250 * and not available in ConnectivityManager.
3251 */
3252 @Override
3253 public VpnInfo[] getAllVpnInfo() {
3254 enforceConnectivityInternalPermission();
3255 if (mLockdownEnabled) {
3256 return new VpnInfo[0];
3257 }
3258
3259 synchronized(mVpns) {
3260 List<VpnInfo> infoList = new ArrayList<>();
3261 for (int i = 0; i < mVpns.size(); i++) {
3262 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3263 if (info != null) {
3264 infoList.add(info);
3265 }
3266 }
3267 return infoList.toArray(new VpnInfo[infoList.size()]);
3268 }
3269 }
3270
3271 /**
3272 * @return VPN information for accounting, or null if we can't retrieve all required
3273 * information, e.g primary underlying iface.
3274 */
3275 @Nullable
3276 private VpnInfo createVpnInfo(Vpn vpn) {
3277 VpnInfo info = vpn.getVpnInfo();
3278 if (info == null) {
3279 return null;
3280 }
3281 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3282 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3283 // the underlyingNetworks list.
3284 if (underlyingNetworks == null) {
3285 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3286 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3287 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3288 }
3289 } else if (underlyingNetworks.length > 0) {
3290 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3291 if (linkProperties != null) {
3292 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3293 }
3294 }
3295 return info.primaryUnderlyingIface == null ? null : info;
3296 }
3297
3298 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003299 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3300 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003301 * Permissions are checked in Vpn class.
3302 * @hide
3303 */
3304 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003305 public VpnConfig getVpnConfig(int userId) {
3306 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003307 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003308 Vpn vpn = mVpns.get(userId);
3309 if (vpn != null) {
3310 return vpn.getVpnConfig();
3311 } else {
3312 return null;
3313 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003314 }
3315 }
3316
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003317 @Override
3318 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003319 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3320 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3321 return false;
3322 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003323
3324 // Tear down existing lockdown if profile was removed
3325 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3326 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003327 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3328 final VpnProfile profile = VpnProfile.decode(
3329 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003330 if (profile == null) {
3331 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3332 setLockdownTracker(null);
3333 return true;
3334 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003335 int user = UserHandle.getUserId(Binder.getCallingUid());
3336 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003337 Vpn vpn = mVpns.get(user);
3338 if (vpn == null) {
3339 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3340 return false;
3341 }
3342 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003343 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003344 } else {
3345 setLockdownTracker(null);
3346 }
3347
3348 return true;
3349 }
3350
3351 /**
3352 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3353 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3354 */
3355 private void setLockdownTracker(LockdownVpnTracker tracker) {
3356 // Shutdown any existing tracker
3357 final LockdownVpnTracker existing = mLockdownTracker;
3358 mLockdownTracker = null;
3359 if (existing != null) {
3360 existing.shutdown();
3361 }
3362
3363 try {
3364 if (tracker != null) {
3365 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003366 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003367 mLockdownTracker = tracker;
3368 mLockdownTracker.init();
3369 } else {
3370 mNetd.setFirewallEnabled(false);
3371 }
3372 } catch (RemoteException e) {
3373 // ignored; NMS lives inside system_server
3374 }
3375 }
3376
3377 private void throwIfLockdownEnabled() {
3378 if (mLockdownEnabled) {
3379 throw new IllegalStateException("Unavailable in lockdown mode");
3380 }
3381 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003382
Robin Lee244ce8e2016-01-05 18:03:46 +00003383 /**
Robin Lee17e61832016-05-09 13:46:28 +01003384 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3385 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003386 *
Robin Lee17e61832016-05-09 13:46:28 +01003387 * @return {@code true} if the service was started, the service was already connected, or there
3388 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003389 */
Robin Lee17e61832016-05-09 13:46:28 +01003390 private boolean startAlwaysOnVpn(int userId) {
3391 final String alwaysOnPackage;
3392 synchronized (mVpns) {
3393 Vpn vpn = mVpns.get(userId);
3394 if (vpn == null) {
3395 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3396 // exists already.
3397 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3398 return false;
3399 }
3400 alwaysOnPackage = vpn.getAlwaysOnPackage();
3401 // Skip if there is no service to start.
3402 if (alwaysOnPackage == null) {
3403 return true;
3404 }
3405 // Skip if the service is already established. This isn't bulletproof: it's not bound
3406 // until after establish(), so if it's mid-setup onStartCommand will be sent twice,
3407 // which may restart the connection.
3408 if (vpn.getNetworkInfo().isConnected()) {
3409 return true;
3410 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003411 }
3412
Robin Lee17e61832016-05-09 13:46:28 +01003413 // Start the VPN service declared in the app's manifest.
Robin Lee244ce8e2016-01-05 18:03:46 +00003414 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
Robin Lee17e61832016-05-09 13:46:28 +01003415 serviceIntent.setPackage(alwaysOnPackage);
Robin Lee244ce8e2016-01-05 18:03:46 +00003416 try {
Robin Lee17e61832016-05-09 13:46:28 +01003417 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(userId)) != null;
Robin Lee244ce8e2016-01-05 18:03:46 +00003418 } catch (RuntimeException e) {
Robin Lee17e61832016-05-09 13:46:28 +01003419 Slog.w(TAG, "VpnService " + serviceIntent + " failed to start", e);
Robin Lee244ce8e2016-01-05 18:03:46 +00003420 return false;
3421 }
3422 }
3423
3424 @Override
Robin Leedc679712016-05-03 13:23:03 +01003425 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003426 enforceConnectivityInternalPermission();
3427 enforceCrossUserPermission(userId);
3428
3429 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3430 if (LockdownVpnTracker.isEnabled()) {
3431 return false;
3432 }
3433
Robin Lee244ce8e2016-01-05 18:03:46 +00003434 synchronized (mVpns) {
3435 Vpn vpn = mVpns.get(userId);
3436 if (vpn == null) {
3437 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3438 return false;
3439 }
Robin Lee17e61832016-05-09 13:46:28 +01003440 // If the current VPN package is the same as the new one, this is a no-op
3441 if (TextUtils.equals(packageName, vpn.getAlwaysOnPackage())) {
3442 return true;
3443 }
3444 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003445 return false;
3446 }
Robin Lee17e61832016-05-09 13:46:28 +01003447 if (!startAlwaysOnVpn(userId)) {
3448 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003449 return false;
3450 }
Robin Lee17e61832016-05-09 13:46:28 +01003451
3452 // Save the configuration
3453 final long token = Binder.clearCallingIdentity();
3454 try {
3455 final ContentResolver cr = mContext.getContentResolver();
3456 Settings.Secure.putStringForUser(cr, Settings.Secure.ALWAYS_ON_VPN_APP,
3457 packageName, userId);
3458 Settings.Secure.putIntForUser(cr, Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN,
3459 (lockdown ? 1 : 0), userId);
3460 } finally {
3461 Binder.restoreCallingIdentity(token);
3462 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003463 }
3464 return true;
3465 }
3466
3467 @Override
3468 public String getAlwaysOnVpnPackage(int userId) {
3469 enforceConnectivityInternalPermission();
3470 enforceCrossUserPermission(userId);
3471
3472 synchronized (mVpns) {
3473 Vpn vpn = mVpns.get(userId);
3474 if (vpn == null) {
3475 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3476 return null;
3477 }
3478 return vpn.getAlwaysOnPackage();
3479 }
3480 }
3481
Wink Savilleab9321d2013-06-29 21:10:57 -07003482 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003483 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003484 // TODO: Remove? Any reason to trigger a provisioning check?
3485 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003486 }
3487
3488 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003489 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003490
Paul Jensen89e0f092014-09-15 15:59:36 -04003491 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003492 Intent intent = new Intent(action);
3493 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003494 // Concatenate the range of types onto the range of NetIDs.
3495 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003496 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003497 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003498 }
3499
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003500 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003501 * Show or hide network provisioning notifications.
3502 *
3503 * We use notifications for two purposes: to notify that a network requires sign in
3504 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3505 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3506 * particular network we can display the notification type that was most recently requested.
3507 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3508 * might first display NO_INTERNET, and then when the captive portal check completes, display
3509 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003510 *
3511 * @param id an identifier that uniquely identifies this notification. This must match
3512 * between show and hide calls. We use the NetID value but for legacy callers
3513 * we concatenate the range of types with the range of NetIDs.
3514 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003515 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003516 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3517 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003518 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003519 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3520 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003521 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003522 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003523
3524 Resources r = Resources.getSystem();
3525 NotificationManager notificationManager = (NotificationManager) mContext
3526 .getSystemService(Context.NOTIFICATION_SERVICE);
3527
3528 if (visible) {
3529 CharSequence title;
3530 CharSequence details;
3531 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003532 if (notifyType == NotificationType.NO_INTERNET &&
3533 networkType == ConnectivityManager.TYPE_WIFI) {
3534 title = r.getString(R.string.wifi_no_internet, 0);
3535 details = r.getString(R.string.wifi_no_internet_detailed);
3536 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3537 } else if (notifyType == NotificationType.SIGN_IN) {
3538 switch (networkType) {
3539 case ConnectivityManager.TYPE_WIFI:
3540 title = r.getString(R.string.wifi_available_sign_in, 0);
3541 details = r.getString(R.string.network_available_sign_in_detailed,
3542 extraInfo);
3543 icon = R.drawable.stat_notify_wifi_in_range;
3544 break;
3545 case ConnectivityManager.TYPE_MOBILE:
3546 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3547 title = r.getString(R.string.network_available_sign_in, 0);
3548 // TODO: Change this to pull from NetworkInfo once a printable
3549 // name has been added to it
3550 details = mTelephonyManager.getNetworkOperatorName();
3551 icon = R.drawable.stat_notify_rssi_in_range;
3552 break;
3553 default:
3554 title = r.getString(R.string.network_available_sign_in, 0);
3555 details = r.getString(R.string.network_available_sign_in_detailed,
3556 extraInfo);
3557 icon = R.drawable.stat_notify_rssi_in_range;
3558 break;
3559 }
3560 } else {
3561 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3562 + getNetworkTypeName(networkType));
3563 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003564 }
3565
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003566 Notification notification = new Notification.Builder(mContext)
3567 .setWhen(0)
3568 .setSmallIcon(icon)
3569 .setAutoCancel(true)
3570 .setTicker(title)
3571 .setColor(mContext.getColor(
3572 com.android.internal.R.color.system_notification_accent_color))
3573 .setContentTitle(title)
3574 .setContentText(details)
3575 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003576 .setLocalOnly(true)
3577 .setPriority(highPriority ?
3578 Notification.PRIORITY_HIGH :
3579 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003580 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003581 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003582 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003583
Wink Saville948282b2013-08-29 08:55:16 -07003584 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003585 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003586 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003587 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003588 npe.printStackTrace();
3589 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003590 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003591 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003592 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003593 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003594 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003595 npe.printStackTrace();
3596 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003597 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003598 }
3599
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003600 /** Location to an updatable file listing carrier provisioning urls.
3601 * An example:
3602 *
3603 * <?xml version="1.0" encoding="utf-8"?>
3604 * <provisioningUrls>
3605 * <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 -07003606 * </provisioningUrls>
3607 */
3608 private static final String PROVISIONING_URL_PATH =
3609 "/data/misc/radio/provisioning_urls.xml";
3610 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003611
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003612 /** XML tag for root element. */
3613 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3614 /** XML tag for individual url */
3615 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003616 /** XML attribute for mcc */
3617 private static final String ATTR_MCC = "mcc";
3618 /** XML attribute for mnc */
3619 private static final String ATTR_MNC = "mnc";
3620
Paul Jensen434dde82015-06-11 09:43:30 -04003621 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003622 FileReader fileReader = null;
3623 XmlPullParser parser = null;
3624 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003625
3626 try {
3627 fileReader = new FileReader(mProvisioningUrlFile);
3628 parser = Xml.newPullParser();
3629 parser.setInput(fileReader);
3630 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3631
3632 while (true) {
3633 XmlUtils.nextElement(parser);
3634
3635 String element = parser.getName();
3636 if (element == null) break;
3637
Paul Jensen434dde82015-06-11 09:43:30 -04003638 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003639 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3640 try {
3641 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3642 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3643 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3644 parser.next();
3645 if (parser.getEventType() == XmlPullParser.TEXT) {
3646 return parser.getText();
3647 }
3648 }
3649 }
3650 } catch (NumberFormatException e) {
3651 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3652 }
3653 }
3654 }
3655 return null;
3656 } catch (FileNotFoundException e) {
3657 loge("Carrier Provisioning Urls file not found");
3658 } catch (XmlPullParserException e) {
3659 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3660 } catch (IOException e) {
3661 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3662 } finally {
3663 if (fileReader != null) {
3664 try {
3665 fileReader.close();
3666 } catch (IOException e) {}
3667 }
3668 }
3669 return null;
3670 }
3671
Wink Saville42d4f082013-07-20 20:31:59 -07003672 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003673 public String getMobileProvisioningUrl() {
3674 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003675 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003676 if (TextUtils.isEmpty(url)) {
3677 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003678 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003679 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003680 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003681 }
Wink Saville8cf35602013-07-10 23:00:07 -07003682 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003683 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003684 String phoneNumber = mTelephonyManager.getLine1Number();
3685 if (TextUtils.isEmpty(phoneNumber)) {
3686 phoneNumber = "0000000000";
3687 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003688 url = String.format(url,
3689 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3690 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003691 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003692 }
3693
Wink Savilleab9321d2013-06-29 21:10:57 -07003694 return url;
3695 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003696
Wink Saville948282b2013-08-29 08:55:16 -07003697 @Override
3698 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003699 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003700 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003701 final long ident = Binder.clearCallingIdentity();
3702 try {
3703 setProvNotificationVisible(visible, networkType, action);
3704 } finally {
3705 Binder.restoreCallingIdentity(ident);
3706 }
Wink Saville948282b2013-08-29 08:55:16 -07003707 }
Wink Saville7788c612013-08-29 14:57:08 -07003708
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003709 @Override
3710 public void setAirplaneMode(boolean enable) {
3711 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003712 final long ident = Binder.clearCallingIdentity();
3713 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003714 final ContentResolver cr = mContext.getContentResolver();
3715 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3716 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3717 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003718 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003719 } finally {
3720 Binder.restoreCallingIdentity(ident);
3721 }
3722 }
3723
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003724 private void onUserStart(int userId) {
3725 synchronized(mVpns) {
3726 Vpn userVpn = mVpns.get(userId);
3727 if (userVpn != null) {
3728 loge("Starting user already has a VPN");
3729 return;
3730 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003731 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003732 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003733
3734 final ContentResolver cr = mContext.getContentResolver();
3735 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3736 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3737 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3738 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3739 if (alwaysOnPackage != null) {
3740 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3741 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003742 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003743 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3744 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003745 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003746 }
3747
3748 private void onUserStop(int userId) {
3749 synchronized(mVpns) {
3750 Vpn userVpn = mVpns.get(userId);
3751 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003752 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003753 return;
3754 }
Robin Lee17e61832016-05-09 13:46:28 +01003755 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003756 mVpns.delete(userId);
3757 }
3758 }
3759
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003760 private void onUserAdded(int userId) {
3761 synchronized(mVpns) {
3762 final int vpnsSize = mVpns.size();
3763 for (int i = 0; i < vpnsSize; i++) {
3764 Vpn vpn = mVpns.valueAt(i);
3765 vpn.onUserAdded(userId);
3766 }
3767 }
3768 }
3769
3770 private void onUserRemoved(int userId) {
3771 synchronized(mVpns) {
3772 final int vpnsSize = mVpns.size();
3773 for (int i = 0; i < vpnsSize; i++) {
3774 Vpn vpn = mVpns.valueAt(i);
3775 vpn.onUserRemoved(userId);
3776 }
3777 }
3778 }
3779
Robin Lee89e7a692016-02-29 14:38:17 +00003780 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003781 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3782 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3783 updateLockdownVpn();
3784 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003785 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003786 }
3787 }
3788
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003789 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3790 @Override
3791 public void onReceive(Context context, Intent intent) {
3792 final String action = intent.getAction();
3793 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3794 if (userId == UserHandle.USER_NULL) return;
3795
Robin Lee323f29d2016-05-04 16:38:06 +01003796 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003797 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003798 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003799 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003800 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3801 onUserAdded(userId);
3802 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3803 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003804 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3805 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003806 }
3807 }
3808 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003809
Robert Greenwalta67be032014-05-16 15:49:14 -07003810 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3811 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003812 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3813 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003814
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003815 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3816 // Map from UID to number of NetworkRequests that UID has filed.
3817 @GuardedBy("mUidToNetworkRequestCount")
3818 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3819
Robert Greenwalta67be032014-05-16 15:49:14 -07003820 private static class NetworkFactoryInfo {
3821 public final String name;
3822 public final Messenger messenger;
3823 public final AsyncChannel asyncChannel;
3824
3825 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3826 this.name = name;
3827 this.messenger = messenger;
3828 this.asyncChannel = asyncChannel;
3829 }
3830 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003831
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003832 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003833 * A NetworkRequest as registered by an application can be one of three
3834 * types:
3835 *
3836 * - "listen", for which the framework will issue callbacks about any
3837 * and all networks that match the specified NetworkCapabilities,
3838 *
3839 * - "request", capable of causing a specific network to be created
3840 * first (e.g. a telephony DUN request), the framework will issue
3841 * callbacks about the single, highest scoring current network
3842 * (if any) that matches the specified NetworkCapabilities, or
3843 *
3844 * - "track the default network", a hybrid of the two designed such
3845 * that the framework will issue callbacks for the single, highest
3846 * scoring current network (if any) that matches the capabilities of
3847 * the default Internet request (mDefaultRequest), but which cannot
3848 * cause the framework to either create or retain the existence of
3849 * any specific network.
3850 *
3851 */
3852 private static enum NetworkRequestType {
3853 LISTEN,
3854 TRACK_DEFAULT,
3855 REQUEST
3856 };
3857
3858 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003859 * Tracks info about the requester.
3860 * Also used to notice when the calling process dies so we can self-expire
3861 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003862 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003863 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003864 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003865 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003866 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003867 final int mPid;
3868 final int mUid;
3869 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003870 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003871
Erik Kline371c7b72016-03-22 17:04:20 +09003872 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003873 request = r;
3874 mPendingIntent = pi;
3875 messenger = null;
3876 mBinder = null;
3877 mPid = getCallingPid();
3878 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003879 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003880 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003881 }
3882
Erik Kline371c7b72016-03-22 17:04:20 +09003883 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003884 super();
3885 messenger = m;
3886 request = r;
3887 mBinder = binder;
3888 mPid = getCallingPid();
3889 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003890 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003891 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003892 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003893
3894 try {
3895 mBinder.linkToDeath(this, 0);
3896 } catch (RemoteException e) {
3897 binderDied();
3898 }
3899 }
3900
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003901 private void enforceRequestCountLimit() {
3902 synchronized (mUidToNetworkRequestCount) {
3903 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3904 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3905 throw new IllegalArgumentException("Too many NetworkRequests filed");
3906 }
3907 mUidToNetworkRequestCount.put(mUid, networkRequests);
3908 }
3909 }
3910
Erik Kline371c7b72016-03-22 17:04:20 +09003911 private String typeString() {
3912 switch (mType) {
3913 case LISTEN: return "Listen";
3914 case REQUEST: return "Request";
3915 case TRACK_DEFAULT: return "Track default";
3916 default:
3917 return "unknown type";
3918 }
3919 }
3920
Robert Greenwalt9258c642014-03-26 16:47:06 -07003921 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003922 if (mBinder != null) {
3923 mBinder.unlinkToDeath(this, 0);
3924 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003925 }
3926
3927 public void binderDied() {
3928 log("ConnectivityService NetworkRequestInfo binderDied(" +
3929 request + ", " + mBinder + ")");
3930 releaseNetworkRequest(request);
3931 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003932
Erik Kline371c7b72016-03-22 17:04:20 +09003933 /**
3934 * Returns true iff. the contained NetworkRequest is one that:
3935 *
3936 * - should be associated with at most one satisfying network
3937 * at a time;
3938 *
3939 * - should cause a network to be kept up if it is the only network
3940 * which can satisfy the NetworkReqeust.
3941 *
3942 * For full detail of how isRequest() is used for pairing Networks with
3943 * NetworkRequests read rematchNetworkAndRequests().
3944 *
3945 * TODO: Rename to something more properly descriptive.
3946 */
3947 public boolean isRequest() {
3948 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3949 (mType == NetworkRequestType.REQUEST);
3950 }
3951
Robert Greenwalta67be032014-05-16 15:49:14 -07003952 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003953 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003954 " from uid/pid:" + mUid + "/" + mPid +
3955 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003956 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003957 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003958 }
3959
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003960 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3961 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3962 if (badCapability != null) {
3963 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003964 }
3965 }
3966
Erik Kline9d598e12015-07-13 16:37:51 +09003967 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003968 final SortedSet<Integer> thresholds = new TreeSet();
3969 synchronized (nai) {
3970 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3971 if (nri.request.networkCapabilities.hasSignalStrength() &&
3972 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3973 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3974 }
3975 }
3976 }
Erik Kline9d598e12015-07-13 16:37:51 +09003977 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003978 }
3979
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003980 private void updateSignalStrengthThresholds(
3981 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3982 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003983 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003984 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3985
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003986 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003987 String detail;
3988 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3989 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3990 } else {
3991 detail = reason;
3992 }
3993 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3994 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3995 }
3996
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003997 nai.asyncChannel.sendMessage(
3998 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003999 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004000 }
4001
Robert Greenwalt9258c642014-03-26 16:47:06 -07004002 @Override
4003 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004004 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09004005 final NetworkRequestType type = (networkCapabilities == null)
4006 ? NetworkRequestType.TRACK_DEFAULT
4007 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004008 // If the requested networkCapabilities is null, take them instead from
4009 // the default network request. This allows callers to keep track of
4010 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09004011 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004012 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4013 enforceAccessPermission();
4014 } else {
4015 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4016 enforceNetworkRequestPermissions(networkCapabilities);
4017 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004018 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004019 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004020
Robert Greenwalt6078b502014-06-11 16:05:07 -07004021 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022 throw new IllegalArgumentException("Bad timeout specified");
4023 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004024
Etan Cohenddb9ef02015-11-18 10:56:15 -08004025 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4026 .equals(networkCapabilities.getNetworkSpecifier())) {
4027 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4028 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4029 }
4030
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004031 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
4032 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09004033 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09004034 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004035
4036 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004037 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004038 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004039 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004040 }
4041 return networkRequest;
4042 }
4043
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004044 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004045 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004046 enforceConnectivityInternalPermission();
4047 } else {
4048 enforceChangePermission();
4049 }
4050 }
4051
fenglub15e72b2015-03-20 11:29:56 -07004052 @Override
fengludb571472015-04-21 17:12:05 -07004053 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004054 enforceAccessPermission();
4055 NetworkAgentInfo nai = null;
4056 if (network == null) {
4057 return false;
4058 }
4059 synchronized (mNetworkForNetId) {
4060 nai = mNetworkForNetId.get(network.netId);
4061 }
4062 if (nai != null) {
4063 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4064 return true;
4065 }
4066 return false;
4067 }
4068
4069
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004070 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
4071 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004072 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004073 final int uidRules;
4074 final int uid = Binder.getCallingUid();
4075 synchronized(mRulesLock) {
4076 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4077 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004078 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4079 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004080 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004081 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004082 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004083 }
4084 }
4085 }
4086
Robert Greenwalt9258c642014-03-26 16:47:06 -07004087 @Override
4088 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4089 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004090 checkNotNull(operation, "PendingIntent cannot be null.");
4091 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4092 enforceNetworkRequestPermissions(networkCapabilities);
4093 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004094 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004095
4096 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
4097 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004098 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004099 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09004100 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004101 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4102 nri));
4103 return networkRequest;
4104 }
4105
Jeremy Joslin79294842014-12-03 17:15:28 -08004106 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4107 mHandler.sendMessageDelayed(
4108 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4109 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4110 }
4111
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004112 @Override
4113 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004114 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004115 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4116 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 }
4118
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004119 // In order to implement the compatibility measure for pre-M apps that call
4120 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4121 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4122 // This ensures it has permission to do so.
4123 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4124 if (nc == null) {
4125 return false;
4126 }
4127 int[] transportTypes = nc.getTransportTypes();
4128 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4129 return false;
4130 }
4131 try {
4132 mContext.enforceCallingOrSelfPermission(
4133 android.Manifest.permission.ACCESS_WIFI_STATE,
4134 "ConnectivityService");
4135 } catch (SecurityException e) {
4136 return false;
4137 }
4138 return true;
4139 }
4140
Robert Greenwalt9258c642014-03-26 16:47:06 -07004141 @Override
4142 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4143 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004144 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4145 enforceAccessPermission();
4146 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004147
Erik Kline7523eb32015-07-09 18:24:03 +09004148 NetworkRequest networkRequest = new NetworkRequest(
4149 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004150 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09004151 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004152 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004153
4154 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4155 return networkRequest;
4156 }
4157
4158 @Override
4159 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4160 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004161 checkNotNull(operation, "PendingIntent cannot be null.");
4162 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4163 enforceAccessPermission();
4164 }
4165
Erik Kline7523eb32015-07-09 18:24:03 +09004166 NetworkRequest networkRequest = new NetworkRequest(
4167 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004168 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004169 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004170 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004171
4172 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004173 }
4174
4175 @Override
4176 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004177 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4178 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004179 }
4180
4181 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004182 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004183 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004184 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4185 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004186 }
4187
Robert Greenwalta67be032014-05-16 15:49:14 -07004188 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004189 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004190 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4191 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4192 }
4193
4194 @Override
4195 public void unregisterNetworkFactory(Messenger messenger) {
4196 enforceConnectivityInternalPermission();
4197 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4198 }
4199
4200 private void handleUnregisterNetworkFactory(Messenger messenger) {
4201 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4202 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004203 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004204 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004205 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004206 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004207 }
4208
Robert Greenwalt7b816022014-04-18 15:25:25 -07004209 /**
4210 * NetworkAgentInfo supporting a request by requestId.
4211 * These have already been vetted (their Capabilities satisfy the request)
4212 * and the are the highest scored network available.
4213 * the are keyed off the Requests requestId.
4214 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004215 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004216 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4217 new SparseArray<NetworkAgentInfo>();
4218
Paul Jensen31a94f42015-02-13 14:18:39 -05004219 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4220 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004221 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4222 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004223 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4224 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4225 // there may not be a strict 1:1 correlation between the two.
4226 @GuardedBy("mNetworkForNetId")
4227 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004228
Robert Greenwalt7b816022014-04-18 15:25:25 -07004229 // NetworkAgentInfo keyed off its connecting messenger
4230 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004231 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004232 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4233 new HashMap<Messenger, NetworkAgentInfo>();
4234
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004235 @GuardedBy("mBlockedAppUids")
4236 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4237
Paul Jensen2c311d62014-11-17 12:34:51 -05004238 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004239 private final NetworkRequest mDefaultRequest;
4240
Erik Klineda4bfa82015-04-30 12:58:40 +09004241 // Request used to optionally keep mobile data active even when higher
4242 // priority networks like Wi-Fi are active.
4243 private final NetworkRequest mDefaultMobileDataRequest;
4244
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004245 private NetworkAgentInfo getDefaultNetwork() {
4246 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4247 }
4248
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004249 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004250 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004251 }
4252
Paul Jensen31a94f42015-02-13 14:18:39 -05004253 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004254 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004255 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004256 enforceConnectivityInternalPermission();
4257
Paul Jensen2c311d62014-11-17 12:34:51 -05004258 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4259 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004260 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004261 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4262 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004263 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004264 synchronized (this) {
4265 nai.networkMonitor.systemReady = mSystemReady;
4266 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004267 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004268 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004269 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004270 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004271 }
4272
4273 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4274 if (VDBG) log("Got NetworkAgent Messenger");
4275 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004276 synchronized (mNetworkForNetId) {
4277 mNetworkForNetId.put(na.network.netId, na);
4278 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004279 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4280 NetworkInfo networkInfo = na.networkInfo;
4281 na.networkInfo = null;
4282 updateNetworkInfo(na, networkInfo);
4283 }
4284
4285 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4286 LinkProperties newLp = networkAgent.linkProperties;
4287 int netId = networkAgent.network.netId;
4288
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004289 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4290 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004291 if (networkAgent.clatd != null) {
4292 networkAgent.clatd.fixupLinkProperties(oldLp);
4293 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004294
Paul Jensen992f2522014-04-28 10:33:11 -04004295 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004296 updateMtu(newLp, oldLp);
4297 // TODO - figure out what to do for clat
4298// for (LinkProperties lp : newLp.getStackedLinks()) {
4299// updateMtu(lp, null);
4300// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004301 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004302
Erik Kline94887872016-04-05 13:30:49 +09004303 updateRoutes(newLp, oldLp, netId);
4304 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004305
Paul Jensen3b759822014-05-13 11:44:01 -04004306 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004307 if (isDefaultNetwork(networkAgent)) {
4308 handleApplyDefaultProxy(newLp.getHttpProxy());
4309 } else {
4310 updateProxy(newLp, oldLp, networkAgent);
4311 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004312 // TODO - move this check to cover the whole function
4313 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004314 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004315 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4316 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004317
4318 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004319 }
4320
Lorenzo Colitti95439462014-10-09 13:44:48 +09004321 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4322 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4323 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004324
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004325 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004326 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4327 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004328 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004329 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004330 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 }
Paul Jensen992f2522014-04-28 10:33:11 -04004332
4333 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4334 CompareResult<String> interfaceDiff = new CompareResult<String>();
4335 if (oldLp != null) {
4336 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4337 } else if (newLp != null) {
4338 interfaceDiff.added = newLp.getAllInterfaceNames();
4339 }
4340 for (String iface : interfaceDiff.added) {
4341 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004342 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004343 mNetd.addInterfaceToNetwork(iface, netId);
4344 } catch (Exception e) {
4345 loge("Exception adding interface: " + e);
4346 }
4347 }
4348 for (String iface : interfaceDiff.removed) {
4349 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004350 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004351 mNetd.removeInterfaceFromNetwork(iface, netId);
4352 } catch (Exception e) {
4353 loge("Exception removing interface: " + e);
4354 }
4355 }
4356 }
4357
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004358 /**
4359 * Have netd update routes from oldLp to newLp.
4360 * @return true if routes changed between oldLp and newLp
4361 */
4362 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004363 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4364 if (oldLp != null) {
4365 routeDiff = oldLp.compareAllRoutes(newLp);
4366 } else if (newLp != null) {
4367 routeDiff.added = newLp.getAllRoutes();
4368 }
4369
4370 // add routes before removing old in case it helps with continuous connectivity
4371
4372 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4373 for (RouteInfo route : routeDiff.added) {
4374 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004375 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004376 try {
4377 mNetd.addRoute(netId, route);
4378 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004379 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4380 loge("Exception in addRoute for non-gateway: " + e);
4381 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004382 }
4383 }
4384 for (RouteInfo route : routeDiff.added) {
4385 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004386 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004387 try {
4388 mNetd.addRoute(netId, route);
4389 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004390 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4391 loge("Exception in addRoute for gateway: " + e);
4392 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004393 }
4394 }
4395
4396 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004397 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398 try {
4399 mNetd.removeRoute(netId, route);
4400 } catch (Exception e) {
4401 loge("Exception in removeRoute: " + e);
4402 }
4403 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004404 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004405 }
Erik Kline41368502015-06-17 13:19:54 +09004406
Erik Kline94887872016-04-05 13:30:49 +09004407 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4408 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4409 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004410 }
Erik Kline94887872016-04-05 13:30:49 +09004411
4412 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004413 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004414 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004415 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004416 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4417 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004418 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004419 }
4420 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4421 if (defaultNai != null && defaultNai.network.netId == netId) {
4422 setDefaultDnsSystemProperties(dnses);
4423 }
4424 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004425 }
4426
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004427 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4428 int last = 0;
4429 for (InetAddress dns : dnses) {
4430 ++last;
4431 String key = "net.dns" + last;
4432 String value = dns.getHostAddress();
4433 SystemProperties.set(key, value);
4434 }
4435 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4436 String key = "net.dns" + i;
4437 SystemProperties.set(key, "");
4438 }
4439 mNumDnsEntries = last;
4440 }
4441
Paul Jensen3d194ea2015-06-16 14:27:36 -04004442 /**
4443 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4444 * augmented with any stateful capabilities implied from {@code networkAgent}
4445 * (e.g., validated status and captive portal status).
4446 *
Paul Jensene0988542015-06-25 15:30:08 -04004447 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004448 * @param networkCapabilities the new network capabilities.
4449 */
Paul Jensene0988542015-06-25 15:30:08 -04004450 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004451 // Don't modify caller's NetworkCapabilities.
4452 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004453 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004454 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4455 } else {
4456 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4457 }
Paul Jensene0988542015-06-25 15:30:08 -04004458 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004459 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4460 } else {
4461 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4462 }
Paul Jensene0988542015-06-25 15:30:08 -04004463 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4464 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004465 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4466 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4467 try {
4468 mNetd.setNetworkPermission(nai.network.netId,
4469 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4470 null : NetworkManagementService.PERMISSION_SYSTEM);
4471 } catch (RemoteException e) {
4472 loge("Exception in setNetworkPermission: " + e);
4473 }
4474 }
Paul Jensene0988542015-06-25 15:30:08 -04004475 synchronized (nai) {
4476 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004477 }
Paul Jensene0988542015-06-25 15:30:08 -04004478 rematchAllNetworksAndRequests(nai, oldScore);
4479 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004480 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004481 }
4482
Paul Jensenc8b9a742014-09-30 15:37:41 -04004483 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4484 for (int i = 0; i < nai.networkRequests.size(); i++) {
4485 NetworkRequest nr = nai.networkRequests.valueAt(i);
4486 // Don't send listening requests to factories. b/17393458
4487 if (!isRequest(nr)) continue;
4488 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4489 }
4490 }
4491
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4493 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004494 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004495 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4496 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004497 }
4498 }
4499
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004500 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4501 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004502 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004503 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004504 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4505 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004506 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004507 sendIntent(nri.mPendingIntent, intent);
4508 }
4509 // else not handled
4510 }
4511
4512 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4513 mPendingIntentWakeLock.acquire();
4514 try {
4515 if (DBG) log("Sending " + pendingIntent);
4516 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4517 } catch (PendingIntent.CanceledException e) {
4518 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4519 mPendingIntentWakeLock.release();
4520 releasePendingNetworkRequest(pendingIntent);
4521 }
4522 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4523 }
4524
4525 @Override
4526 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4527 String resultData, Bundle resultExtras) {
4528 if (DBG) log("Finished sending " + pendingIntent);
4529 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004530 // Release with a delay so the receiving client has an opportunity to put in its
4531 // own request.
4532 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004533 }
4534
Robert Greenwalt9258c642014-03-26 16:47:06 -07004535 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004536 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004537 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004538 Bundle bundle = new Bundle();
4539 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4540 new NetworkRequest(nri.request));
4541 Message msg = Message.obtain();
4542 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4543 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4544 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4545 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004546 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004547 case ConnectivityManager.CALLBACK_LOSING: {
4548 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4549 break;
4550 }
4551 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4552 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4553 new NetworkCapabilities(networkAgent.networkCapabilities));
4554 break;
4555 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004556 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004557 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4558 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004559 break;
4560 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004561 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004562 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004563 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004564 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004565 if (VDBG) {
4566 log("sending notification " + notifyTypeToName(notificationType) +
4567 " for " + nri.request);
4568 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004569 nri.messenger.send(msg);
4570 } catch (RemoteException e) {
4571 // may occur naturally in the race of binder death.
4572 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4573 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004574 }
4575
Paul Jensenc8b9a742014-09-30 15:37:41 -04004576 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4577 for (int i = 0; i < nai.networkRequests.size(); i++) {
4578 NetworkRequest nr = nai.networkRequests.valueAt(i);
4579 // Ignore listening requests.
4580 if (!isRequest(nr)) continue;
4581 loge("Dead network still had at least " + nr);
4582 break;
4583 }
4584 nai.asyncChannel.disconnect();
4585 }
4586
Robert Greenwalt7b816022014-04-18 15:25:25 -07004587 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4588 if (oldNetwork == null) {
4589 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4590 return;
4591 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004592 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4593 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004594 }
4595
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004596 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004597 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004598 setupDataActivityTracking(newNetwork);
4599 try {
4600 mNetd.setDefaultNetId(newNetwork.network.netId);
4601 } catch (Exception e) {
4602 loge("Exception setting default network :" + e);
4603 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004604 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004605 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004606 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004607 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004608 }
4609
Paul Jensen2161a8e2014-09-11 11:00:39 -04004610 // Handles a network appearing or improving its score.
4611 //
4612 // - Evaluates all current NetworkRequests that can be
4613 // satisfied by newNetwork, and reassigns to newNetwork
4614 // any such requests for which newNetwork is the best.
4615 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004616 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004617 // needed. A network is needed if it is the best network for
4618 // one or more NetworkRequests, or if it is a VPN.
4619 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004620 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004621 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004622 //
4623 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4624 // networks that have no chance (i.e. even if validated)
4625 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004626 //
4627 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4628 // it does not remove NetworkRequests that other Networks could better satisfy.
4629 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4630 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4631 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004632 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004633 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004634 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4635 // performed to tear down unvalidated networks that have no chance (i.e. even if
4636 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004637 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004638 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Robin Lee585e2482016-05-01 23:00:00 +01004639 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004640 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004641 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004642 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004643 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004644 // Find and migrate to this Network any NetworkRequests for
4645 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004646 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004647 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004648 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004649 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004650 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4651 final boolean satisfies = newNetwork.satisfies(nri.request);
4652 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004653 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004654 log("Network " + newNetwork.name() + " was already satisfying" +
4655 " request " + nri.request.requestId + ". No change.");
4656 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004657 keep = true;
4658 continue;
4659 }
4660
4661 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004662 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004663 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004664 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004665 // This is not a request, it's a callback listener.
4666 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004667 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004668 continue;
4669 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004670
Robert Greenwalt7b816022014-04-18 15:25:25 -07004671 // next check if it's better than any current network we're using for
4672 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004673 if (VDBG) {
4674 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004675 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4676 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004677 }
4678 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004679 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004680 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004681 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004682 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004683 currentNetwork.networkRequests.remove(nri.request.requestId);
4684 currentNetwork.networkLingered.add(nri.request);
4685 affectedNetworks.add(currentNetwork);
4686 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004687 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004688 }
Paul Jensen573a0352015-01-08 10:49:34 -05004689 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004690 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004691 if (!newNetwork.addRequest(nri.request)) {
4692 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4693 }
4694 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004695 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004696 // Tell NetworkFactories about the new score, so they can stop
4697 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004698 // TODO - this could get expensive if we have alot of requests for this
4699 // network. Think about if there is a way to reduce this. Push
4700 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004701 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004702 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004703 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004704 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004705 }
4706 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004707 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4708 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4709 // mark it as no longer satisfying "nri". Because networks are processed by
4710 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4711 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4712 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4713 // This means this code doesn't have to handle the case where "currentNetwork" no
4714 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4715 if (DBG) {
4716 log("Network " + newNetwork.name() + " stopped satisfying" +
4717 " request " + nri.request.requestId);
4718 }
4719 newNetwork.networkRequests.remove(nri.request.requestId);
4720 if (currentNetwork == newNetwork) {
4721 mNetworkForRequestId.remove(nri.request.requestId);
4722 sendUpdatedScoreToFactories(nri.request, 0);
4723 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004724 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004725 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4726 newNetwork.name() +
4727 " without updating mNetworkForRequestId or factories!");
4728 }
4729 }
4730 // TODO: technically, sending CALLBACK_LOST here is
4731 // incorrect if nri is a request (not a listen) and there
4732 // is a replacement network currently connected that can
4733 // satisfy it. However, the only capability that can both
4734 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4735 // so this code is only incorrect for a network that loses
4736 // the TRUSTED capability, which is a rare case.
4737 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004738 }
4739 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004740 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004741 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004742 if (nai.lingering) {
4743 // Already lingered. Nothing to do. This can only happen if "nai" is in
4744 // "affectedNetworks" twice. The reasoning being that to get added to
4745 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4746 // (i.e. not lingered) so it could have only been lingered by this loop.
4747 // unneeded(nai) will be false and we'll call unlinger() below which would
4748 // be bad, so handle it here.
4749 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004750 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004751 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004752 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004753 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004754 }
4755 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004756 if (isNewDefault) {
4757 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004758 makeDefault(newNetwork);
4759 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4760 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004761 synchronized (ConnectivityService.this) {
4762 // have a new default network, release the transition wakelock in
4763 // a second if it's held. The second pause is to allow apps
4764 // to reconnect over the new network
4765 if (mNetTransitionWakeLock.isHeld()) {
4766 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4767 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4768 mNetTransitionWakeLockSerialNumber, 0),
4769 1000);
4770 }
4771 }
4772 }
4773
4774 // do this after the default net is switched, but
4775 // before LegacyTypeTracker sends legacy broadcasts
4776 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4777
4778 if (isNewDefault) {
4779 // Maintain the illusion: since the legacy API only
4780 // understands one network at a time, we must pretend
4781 // that the current default network disconnected before
4782 // the new one connected.
4783 if (oldDefaultNetwork != null) {
4784 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4785 oldDefaultNetwork, true);
4786 }
4787 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4788 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4789 notifyLockdownVpn(newNetwork);
4790 }
4791
Robert Greenwalt7b816022014-04-18 15:25:25 -07004792 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004793 // Notify battery stats service about this network, both the normal
4794 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004795 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004796 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004797 final IBatteryStats bs = BatteryStatsService.getService();
4798 final int type = newNetwork.networkInfo.getType();
4799
4800 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4801 bs.noteNetworkInterfaceType(baseIface, type);
4802 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4803 final String stackedIface = stacked.getInterfaceName();
4804 bs.noteNetworkInterfaceType(stackedIface, type);
4805 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4806 }
4807 } catch (RemoteException ignored) {
4808 }
4809
Robert Greenwalt152ed372014-12-17 17:19:53 -08004810 // This has to happen after the notifyNetworkCallbacks as that tickles each
4811 // ConnectivityManager instance so that legacy requests correctly bind dns
4812 // requests to this network. The legacy users are listening for this bcast
4813 // and will generally do a dns request so they can ensureRouteToHost and if
4814 // they do that before the callbacks happen they'll use the default network.
4815 //
4816 // TODO: Is there still a race here? We send the broadcast
4817 // after sending the callback, but if the app can receive the
4818 // broadcast before the callback, it might still break.
4819 //
4820 // This *does* introduce a race where if the user uses the new api
4821 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4822 // they may get old info. Reverse this after the old startUsing api is removed.
4823 // This is on top of the multiple intent sequencing referenced in the todo above.
4824 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4825 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4826 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4827 // legacy type tracker filters out repeat adds
4828 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4829 }
4830 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004831
4832 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4833 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4834 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4835 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4836 if (newNetwork.isVPN()) {
4837 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4838 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004839 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004840 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4841 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004842 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004843 if (DBG) log("Reaping " + nai.name());
4844 teardownUnneededNetwork(nai);
4845 }
4846 }
4847 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004848 }
4849
Paul Jensen1c7ba022015-06-16 14:27:36 -04004850 /**
4851 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4852 * being disconnected.
4853 * @param changed If only one Network's score or capabilities have been modified since the last
4854 * time this function was called, pass this Network in this argument, otherwise pass
4855 * null.
4856 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4857 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4858 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4859 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4860 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004861 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004862 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004863 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4864 // to avoid the slowness. It is not simply enough to process just "changed", for
4865 // example in the case where "changed"'s score decreases and another network should begin
4866 // satifying a NetworkRequest that "changed" currently satisfies.
4867
4868 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4869 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4870 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004871 if (changed != null && oldScore < changed.getCurrentScore()) {
4872 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004873 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004874 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4875 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4876 // Rematch higher scoring networks first to prevent requests first matching a lower
4877 // scoring network and then a higher scoring network, which could produce multiple
4878 // callbacks and inadvertently unlinger networks.
4879 Arrays.sort(nais);
4880 for (NetworkAgentInfo nai : nais) {
4881 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004882 // Only reap the last time through the loop. Reaping before all rematching
4883 // is complete could incorrectly teardown a network that hasn't yet been
4884 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004885 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004886 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004887 }
4888 }
4889 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004890
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004891 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004892 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004893 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004894 // For now only update icons for default connection.
4895 // TODO: Update WiFi and cellular icons separately. b/17237507
4896 if (!isDefaultNetwork(nai)) return;
4897
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004898 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004899 // Don't repeat publish.
4900 if (newInetCondition == mDefaultInetConditionPublished) return;
4901
4902 mDefaultInetConditionPublished = newInetCondition;
4903 sendInetConditionBroadcast(nai.networkInfo);
4904 }
4905
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004906 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4907 if (mLockdownTracker != null) {
4908 if (nai != null && nai.isVPN()) {
4909 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4910 } else {
4911 mLockdownTracker.onNetworkInfoChanged();
4912 }
4913 }
4914 }
4915
Robert Greenwalt7b816022014-04-18 15:25:25 -07004916 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4917 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004918 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004919 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004920 synchronized (networkAgent) {
4921 oldInfo = networkAgent.networkInfo;
4922 networkAgent.networkInfo = newInfo;
4923 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004924 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004925
4926 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004927 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4928 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4929 notifyIfacesChangedForNetworkStats();
4930 } else if (VDBG) log("ignoring duplicate network state non-change");
4931 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004932 return;
4933 }
4934 if (DBG) {
4935 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4936 (oldInfo == null ? "null" : oldInfo.getState()) +
4937 " to " + state);
4938 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004939
Robin Lee585e2482016-05-01 23:00:00 +01004940 if (!networkAgent.created
4941 && (state == NetworkInfo.State.CONNECTED
4942 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004943 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004944 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004945 if (networkAgent.isVPN()) {
4946 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004947 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4948 (networkAgent.networkMisc == null ||
4949 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004950 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004951 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4952 networkAgent.networkCapabilities.hasCapability(
4953 NET_CAPABILITY_NOT_RESTRICTED) ?
4954 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004955 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004956 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004957 loge("Error creating network " + networkAgent.network.netId + ": "
4958 + e.getMessage());
4959 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004960 }
Paul Jenseneec75412014-08-04 12:21:19 -04004961 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004962 }
4963
4964 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4965 networkAgent.everConnected = true;
4966
Robert Greenwalt7b816022014-04-18 15:25:25 -07004967 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004968 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004969
Paul Jensenca8f16a2014-05-09 12:47:55 -04004970 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004971 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004972
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004973 if (networkAgent.isVPN()) {
4974 // Temporarily disable the default proxy (not global).
4975 synchronized (mProxyLock) {
4976 if (!mDefaultProxyDisabled) {
4977 mDefaultProxyDisabled = true;
4978 if (mGlobalProxy == null && mDefaultProxy != null) {
4979 sendProxyBroadcast(null);
4980 }
4981 }
4982 }
4983 // TODO: support proxy per network.
4984 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004985
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004986 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4987 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4988 // capabilities, so it only needs to be done once on initial connect, not every time the
4989 // network's capabilities change. Note that we do this before rematching the network,
4990 // so we could decide to tear it down immediately afterwards. That's fine though - on
4991 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4992 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004993 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004994
Paul Jensen2161a8e2014-09-11 11:00:39 -04004995 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004996 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004997
4998 // This has to happen after matching the requests, because callbacks are just requests.
4999 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005000 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005001 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005002 if (networkAgent.isVPN()) {
5003 synchronized (mProxyLock) {
5004 if (mDefaultProxyDisabled) {
5005 mDefaultProxyDisabled = false;
5006 if (mGlobalProxy == null && mDefaultProxy != null) {
5007 sendProxyBroadcast(mDefaultProxy);
5008 }
5009 }
5010 }
5011 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005012 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5013 state == NetworkInfo.State.SUSPENDED) {
5014 // going into or coming out of SUSPEND: rescore and notify
5015 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005016 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005017 }
5018 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5019 ConnectivityManager.CALLBACK_SUSPENDED :
5020 ConnectivityManager.CALLBACK_RESUMED));
5021 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005022 }
5023 }
5024
Robert Greenwaltac96c522014-06-03 16:43:57 -07005025 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005026 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005027 if (score < 0) {
5028 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5029 "). Bumping score to min of 0");
5030 score = 0;
5031 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005032
Paul Jensen2161a8e2014-09-11 11:00:39 -04005033 final int oldScore = nai.getCurrentScore();
5034 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005035
Paul Jensen85cf78e2015-06-25 13:25:07 -04005036 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005037
Paul Jensenc8b9a742014-09-30 15:37:41 -04005038 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005039 }
5040
Robert Greenwalt9258c642014-03-26 16:47:06 -07005041 // notify only this one new request of the current state
5042 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5043 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
5044 // TODO - read state from monitor to decide what to send.
5045// if (nai.networkMonitor.isLingering()) {
5046// notifyType = NetworkCallbacks.LOSING;
5047// } else if (nai.networkMonitor.isEvaluating()) {
5048// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
5049// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005050 if (nri.mPendingIntent == null) {
5051 callCallbackForRequest(nri, nai, notifyType);
5052 } else {
5053 sendPendingIntentForRequest(nri, nai, notifyType);
5054 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005055 }
5056
Robert Greenwalt8d482522015-06-24 13:23:42 -07005057 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005058 // The NetworkInfo we actually send out has no bearing on the real
5059 // state of affairs. For example, if the default connection is mobile,
5060 // and a request for HIPRI has just gone away, we need to pretend that
5061 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5062 // the state to DISCONNECTED, even though the network is of type MOBILE
5063 // and is still connected.
5064 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5065 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005066 if (state != DetailedState.DISCONNECTED) {
5067 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005068 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005069 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005070 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005071 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5072 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5073 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5074 if (info.isFailover()) {
5075 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5076 nai.networkInfo.setFailover(false);
5077 }
5078 if (info.getReason() != null) {
5079 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5080 }
5081 if (info.getExtraInfo() != null) {
5082 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5083 }
5084 NetworkAgentInfo newDefaultAgent = null;
5085 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005086 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005087 if (newDefaultAgent != null) {
5088 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5089 newDefaultAgent.networkInfo);
5090 } else {
5091 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5092 }
5093 }
5094 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5095 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005096 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005097 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005098 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005099 }
5100 }
5101 }
5102
Robert Greenwalt7b816022014-04-18 15:25:25 -07005103 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005104 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005105 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005106 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
5107 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5108 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005109 if (nri.mPendingIntent == null) {
5110 callCallbackForRequest(nri, networkAgent, notifyType);
5111 } else {
5112 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5113 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005114 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005116
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005117 private String notifyTypeToName(int notifyType) {
5118 switch (notifyType) {
5119 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5120 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5121 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5122 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5123 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5124 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5125 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5126 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5127 }
5128 return "UNKNOWN";
5129 }
5130
Jeff Sharkey69736342014-12-08 14:50:12 -08005131 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005132 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5133 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005134 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005135 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005136 try {
5137 mStatsService.forceUpdateIfaces();
5138 } catch (Exception ignored) {
5139 }
5140 }
5141
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005142 @Override
5143 public boolean addVpnAddress(String address, int prefixLength) {
5144 throwIfLockdownEnabled();
5145 int user = UserHandle.getUserId(Binder.getCallingUid());
5146 synchronized (mVpns) {
5147 return mVpns.get(user).addAddress(address, prefixLength);
5148 }
5149 }
5150
5151 @Override
5152 public boolean removeVpnAddress(String address, int prefixLength) {
5153 throwIfLockdownEnabled();
5154 int user = UserHandle.getUserId(Binder.getCallingUid());
5155 synchronized (mVpns) {
5156 return mVpns.get(user).removeAddress(address, prefixLength);
5157 }
5158 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005159
5160 @Override
5161 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5162 throwIfLockdownEnabled();
5163 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005164 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005165 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005166 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005167 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005168 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005169 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005170 }
5171 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005172 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005173
5174 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005175 public String getCaptivePortalServerUrl() {
5176 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5177 }
5178
5179 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005180 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5181 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5182 enforceKeepalivePermission();
5183 mKeepaliveTracker.startNattKeepalive(
5184 getNetworkAgentInfoForNetwork(network),
5185 intervalSeconds, messenger, binder,
5186 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5187 }
5188
5189 @Override
5190 public void stopKeepalive(Network network, int slot) {
5191 mHandler.sendMessage(mHandler.obtainMessage(
5192 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5193 }
5194
5195 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005196 public void factoryReset() {
5197 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005198
5199 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5200 return;
5201 }
5202
Robin Lee3b3dd942015-05-12 18:14:58 +01005203 final int userId = UserHandle.getCallingUserId();
5204
Stuart Scottf1fb3972015-04-02 18:00:02 -07005205 // Turn airplane mode off
5206 setAirplaneMode(false);
5207
Stuart Scotte3e314d2015-04-20 14:07:45 -07005208 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5209 // Untether
5210 for (String tether : getTetheredIfaces()) {
5211 untether(tether);
5212 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005213 }
5214
Stuart Scotte3e314d2015-04-20 14:07:45 -07005215 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5216 // Turn VPN off
5217 VpnConfig vpnConfig = getVpnConfig(userId);
5218 if (vpnConfig != null) {
5219 if (vpnConfig.legacy) {
5220 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5221 } else {
5222 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5223 // in the future without user intervention.
5224 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005225
Stuart Scotte3e314d2015-04-20 14:07:45 -07005226 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5227 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005228 }
5229 }
5230 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005231
5232 @VisibleForTesting
5233 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5234 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5235 return new NetworkMonitor(context, handler, nai, defaultRequest);
5236 }
Erik Kline48f12f22016-04-14 17:30:59 +09005237
Hugo Benichi5f16f762016-04-20 12:09:33 +09005238 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5239 int newNetid = NETID_UNSET;
5240 int prevNetid = NETID_UNSET;
5241 int[] transports = new int[0];
5242 boolean hadIPv4 = false;
5243 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005244
Hugo Benichi5f16f762016-04-20 12:09:33 +09005245 if (newNai != null) {
5246 newNetid = newNai.network.netId;
5247 transports = newNai.networkCapabilities.getTransportTypes();
5248 }
5249 if (prevNai != null) {
5250 prevNetid = prevNai.network.netId;
5251 final LinkProperties lp = prevNai.linkProperties;
5252 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5253 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5254 }
5255
5256 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005257 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005258}