blob: 53b29427b29c47057272b44383751efd6e338ee3 [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
789 private void handleMobileDataAlwaysOn() {
790 final boolean enable = (Settings.Global.getInt(
791 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
792 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
793 if (enable == isEnabled) {
794 return; // Nothing to do.
795 }
796
797 if (enable) {
798 handleRegisterNetworkRequest(new NetworkRequestInfo(
Erik Kline371c7b72016-03-22 17:04:20 +0900799 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestType.REQUEST));
Erik Klineda4bfa82015-04-30 12:58:40 +0900800 } else {
801 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
802 }
803 }
804
805 private void registerSettingsCallbacks() {
806 // Watch for global HTTP proxy changes.
807 mSettingsObserver.observe(
808 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
809 EVENT_APPLY_GLOBAL_HTTP_PROXY);
810
811 // Watch for whether or not to keep mobile data always on.
812 mSettingsObserver.observe(
813 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
814 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
815 }
816
Robert Greenwalt34524f02014-05-18 16:22:10 -0700817 private synchronized int nextNetworkRequestId() {
818 return mNextNetworkRequestId++;
819 }
820
Paul Jensen67b0b072015-06-10 11:22:17 -0400821 @VisibleForTesting
822 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400823 synchronized (mNetworkForNetId) {
824 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
825 int netId = mNextNetId;
826 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
827 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500828 if (!mNetIdInUse.get(netId)) {
829 mNetIdInUse.put(netId, true);
830 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400831 }
832 }
833 }
834 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700835 }
836
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600837 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800838 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600839 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
840 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600842 state = nai.getNetworkState();
843 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800844 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600845 final NetworkInfo info = new NetworkInfo(networkType, 0,
846 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
848 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600849 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
850 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800851 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600852 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600853 return state;
854 } else {
855 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800856 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400857 }
858
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
860 if (network == null) {
861 return null;
862 }
863 synchronized (mNetworkForNetId) {
864 return mNetworkForNetId.get(network.netId);
865 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600866 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800867
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900868 private Network[] getVpnUnderlyingNetworks(int uid) {
869 if (!mLockdownEnabled) {
870 int user = UserHandle.getUserId(uid);
871 synchronized (mVpns) {
872 Vpn vpn = mVpns.get(user);
873 if (vpn != null && vpn.appliesToUid(uid)) {
874 return vpn.getUnderlyingNetworks();
875 }
876 }
877 }
878 return null;
879 }
880
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800881 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400882 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800883
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900884 final Network[] networks = getVpnUnderlyingNetworks(uid);
885 if (networks != null) {
886 // getUnderlyingNetworks() returns:
887 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
888 // empty array => the VPN explicitly said "no default network".
889 // non-empty array => the VPN specified one or more default networks; we use the
890 // first one.
891 if (networks.length > 0) {
892 nai = getNetworkAgentInfoForNetwork(networks[0]);
893 } else {
894 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800895 }
896 }
897
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800898 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600899 return nai.getNetworkState();
900 } else {
901 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800902 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400903 }
904
905 /**
906 * Check if UID should be blocked from using the network with the given LinkProperties.
907 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600908 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
909 boolean ignoreBlocked) {
910 // Networks aren't blocked when ignoring blocked status
911 if (ignoreBlocked) return false;
912 // Networks are never blocked for system services
913 if (uid < Process.FIRST_APPLICATION_UID) return false;
914
915 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700916 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700917
Robert Greenwalt12e67352014-05-13 21:41:06 -0700918 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700919 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600920 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -0700921 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700922 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700923
Felipe Lemed31a97f2016-05-06 14:53:50 -0700924 boolean allowed = true;
925 // Check Data Saver Mode first...
926 if (networkMetered) {
927 if ((uidRules & RULE_REJECT_METERED) != 0) {
928 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
929 // Explicitly blacklisted.
930 allowed = false;
931 } else {
932 allowed = !mRestrictBackground
933 || (uidRules & RULE_ALLOW_METERED) != 0
934 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
935 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
936 + " mRestrictBackground=" + mRestrictBackground
937 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
938 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
939 + ": " + allowed);
940 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700941 }
Felipe Leme781ba142016-05-09 16:24:48 -0700942 // ...then power restrictions.
943 if (allowed) {
944 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -0700945 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -0700946 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -0700947 }
948 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700949 }
950
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900951 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
952 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) return;
953 boolean removed = false;
954 boolean added = false;
955 synchronized (mBlockedAppUids) {
956 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
957 added = true;
958 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
959 removed = true;
960 }
961 }
962 if (added) log("Returning blocked NetworkInfo to uid=" + uid);
963 else if (removed) log("Returning unblocked NetworkInfo to uid=" + uid);
964 }
965
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700966 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600967 * Apply any relevant filters to {@link NetworkState} for the given UID. For
968 * example, this may mark the network as {@link DetailedState#BLOCKED} based
969 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
970 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700971 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600972 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600973 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
974
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600975 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600976 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700977 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600978 if (mLockdownTracker != null) {
979 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700980 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600981
982 // TODO: apply metered state closer to NetworkAgentInfo
983 final long token = Binder.clearCallingIdentity();
984 try {
985 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
986 } catch (RemoteException e) {
987 } finally {
988 Binder.restoreCallingIdentity(token);
989 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700990 }
991
992 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800993 * Return NetworkInfo for the active (i.e., connected) network interface.
994 * It is assumed that at most one network is active at a time. If more
995 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700996 * @return the info for the active network, or {@code null} if none is
997 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700999 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001001 enforceAccessPermission();
1002 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001003 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001004 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001005 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1006 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001007 }
1008
Paul Jensen31a94f42015-02-13 14:18:39 -05001009 @Override
1010 public Network getActiveNetwork() {
1011 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001012 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001013 }
1014
1015 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001016 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001017 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001018 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001019 }
1020
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001021 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001022 final int user = UserHandle.getUserId(uid);
1023 int vpnNetId = NETID_UNSET;
1024 synchronized (mVpns) {
1025 final Vpn vpn = mVpns.get(user);
1026 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1027 }
1028 NetworkAgentInfo nai;
1029 if (vpnNetId != NETID_UNSET) {
1030 synchronized (mNetworkForNetId) {
1031 nai = mNetworkForNetId.get(vpnNetId);
1032 }
1033 if (nai != null) return nai.network;
1034 }
1035 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001036 if (nai != null
1037 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1038 nai = null;
1039 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001040 return nai != null ? nai.network : null;
1041 }
1042
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001043 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1044 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001045 final int uid = Binder.getCallingUid();
1046 NetworkState state = getUnfilteredActiveNetworkState(uid);
1047 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001048 }
1049
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001050 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001051 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001053 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001054 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001055 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001056 }
1057
1058 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001059 public NetworkInfo getNetworkInfo(int networkType) {
1060 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001061 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001062 if (getVpnUnderlyingNetworks(uid) != null) {
1063 // A VPN is active, so we may need to return one of its underlying networks. This
1064 // information is not available in LegacyTypeTracker, so we have to get it from
1065 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001066 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001067 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001068 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001069 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001070 }
1071 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001072 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001073 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001076 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001077 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001078 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001079 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001080 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001081 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001082 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 return state.networkInfo;
1084 } else {
1085 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001086 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001087 }
1088
1089 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 public NetworkInfo[] getAllNetworkInfo() {
1091 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001092 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001093 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1094 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001095 NetworkInfo info = getNetworkInfo(networkType);
1096 if (info != null) {
1097 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001098 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001100 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 }
1102
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001103 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001104 public Network getNetworkForType(int networkType) {
1105 enforceAccessPermission();
1106 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001107 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1108 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001109 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001110 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001111 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001112 }
1113
1114 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001115 public Network[] getAllNetworks() {
1116 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001117 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001118 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001119 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001120 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001121 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001122 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001123 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001124 }
1125
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001126 @Override
1127 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1128 // The basic principle is: if an app's traffic could possibly go over a
1129 // network, without the app doing anything multinetwork-specific,
1130 // (hence, by "default"), then include that network's capabilities in
1131 // the array.
1132 //
1133 // In the normal case, app traffic only goes over the system's default
1134 // network connection, so that's the only network returned.
1135 //
1136 // With a VPN in force, some app traffic may go into the VPN, and thus
1137 // over whatever underlying networks the VPN specifies, while other app
1138 // traffic may go over the system default network (e.g.: a split-tunnel
1139 // VPN, or an app disallowed by the VPN), so the set of networks
1140 // returned includes the VPN's underlying networks and the system
1141 // default.
1142 enforceAccessPermission();
1143
1144 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1145
1146 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001147 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001148 if (nc != null) {
1149 result.put(nai.network, nc);
1150 }
1151
1152 if (!mLockdownEnabled) {
1153 synchronized (mVpns) {
1154 Vpn vpn = mVpns.get(userId);
1155 if (vpn != null) {
1156 Network[] networks = vpn.getUnderlyingNetworks();
1157 if (networks != null) {
1158 for (Network network : networks) {
1159 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001160 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001161 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001162 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001163 }
1164 }
1165 }
1166 }
1167 }
1168 }
1169
1170 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1171 out = result.values().toArray(out);
1172 return out;
1173 }
1174
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001175 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001176 public boolean isNetworkSupported(int networkType) {
1177 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001179 }
1180
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001181 /**
1182 * Return LinkProperties for the active (i.e., connected) default
1183 * network interface. It is assumed that at most one default network
1184 * is active at a time. If more than one is active, it is indeterminate
1185 * which will be returned.
1186 * @return the ip properties for the active network, or {@code null} if
1187 * none is active
1188 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001189 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001190 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001191 enforceAccessPermission();
1192 final int uid = Binder.getCallingUid();
1193 NetworkState state = getUnfilteredActiveNetworkState(uid);
1194 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001195 }
1196
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001197 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001198 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001199 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001200 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1201 if (nai != null) {
1202 synchronized (nai) {
1203 return new LinkProperties(nai.linkProperties);
1204 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001205 }
1206 return null;
1207 }
1208
Robert Greenwalt12e67352014-05-13 21:41:06 -07001209 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001210 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001211 public LinkProperties getLinkProperties(Network network) {
1212 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001213 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001214 if (nai != null) {
1215 synchronized (nai) {
1216 return new LinkProperties(nai.linkProperties);
1217 }
1218 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001219 return null;
1220 }
1221
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001222 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001223 if (nai != null) {
1224 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001225 if (nai.networkCapabilities != null) {
1226 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001227 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 }
1229 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001230 return null;
1231 }
1232
1233 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001234 public NetworkCapabilities getNetworkCapabilities(Network network) {
1235 enforceAccessPermission();
1236 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1237 }
1238
1239 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001240 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001241 // Require internal since we're handing out IMSI details
1242 enforceConnectivityInternalPermission();
1243
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001244 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001245 for (Network network : getAllNetworks()) {
1246 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1247 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001248 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001249 }
1250 }
1251 return result.toArray(new NetworkState[result.size()]);
1252 }
1253
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001254 @Override
1255 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1256 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001257 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001258 final long token = Binder.clearCallingIdentity();
1259 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001260 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1261 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001262 try {
1263 return mPolicyManager.getNetworkQuotaInfo(state);
1264 } catch (RemoteException e) {
1265 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001266 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001267 return null;
1268 } finally {
1269 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001270 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001271 }
1272
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001273 @Override
1274 public boolean isActiveNetworkMetered() {
1275 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001276
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001277 final NetworkInfo info = getActiveNetworkInfo();
1278 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001279 }
1280
Jeff Sharkey216c1812012-08-05 14:29:23 -07001281 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1282 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001283 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001284 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001285 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001286 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001287 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001288
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001289 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 * Ensure that a network route exists to deliver traffic to the specified
1291 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001292 * @param networkType the type of the network over which traffic to the
1293 * specified host is to be routed
1294 * @param hostAddress the IP address of the host to which the route is
1295 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 * @return {@code true} on success, {@code false} on failure
1297 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001298 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001299 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001300 if (mProtectedNetworks.contains(networkType)) {
1301 enforceConnectivityInternalPermission();
1302 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001303
Chad Brubakerc0234532014-02-14 13:24:29 -08001304 InetAddress addr;
1305 try {
1306 addr = InetAddress.getByAddress(hostAddress);
1307 } catch (UnknownHostException e) {
1308 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1309 return false;
1310 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001311
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001313 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 return false;
1315 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001316
1317 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1318 if (nai == null) {
1319 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1320 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1321 } else {
1322 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1323 }
1324 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001325 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001326
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001327 DetailedState netState;
1328 synchronized (nai) {
1329 netState = nai.networkInfo.getDetailedState();
1330 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001331
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001332 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001333 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001334 log("requestRouteToHostAddress on down network "
1335 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001336 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001337 }
1338 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001339 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001340
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001341 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001342 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001343 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001344 LinkProperties lp;
1345 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001346 synchronized (nai) {
1347 lp = nai.linkProperties;
1348 netId = nai.network.netId;
1349 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001350 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001351 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1352 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001353 } finally {
1354 Binder.restoreCallingIdentity(token);
1355 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001356 }
1357
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001358 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001359 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001360 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001361 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001362 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001363 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001364 if (bestRoute.getGateway().equals(addr)) {
1365 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001366 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001367 } else {
1368 // if we will connect to this through another route, add a direct route
1369 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001370 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001371 }
1372 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001373 if (DBG) log("Adding legacy route " + bestRoute +
1374 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001375 try {
1376 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1377 } catch (Exception e) {
1378 // never crash - catch them all
1379 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001380 return false;
1381 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001382 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 }
1384
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001385 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1386 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001387 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001388 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001389 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001390 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001391 }
1392
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001393 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001394 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001395 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001396 if (oldRules == uidRules) return;
1397
Felipe Leme781ba142016-05-09 16:24:48 -07001398 if (uidRules == RULE_NONE) {
1399 mUidRules.delete(uid);
1400 } else {
1401 mUidRules.put(uid, uidRules);
1402 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001403 }
1404
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001405 // TODO: notify UID when it has requested targeted updates
1406 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001407
1408 @Override
1409 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001410 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001411 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001412 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001413 }
1414
1415 synchronized (mRulesLock) {
1416 mMeteredIfaces.clear();
1417 for (String iface : meteredIfaces) {
1418 mMeteredIfaces.add(iface);
1419 }
1420 }
1421 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001422
1423 @Override
1424 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1425 // caller is NPMS, since we only register with them
1426 if (LOGD_RULES) {
1427 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1428 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001429
1430 synchronized (mRulesLock) {
1431 mRestrictBackground = restrictBackground;
1432 }
1433
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001434 if (restrictBackground) {
1435 log("onRestrictBackgroundChanged(true): disabling tethering");
1436 mTethering.untetherAll();
1437 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001438 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001439
1440 @Override
1441 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1442 if (LOGD_RULES) {
1443 // caller is NPMS, since we only register with them
1444 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1445 + whitelisted + ")");
1446 }
1447 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001448 };
1449
Robin Lee3b3dd942015-05-12 18:14:58 +01001450 /**
1451 * Require that the caller is either in the same user or has appropriate permission to interact
1452 * across users.
1453 *
1454 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1455 */
1456 private void enforceCrossUserPermission(int userId) {
1457 if (userId == UserHandle.getCallingUserId()) {
1458 // Not a cross-user call.
1459 return;
1460 }
1461 mContext.enforceCallingOrSelfPermission(
1462 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1463 "ConnectivityService");
1464 }
1465
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001466 private void enforceInternetPermission() {
1467 mContext.enforceCallingOrSelfPermission(
1468 android.Manifest.permission.INTERNET,
1469 "ConnectivityService");
1470 }
1471
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001472 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001473 mContext.enforceCallingOrSelfPermission(
1474 android.Manifest.permission.ACCESS_NETWORK_STATE,
1475 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
1477
1478 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001479 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001480 }
1481
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001482 private void enforceTetherAccessPermission() {
1483 mContext.enforceCallingOrSelfPermission(
1484 android.Manifest.permission.ACCESS_NETWORK_STATE,
1485 "ConnectivityService");
1486 }
1487
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001488 private void enforceConnectivityInternalPermission() {
1489 mContext.enforceCallingOrSelfPermission(
1490 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1491 "ConnectivityService");
1492 }
1493
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001494 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001495 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001496 }
1497
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001498 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001499 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001500 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001501 }
1502
1503 private void sendInetConditionBroadcast(NetworkInfo info) {
1504 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1505 }
1506
Wink Saville628b0852011-08-04 15:01:58 -07001507 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001508 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001509 info = new NetworkInfo(info);
1510 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001511 }
1512
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001513 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001514 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001515 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 if (info.isFailover()) {
1517 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1518 info.setFailover(false);
1519 }
1520 if (info.getReason() != null) {
1521 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1522 }
1523 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001524 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1525 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001527 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001528 return intent;
1529 }
1530
1531 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1532 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1533 }
1534
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001535 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001536 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1537 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1538 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001539 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001540 final long ident = Binder.clearCallingIdentity();
1541 try {
1542 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1543 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1544 } finally {
1545 Binder.restoreCallingIdentity(ident);
1546 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001547 }
1548
Mike Lockwood0f79b542009-08-14 14:18:49 -04001549 private void sendStickyBroadcast(Intent intent) {
1550 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001551 if (!mSystemReady) {
1552 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001553 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001554 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001555 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001556 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001557 }
1558
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001559 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001560 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001561 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001562 final NetworkInfo ni = intent.getParcelableExtra(
1563 ConnectivityManager.EXTRA_NETWORK_INFO);
1564 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1565 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1566 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001567 } else {
1568 BroadcastOptions opts = BroadcastOptions.makeBasic();
1569 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1570 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001571 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001572 final IBatteryStats bs = BatteryStatsService.getService();
1573 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001574 bs.noteConnectivityChanged(intent.getIntExtra(
1575 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1576 ni != null ? ni.getState().toString() : "?");
1577 } catch (RemoteException e) {
1578 }
1579 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001580 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001581 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001582 } finally {
1583 Binder.restoreCallingIdentity(ident);
1584 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001585 }
1586 }
1587
1588 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001589 loadGlobalProxy();
1590
Mike Lockwood0f79b542009-08-14 14:18:49 -04001591 synchronized(this) {
1592 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001593 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001594 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001595 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001596 }
1597 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001598 // load the global proxy at startup
1599 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001600
Robin Lee244ce8e2016-01-05 18:03:46 +00001601 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1602 // for user to unlock device too.
1603 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001604
Erik Klineda4bfa82015-04-30 12:58:40 +09001605 // Configure whether mobile data is always on.
1606 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1607
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001608 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001609
1610 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001611 }
1612
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001614 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001615 *
1616 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001617 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001618 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001619 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1620 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001621
1622 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001623 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001624
Robert Greenwalt7b816022014-04-18 15:25:25 -07001625 if (networkAgent.networkCapabilities.hasTransport(
1626 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001627 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1628 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001629 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001630 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001631 } else if (networkAgent.networkCapabilities.hasTransport(
1632 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001633 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1634 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001635 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001636 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001637 } else {
1638 // do not track any other networks
1639 timeout = 0;
1640 }
1641
Robert Greenwalt7b816022014-04-18 15:25:25 -07001642 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001643 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001644 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001645 } catch (Exception e) {
1646 // You shall not crash!
1647 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001648 }
1649 }
1650 }
1651
1652 /**
1653 * Remove data activity tracking when network disconnects.
1654 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001655 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1656 final String iface = networkAgent.linkProperties.getInterfaceName();
1657 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001658
Robert Greenwalt7b816022014-04-18 15:25:25 -07001659 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1660 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001661 try {
1662 // the call fails silently if no idletimer setup for this interface
1663 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001664 } catch (Exception e) {
1665 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001666 }
1667 }
1668 }
1669
1670 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001671 * Reads the network specific MTU size from reources.
1672 * and set it on it's iface.
1673 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001674 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1675 final String iface = newLp.getInterfaceName();
1676 final int mtu = newLp.getMtu();
1677 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1678 if (VDBG) log("identical MTU - not setting");
1679 return;
1680 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001681
Robert Greenwalt43074032014-08-15 17:53:05 -07001682 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001683 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001684 return;
1685 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001686
w1997615afd812014-08-05 15:18:11 -07001687 // Cannot set MTU without interface name
1688 if (TextUtils.isEmpty(iface)) {
1689 loge("Setting MTU size with null iface.");
1690 return;
1691 }
1692
Robert Greenwalt7b816022014-04-18 15:25:25 -07001693 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001694 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001695 mNetd.setMtu(iface, mtu);
1696 } catch (Exception e) {
1697 Slog.e(TAG, "exception in setMtu()" + e);
1698 }
1699 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001700
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001701 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001702 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1703
1704 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001705 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001706 protected int getDefaultTcpRwnd() {
1707 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1708 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001709
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001710 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1711 if (isDefaultNetwork(nai) == false) {
1712 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001713 }
1714
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001715 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1716 String[] values = null;
1717 if (tcpBufferSizes != null) {
1718 values = tcpBufferSizes.split(",");
1719 }
1720
1721 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001722 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001723 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1724 values = tcpBufferSizes.split(",");
1725 }
1726
1727 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1728
1729 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001730 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001731
1732 final String prefix = "/sys/kernel/ipv4/tcp_";
1733 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1734 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1735 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1736 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1737 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1738 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1739 mCurrentTcpBufferSizes = tcpBufferSizes;
1740 } catch (IOException e) {
1741 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001742 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001743
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001744 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001745 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001746 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1747 if (rwndValue != 0) {
1748 SystemProperties.set(sysctlKey, rwndValue.toString());
1749 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001750 }
1751
Mattias Falk8b47b362011-08-23 14:15:13 +02001752 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001753 /*
1754 * Tell the VMs to toss their DNS caches
1755 */
1756 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1757 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001758 /*
1759 * Connectivity events can happen before boot has completed ...
1760 */
1761 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001762 final long ident = Binder.clearCallingIdentity();
1763 try {
1764 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1765 } finally {
1766 Binder.restoreCallingIdentity(ident);
1767 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001768 }
1769
Robert Greenwalt562cc542014-05-15 18:07:26 -07001770 @Override
1771 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001772 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1773 NETWORK_RESTORE_DELAY_PROP_NAME);
1774 if(restoreDefaultNetworkDelayStr != null &&
1775 restoreDefaultNetworkDelayStr.length() != 0) {
1776 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001777 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001778 } catch (NumberFormatException e) {
1779 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001780 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001781 // if the system property isn't set, use the value for the apn type
1782 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1783
1784 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1785 (mNetConfigs[networkType] != null)) {
1786 ret = mNetConfigs[networkType].restoreTime;
1787 }
1788 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 }
1790
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001791 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001792 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001793 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001794 }
1795 return false;
1796 }
1797
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001798 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1799 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1800 final long DIAG_TIME_MS = 5000;
1801 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1802 // Start gathering diagnostic information.
1803 netDiags.add(new NetworkDiagnostics(
1804 nai.network,
1805 new LinkProperties(nai.linkProperties), // Must be a copy.
1806 DIAG_TIME_MS));
1807 }
1808
1809 for (NetworkDiagnostics netDiag : netDiags) {
1810 pw.println();
1811 netDiag.waitForMeasurements();
1812 netDiag.dump(pw);
1813 }
1814 }
1815
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001817 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1818 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001819 if (mContext.checkCallingOrSelfPermission(
1820 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001822 pw.println("Permission Denial: can't dump ConnectivityService " +
1823 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1824 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001825 return;
1826 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001827
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001828 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001829 dumpNetworkDiagnostics(pw);
1830 return;
1831 }
Erik Kline379747a2015-06-05 17:47:34 +09001832
Lorenzo Colittie3805462015-06-03 11:18:24 +09001833 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001834 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001835 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001836 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001837 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001838 pw.println();
1839
Paul Jensen85cf78e2015-06-25 13:25:07 -04001840 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001841 pw.print("Active default network: ");
1842 if (defaultNai == null) {
1843 pw.println("none");
1844 } else {
1845 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001847 pw.println();
1848
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001849 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001850 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001851 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1852 pw.println(nai.toString());
1853 pw.increaseIndent();
1854 pw.println("Requests:");
1855 pw.increaseIndent();
1856 for (int i = 0; i < nai.networkRequests.size(); i++) {
1857 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001858 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001859 pw.decreaseIndent();
1860 pw.println("Lingered:");
1861 pw.increaseIndent();
1862 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1863 pw.decreaseIndent();
1864 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001865 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001866 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001867 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001868
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001869 pw.println("Metered Interfaces:");
1870 pw.increaseIndent();
1871 for (String value : mMeteredIfaces) {
1872 pw.println(value);
1873 }
1874 pw.decreaseIndent();
1875 pw.println();
1876
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001877 pw.print("Restrict background: ");
1878 pw.println(mRestrictBackground);
1879 pw.println();
1880
Felipe Leme46c4fc32016-05-04 09:21:43 -07001881 pw.println("Status for known UIDs:");
1882 pw.increaseIndent();
1883 final int size = mUidRules.size();
1884 for (int i = 0; i < size; i++) {
1885 final int uid = mUidRules.keyAt(i);
1886 pw.print("UID=");
1887 pw.print(uid);
1888 final int uidRules = mUidRules.get(uid, RULE_NONE);
1889 pw.print(" rules=");
1890 pw.print(uidRulesToString(uidRules));
1891 pw.println();
1892 }
1893 pw.println();
1894 pw.decreaseIndent();
1895
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001896 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001897 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001898 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1899 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001900 }
1901 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001902 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001903
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001904 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001905
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001906 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001907 pw.print("mNetTransitionWakeLock: currently " +
1908 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1909 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1910 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1911 } else {
1912 pw.println(", last requested never");
1913 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001914 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001915
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001916 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001917 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001918
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001919 pw.println();
1920 mKeepaliveTracker.dump(pw);
1921
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001922 pw.println();
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001923
Lorenzo Colittie3805462015-06-03 11:18:24 +09001924 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001925 pw.println();
1926 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001927 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001928 for(int i = 0; i < mInetLog.size(); i++) {
1929 pw.println(mInetLog.get(i));
1930 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001931 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001932 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001933
1934 if (argsContain(args, "--short") == false) {
1935 pw.println();
1936 synchronized (mValidationLogs) {
1937 pw.println("mValidationLogs (most recent first):");
1938 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1939 pw.println(p.first);
1940 pw.increaseIndent();
1941 p.second.dump(fd, pw, args);
1942 pw.decreaseIndent();
1943 }
1944 }
Erik Kline7523eb32015-07-09 18:24:03 +09001945
1946 pw.println();
1947 pw.println("mNetworkRequestInfoLogs (most recent first):");
1948 pw.increaseIndent();
1949 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1950 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 }
1953
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001954 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001955 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001956 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001957 if (officialNai != null && officialNai.equals(nai)) return true;
1958 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001959 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001960 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001961 " - " + nai);
1962 }
1963 return false;
1964 }
1965
Paul Jensenc8b9a742014-09-30 15:37:41 -04001966 private boolean isRequest(NetworkRequest request) {
Erik Kline371c7b72016-03-22 17:04:20 +09001967 return mNetworkRequests.get(request).isRequest();
Paul Jensenc8b9a742014-09-30 15:37:41 -04001968 }
1969
Robert Greenwalt42acef32009-08-12 16:08:25 -07001970 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001971 private class NetworkStateTrackerHandler extends Handler {
1972 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001973 super(looper);
1974 }
1975
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001976 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001978 default:
1979 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001980 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001981 handleAsyncChannelHalfConnect(msg);
1982 break;
1983 }
1984 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1985 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1986 if (nai != null) nai.asyncChannel.disconnect();
1987 break;
1988 }
1989 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1990 handleAsyncChannelDisconnected(msg);
1991 break;
1992 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001993 }
1994 return true;
1995 }
1996
1997 private void maybeHandleNetworkAgentMessage(Message msg) {
1998 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1999 if (nai == null) {
2000 if (VDBG) {
2001 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2002 log(String.format("%s from unknown NetworkAgent", what));
2003 }
2004 return;
2005 }
2006
2007 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002008 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002009 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2010 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2011 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2012 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002013 }
Robin Lee585e2482016-05-01 23:00:00 +01002014 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002015 networkCapabilities)) {
2016 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2017 + nai.networkCapabilities + " -> " + networkCapabilities);
2018 }
2019 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002020 break;
2021 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002022 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002023 if (VDBG) {
2024 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002025 "; created=" + nai.created +
2026 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002027 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002028 LinkProperties oldLp = nai.linkProperties;
2029 synchronized (nai) {
2030 nai.linkProperties = (LinkProperties)msg.obj;
2031 }
Robin Lee585e2482016-05-01 23:00:00 +01002032 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002033 break;
2034 }
2035 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002036 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002037 updateNetworkInfo(nai, info);
2038 break;
2039 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002040 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002041 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002042 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002043 break;
2044 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002045 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002046 try {
2047 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002048 } catch (Exception e) {
2049 // Never crash!
2050 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002051 }
2052 break;
2053 }
2054 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002055 try {
2056 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002057 } catch (Exception e) {
2058 // Never crash!
2059 loge("Exception in removeVpnUidRanges: " + e);
2060 }
2061 break;
2062 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002063 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002064 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2065 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002066 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002067 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002068 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002069 break;
2070 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002071 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002072 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2073 break;
2074 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002075 }
2076 }
2077
2078 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2079 switch (msg.what) {
2080 default:
2081 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002082 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002083 final NetworkAgentInfo nai;
2084 synchronized (mNetworkForNetId) {
2085 nai = mNetworkForNetId.get(msg.arg2);
2086 }
2087 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002088 final boolean valid =
2089 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen232437312016-04-06 09:51:26 -04002090 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2091 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002092 if (valid != nai.lastValidated) {
2093 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002094 nai.lastValidated = valid;
2095 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002096 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002097 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2098 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002099 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002100 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002101 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002102 Bundle redirectUrlBundle = new Bundle();
2103 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002104 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002105 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002106 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002107 0, redirectUrlBundle);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002108 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002109 break;
2110 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002111 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002112 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002113 if (isLiveNetworkAgent(nai, msg.what)) {
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002114 handleLingerComplete(nai);
2115 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002116 break;
2117 }
Paul Jensen869868be2014-05-15 10:33:05 -04002118 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002119 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002120 final boolean visible = (msg.arg1 != 0);
2121 final NetworkAgentInfo nai;
2122 synchronized (mNetworkForNetId) {
2123 nai = mNetworkForNetId.get(netId);
2124 }
2125 // If captive portal status has changed, update capabilities.
2126 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2127 nai.lastCaptivePortalDetected = visible;
2128 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002129 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002130 }
2131 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002132 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002133 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002134 if (nai == null) {
2135 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2136 break;
2137 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002138 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002139 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2140 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002141 }
Paul Jensen869868be2014-05-15 10:33:05 -04002142 break;
2143 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002144 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002145 return true;
2146 }
2147
2148 @Override
2149 public void handleMessage(Message msg) {
2150 if (!maybeHandleAsyncChannelMessage(msg) && !maybeHandleNetworkMonitorMessage(msg)) {
2151 maybeHandleNetworkAgentMessage(msg);
2152 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002153 }
2154 }
2155
Paul Jensen85cf78e2015-06-25 13:25:07 -04002156 private void linger(NetworkAgentInfo nai) {
2157 nai.lingering = true;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002158 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_LINGER);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002159 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2160 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2161 }
2162
Paul Jensen0cc17322014-11-25 15:26:53 -05002163 // Cancel any lingering so the linger timeout doesn't teardown a network.
2164 // This should be called when a network begins satisfying a NetworkRequest.
2165 // Note: depending on what state the NetworkMonitor is in (e.g.,
2166 // if it's awaiting captive portal login, or if validation failed), this
2167 // may trigger a re-evaluation of the network.
2168 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002169 nai.networkLingered.clear();
2170 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002171 nai.lingering = false;
Hugo Benichicc92c6e2016-04-21 15:02:38 +09002172 NetworkEvent.logEvent(nai.network.netId, NetworkEvent.NETWORK_UNLINGER);
Paul Jensen0cc17322014-11-25 15:26:53 -05002173 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002174 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2175 }
2176
Robert Greenwalt7b816022014-04-18 15:25:25 -07002177 private void handleAsyncChannelHalfConnect(Message msg) {
2178 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002179 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002180 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2181 if (VDBG) log("NetworkFactory connected");
2182 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002183 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Erik Kline371c7b72016-03-22 17:04:20 +09002184 if (!nri.isRequest()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002185 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002186 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002187 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002188 }
2189 } else {
2190 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002191 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002192 }
2193 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2194 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2195 if (VDBG) log("NetworkAgent connected");
2196 // A network agent has requested a connection. Establish the connection.
2197 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2198 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2199 } else {
2200 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002201 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002202 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002203 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002204 synchronized (mNetworkForNetId) {
2205 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002206 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002207 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002208 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002209 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002210 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002211 }
2212 }
2213 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002214
Robert Greenwalt7b816022014-04-18 15:25:25 -07002215 private void handleAsyncChannelDisconnected(Message msg) {
2216 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2217 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002218 if (DBG) {
2219 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2220 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002221 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002222 // TODO - if we move the logic to the network agent (have them disconnect
2223 // because they lost all their requests or because their score isn't good)
2224 // then they would disconnect organically, report their new state and then
2225 // disconnect the channel.
2226 if (nai.networkInfo.isConnected()) {
2227 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2228 null, null);
2229 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002230 final boolean wasDefault = isDefaultNetwork(nai);
2231 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002232 mDefaultInetConditionPublished = 0;
2233 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002234 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002235 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2236 // by other networks that are already connected. Perhaps that can be done by
2237 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2238 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002239 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002240 mKeepaliveTracker.handleStopAllKeepalives(nai,
2241 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002242 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002243 mNetworkAgentInfos.remove(msg.replyTo);
2244 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002245 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002246 // Remove the NetworkAgent, but don't mark the netId as
2247 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002248 mNetworkForNetId.remove(nai.network.netId);
2249 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002250 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002251 for (int i = 0; i < nai.networkRequests.size(); i++) {
2252 NetworkRequest request = nai.networkRequests.valueAt(i);
2253 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2254 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2255 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002256 sendUpdatedScoreToFactories(request, 0);
2257 }
2258 }
2259 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2260 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002261 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002262 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002263 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002264 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002265 rematchAllNetworksAndRequests(null, 0);
Pierre Imai04e222252016-04-12 18:02:58 +09002266 if (wasDefault && getDefaultNetwork() == null) {
2267 // Log that we lost the default network and there is no replacement.
Hugo Benichi5f16f762016-04-20 12:09:33 +09002268 logDefaultNetworkEvent(null, nai);
Pierre Imai04e222252016-04-12 18:02:58 +09002269 }
Paul Jensen62d30802015-06-17 14:42:30 -04002270 if (nai.created) {
2271 // Tell netd to clean up the configuration for this network
2272 // (routing rules, DNS, etc).
2273 // This may be slow as it requires a lot of netd shelling out to ip and
2274 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2275 // after we've rematched networks with requests which should make a potential
2276 // fallback network the default or requested a new network from the
2277 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2278 // long time.
2279 try {
2280 mNetd.removeNetwork(nai.network.netId);
2281 } catch (Exception e) {
2282 loge("Exception removing network: " + e);
2283 }
2284 }
2285 synchronized (mNetworkForNetId) {
2286 mNetIdInUse.delete(nai.network.netId);
2287 }
2288 } else {
2289 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2290 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002291 }
2292 }
2293
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002294 // If this method proves to be too slow then we can maintain a separate
2295 // pendingIntent => NetworkRequestInfo map.
2296 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2297 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2298 Intent intent = pendingIntent.getIntent();
2299 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2300 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2301 if (existingPendingIntent != null &&
2302 existingPendingIntent.getIntent().filterEquals(intent)) {
2303 return entry.getValue();
2304 }
2305 }
2306 return null;
2307 }
2308
2309 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2310 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2311
2312 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2313 if (existingRequest != null) { // remove the existing request.
2314 if (DBG) log("Replacing " + existingRequest.request + " with "
2315 + nri.request + " because their intents matched.");
2316 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2317 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002318 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002319 }
2320
Erik Klineda4bfa82015-04-30 12:58:40 +09002321 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002322 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002323 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002324 if (!nri.isRequest()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002325 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002326 if (nri.request.networkCapabilities.hasSignalStrength() &&
2327 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2328 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002329 }
2330 }
2331 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002332 rematchAllNetworksAndRequests(null, 0);
Erik Kline371c7b72016-03-22 17:04:20 +09002333 if (nri.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002334 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002335 }
2336 }
2337
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002338 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2339 int callingUid) {
2340 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2341 if (nri != null) {
2342 handleReleaseNetworkRequest(nri.request, callingUid);
2343 }
2344 }
2345
Paul Jensen99364842014-12-09 11:43:45 -05002346 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002347 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2348 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002349 private boolean unneeded(NetworkAgentInfo nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002350 if (!nai.everConnected || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002351 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2352 // If this Network is already the highest scoring Network for a request, or if
2353 // there is hope for it to become one if it validated, then it is needed.
Erik Kline371c7b72016-03-22 17:04:20 +09002354 if (nri.isRequest() && nai.satisfies(nri.request) &&
Paul Jensene0988542015-06-25 15:30:08 -04002355 (nai.networkRequests.get(nri.request.requestId) != null ||
2356 // Note that this catches two important cases:
2357 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2358 // is currently satisfying the request. This is desirable when
2359 // cellular ends up validating but WiFi does not.
2360 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002361 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002362 // WiFi ends up validating and out scoring cellular.
2363 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2364 nai.getCurrentScoreAsValidated())) {
2365 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002366 }
2367 }
Paul Jensene0988542015-06-25 15:30:08 -04002368 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002369 }
2370
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002371 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2372 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002373 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002374 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002375 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2376 return;
2377 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002378 if (VDBG || (DBG && nri.isRequest())) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002379 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002380 mNetworkRequests.remove(request);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002381 synchronized (mUidToNetworkRequestCount) {
2382 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2383 if (requests < 1) {
2384 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2385 nri.mUid);
2386 } else if (requests == 1) {
2387 mUidToNetworkRequestCount.removeAt(
2388 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2389 } else {
2390 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2391 }
2392 }
Erik Kline7523eb32015-07-09 18:24:03 +09002393 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Erik Kline371c7b72016-03-22 17:04:20 +09002394 if (nri.isRequest()) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002395 // Find all networks that are satisfying this request and remove the request
2396 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002397 // TODO - it's my understanding that for a request there is only a single
2398 // network satisfying it, so this loop is wasteful
2399 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002400 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2401 if (nai.networkRequests.get(nri.request.requestId) != null) {
2402 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002403 if (VDBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002404 log(" Removing from current network " + nai.name() +
2405 ", leaving " + nai.networkRequests.size() +
2406 " requests.");
2407 }
Paul Jensen99364842014-12-09 11:43:45 -05002408 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002409 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002410 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002411 } else {
2412 // suspect there should only be one pass through here
2413 // but if any were kept do the check below
2414 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002415 }
2416 }
2417 }
2418
Robert Greenwalt51481852015-01-08 14:43:31 -08002419 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2420 if (nai != null) {
2421 mNetworkForRequestId.remove(nri.request.requestId);
2422 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002423 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002424 // that a network connected to serve it, even though the network was already
2425 // connected. Now that this request has gone away, we might have to pretend
2426 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002427 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002428 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2429 boolean doRemove = true;
2430 if (wasKept) {
2431 // check if any of the remaining requests for this network are for the
2432 // same legacy type - if so, don't remove the nai
2433 for (int i = 0; i < nai.networkRequests.size(); i++) {
2434 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2435 if (otherRequest.legacyType == nri.request.legacyType &&
2436 isRequest(otherRequest)) {
2437 if (DBG) log(" still have other legacy request - leaving");
2438 doRemove = false;
2439 }
2440 }
2441 }
2442
2443 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002444 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002445 }
2446 }
2447
Robert Greenwalta67be032014-05-16 15:49:14 -07002448 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002449 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2450 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002451 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002452 } else {
2453 // listens don't have a singular affectedNetwork. Check all networks to see
2454 // if this listen request applies and remove it.
2455 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2456 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002457 if (nri.request.networkCapabilities.hasSignalStrength() &&
2458 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2459 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002460 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002461 }
2462 }
2463 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2464 }
2465 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002466
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002467 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2468 enforceConnectivityInternalPermission();
2469 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2470 accept ? 1 : 0, always ? 1: 0, network));
2471 }
2472
2473 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2474 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2475 " accept=" + accept + " always=" + always);
2476
2477 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2478 if (nai == null) {
2479 // Nothing to do.
2480 return;
2481 }
2482
2483 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002484 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002485 return;
2486 }
2487
2488 if (!nai.networkMisc.explicitlySelected) {
2489 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2490 }
2491
2492 if (accept != nai.networkMisc.acceptUnvalidated) {
2493 int oldScore = nai.getCurrentScore();
2494 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002495 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002496 sendUpdatedScoreToFactories(nai);
2497 }
2498
2499 if (always) {
2500 nai.asyncChannel.sendMessage(
2501 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2502 }
2503
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002504 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002505 // Tell the NetworkAgent to not automatically reconnect to the network.
2506 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2507 // Teardown the nework.
2508 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002509 }
2510
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002511 }
2512
2513 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002514 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002515 mHandler.sendMessageDelayed(
2516 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2517 PROMPT_UNVALIDATED_DELAY_MS);
2518 }
2519
2520 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002521 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002522 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2523
2524 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2525 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002526 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002527 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002528 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2529 return;
2530 }
2531
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002532 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002533 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002534 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2535 intent.setClassName("com.android.settings",
2536 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002537
2538 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2539 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2540 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002541 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002542 }
2543
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002544 private class InternalHandler extends Handler {
2545 public InternalHandler(Looper looper) {
2546 super(looper);
2547 }
2548
2549 @Override
2550 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002551 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002552 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002553 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002554 String causedBy = null;
2555 synchronized (ConnectivityService.this) {
2556 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2557 mNetTransitionWakeLock.isHeld()) {
2558 mNetTransitionWakeLock.release();
2559 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002560 } else {
2561 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002562 }
2563 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002564 if (VDBG) {
2565 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2566 log("Failed to find a new network - expiring NetTransition Wakelock");
2567 } else {
2568 log("NetTransition Wakelock (" +
2569 (causedBy == null ? "unknown" : causedBy) +
2570 " cleared because we found a replacement network");
2571 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002572 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002573 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002574 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002575 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002576 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002577 break;
2578 }
Jason Monkdecd2952013-10-10 14:02:51 -04002579 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002580 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002581 break;
2582 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002583 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002584 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2585 break;
2586 }
2587 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2588 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002589 break;
2590 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002591 case EVENT_REGISTER_NETWORK_AGENT: {
2592 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2593 break;
2594 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002595 case EVENT_REGISTER_NETWORK_REQUEST:
2596 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002597 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002598 break;
2599 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002600 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2601 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002602 handleRegisterNetworkRequestWithIntent(msg);
2603 break;
2604 }
2605 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2606 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2607 break;
2608 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002609 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002610 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002611 break;
2612 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002613 case EVENT_SET_ACCEPT_UNVALIDATED: {
2614 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2615 break;
2616 }
2617 case EVENT_PROMPT_UNVALIDATED: {
2618 handlePromptUnvalidated((Network) msg.obj);
2619 break;
2620 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002621 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2622 handleMobileDataAlwaysOn();
2623 break;
2624 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002625 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2626 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2627 mKeepaliveTracker.handleStartKeepalive(msg);
2628 break;
2629 }
2630 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2631 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2632 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2633 int slot = msg.arg1;
2634 int reason = msg.arg2;
2635 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2636 break;
2637 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002638 case EVENT_SYSTEM_READY: {
2639 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2640 nai.networkMonitor.systemReady = true;
2641 }
2642 break;
2643 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002644 }
2645 }
2646 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002647
2648 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002649 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002650 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002651 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002652 final int status = mTethering.tether(iface);
2653 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2654 try {
2655 mPolicyManager.onTetheringChanged(iface, true);
2656 } catch (RemoteException e) {
2657 }
2658 }
2659 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002660 } else {
2661 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2662 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002663 }
2664
2665 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002666 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002667 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002668
2669 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002670 final int status = mTethering.untether(iface);
2671 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2672 try {
2673 mPolicyManager.onTetheringChanged(iface, false);
2674 } catch (RemoteException e) {
2675 }
2676 }
2677 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002678 } else {
2679 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2680 }
2681 }
2682
2683 // javadoc from interface
2684 public int getLastTetherError(String iface) {
2685 enforceTetherAccessPermission();
2686
2687 if (isTetheringSupported()) {
2688 return mTethering.getLastTetherError(iface);
2689 } else {
2690 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2691 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002692 }
2693
2694 // TODO - proper iface API for selection by property, inspection, etc
2695 public String[] getTetherableUsbRegexs() {
2696 enforceTetherAccessPermission();
2697 if (isTetheringSupported()) {
2698 return mTethering.getTetherableUsbRegexs();
2699 } else {
2700 return new String[0];
2701 }
2702 }
2703
2704 public String[] getTetherableWifiRegexs() {
2705 enforceTetherAccessPermission();
2706 if (isTetheringSupported()) {
2707 return mTethering.getTetherableWifiRegexs();
2708 } else {
2709 return new String[0];
2710 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002711 }
2712
Danica Chang6fdd0c62010-08-11 14:54:43 -07002713 public String[] getTetherableBluetoothRegexs() {
2714 enforceTetherAccessPermission();
2715 if (isTetheringSupported()) {
2716 return mTethering.getTetherableBluetoothRegexs();
2717 } else {
2718 return new String[0];
2719 }
2720 }
2721
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002722 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002723 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002724 if (isTetheringSupported()) {
2725 return mTethering.setUsbTethering(enable);
2726 } else {
2727 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2728 }
2729 }
2730
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002731 // TODO - move iface listing, queries, etc to new module
2732 // javadoc from interface
2733 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002734 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002735 return mTethering.getTetherableIfaces();
2736 }
2737
2738 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002739 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002740 return mTethering.getTetheredIfaces();
2741 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002742
Robert Greenwalt5a735062010-03-02 17:25:02 -08002743 public String[] getTetheringErroredIfaces() {
2744 enforceTetherAccessPermission();
2745 return mTethering.getErroredIfaces();
2746 }
2747
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002748 public String[] getTetheredDhcpRanges() {
2749 enforceConnectivityInternalPermission();
2750 return mTethering.getTetheredDhcpRanges();
2751 }
2752
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002753 // if ro.tether.denied = true we default to no tethering
2754 // gservices could set the secure setting to 1 though to enable it on a build where it
2755 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002756 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002757 public boolean isTetheringSupported() {
2758 enforceTetherAccessPermission();
2759 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002760 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002761 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2762 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002763 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
2764 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002765 mTethering.getTetherableWifiRegexs().length != 0 ||
2766 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2767 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002768 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002769
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002770 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002771 public void startTethering(int type, ResultReceiver receiver,
2772 boolean showProvisioningUi) {
2773 ConnectivityManager.enforceTetherChangePermission(mContext);
2774 if (!isTetheringSupported()) {
2775 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2776 return;
2777 }
2778 mTethering.startTethering(type, receiver, showProvisioningUi);
2779 }
2780
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002781 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002782 public void stopTethering(int type) {
2783 ConnectivityManager.enforceTetherChangePermission(mContext);
2784 mTethering.stopTethering(type);
2785 }
2786
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002787 // Called when we lose the default network and have no replacement yet.
2788 // This will automatically be cleared after X seconds or a new default network
2789 // becomes CONNECTED, whichever happens first. The timer is started by the
2790 // first caller and not restarted by subsequent callers.
2791 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002792 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002793 synchronized (this) {
2794 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002795 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002796 mNetTransitionWakeLock.acquire();
2797 mNetTransitionWakeLockCausedBy = forWhom;
2798 }
2799 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002800 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002801 mNetTransitionWakeLockTimeout);
2802 return;
2803 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002804
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002805 // 100 percent is full good, 0 is full bad.
2806 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002807 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002808 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002809 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002810 }
2811
Paul Jensenbfd17b72015-04-07 12:43:13 -04002812 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002813 enforceAccessPermission();
2814 enforceInternetPermission();
2815
Paul Jensenbfd17b72015-04-07 12:43:13 -04002816 NetworkAgentInfo nai;
2817 if (network == null) {
2818 nai = getDefaultNetwork();
2819 } else {
2820 nai = getNetworkAgentInfoForNetwork(network);
2821 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002822 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2823 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2824 return;
2825 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002826 // Revalidate if the app report does not match our current validated state.
2827 if (hasConnectivity == nai.lastValidated) return;
2828 final int uid = Binder.getCallingUid();
2829 if (DBG) {
2830 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2831 ") by " + uid);
2832 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002833 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01002834 // Validating a network that has not yet connected could result in a call to
2835 // rematchNetworkAndRequests() which is not meant to work on such networks.
2836 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04002837
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002838 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002839
2840 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2841 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002842 }
2843
Paul Jensencee9b512015-05-06 07:32:40 -04002844 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002845 // this information is already available as a world read/writable jvm property
2846 // so this API change wouldn't have a benifit. It also breaks the passing
2847 // of proxy info to all the JVMs.
2848 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002849 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002850 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002851 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2852 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002853 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002854 }
2855
Paul Jensencee9b512015-05-06 07:32:40 -04002856 public ProxyInfo getProxyForNetwork(Network network) {
2857 if (network == null) return getDefaultProxy();
2858 final ProxyInfo globalProxy = getGlobalProxy();
2859 if (globalProxy != null) return globalProxy;
2860 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2861 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2862 // caller may not have.
2863 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2864 if (nai == null) return null;
2865 synchronized (nai) {
2866 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2867 if (proxyInfo == null) return null;
2868 return new ProxyInfo(proxyInfo);
2869 }
2870 }
2871
Paul Jensene0bef712014-12-10 15:12:18 -05002872 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2873 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2874 // proxy is null then there is no proxy in place).
2875 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2876 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2877 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2878 proxy = null;
2879 }
2880 return proxy;
2881 }
2882
2883 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2884 // better for determining if a new proxy broadcast is necessary:
2885 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2886 // avoid unnecessary broadcasts.
2887 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2888 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2889 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2890 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2891 // all set.
2892 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2893 a = canonicalizeProxyInfo(a);
2894 b = canonicalizeProxyInfo(b);
2895 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2896 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2897 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2898 }
2899
Jason Monk207900c2014-04-25 15:00:09 -04002900 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002901 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002902
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002903 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002904 if (proxyProperties == mGlobalProxy) return;
2905 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2906 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2907
2908 String host = "";
2909 int port = 0;
2910 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002911 String pacFileUrl = "";
2912 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002913 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002914 if (!proxyProperties.isValid()) {
2915 if (DBG)
2916 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2917 return;
2918 }
Jason Monk207900c2014-04-25 15:00:09 -04002919 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002920 host = mGlobalProxy.getHost();
2921 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002922 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002923 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002924 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002925 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002926 } else {
2927 mGlobalProxy = null;
2928 }
2929 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002930 final long token = Binder.clearCallingIdentity();
2931 try {
2932 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2933 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2934 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2935 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002936 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002937 } finally {
2938 Binder.restoreCallingIdentity(token);
2939 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002940
Jason Monkcf0f97a2014-10-02 15:39:38 -04002941 if (mGlobalProxy == null) {
2942 proxyProperties = mDefaultProxy;
2943 }
2944 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002945 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002946 }
2947
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002948 private void loadGlobalProxy() {
2949 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002950 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2951 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2952 String exclList = Settings.Global.getString(res,
2953 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002954 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2955 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002956 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002957 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002958 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002959 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002960 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002961 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002962 if (!proxyProperties.isValid()) {
2963 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2964 return;
2965 }
2966
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002967 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002968 mGlobalProxy = proxyProperties;
2969 }
2970 }
2971 }
2972
Jason Monk207900c2014-04-25 15:00:09 -04002973 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002974 // this information is already available as a world read/writable jvm property
2975 // so this API change wouldn't have a benifit. It also breaks the passing
2976 // of proxy info to all the JVMs.
2977 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002978 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002979 return mGlobalProxy;
2980 }
2981 }
2982
Jason Monk207900c2014-04-25 15:00:09 -04002983 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002984 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002985 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002986 proxy = null;
2987 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002988 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002989 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002990 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002991 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002992 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2993 return;
2994 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002995
2996 // This call could be coming from the PacManager, containing the port of the local
2997 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2998 // global (to get the correct local port), and send a broadcast.
2999 // TODO: Switch PacManager to have its own message to send back rather than
3000 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003001 if ((mGlobalProxy != null) && (proxy != null)
3002 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003003 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3004 mGlobalProxy = proxy;
3005 sendProxyBroadcast(mGlobalProxy);
3006 return;
3007 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003008 mDefaultProxy = proxy;
3009
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003010 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003011 if (!mDefaultProxyDisabled) {
3012 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003013 }
3014 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003015 }
3016
Paul Jensene0bef712014-12-10 15:12:18 -05003017 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3018 // This method gets called when any network changes proxy, but the broadcast only ever contains
3019 // the default proxy (even if it hasn't changed).
3020 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3021 // world where an app might be bound to a non-default network.
3022 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3023 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3024 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3025
3026 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3027 sendProxyBroadcast(getDefaultProxy());
3028 }
3029 }
3030
Robert Greenwalt434203a2010-10-11 16:00:27 -07003031 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003032 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3033 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003034 if (!TextUtils.isEmpty(proxy)) {
3035 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003036 if (data.length == 0) {
3037 return;
3038 }
3039
Robert Greenwalt434203a2010-10-11 16:00:27 -07003040 String proxyHost = data[0];
3041 int proxyPort = 8080;
3042 if (data.length > 1) {
3043 try {
3044 proxyPort = Integer.parseInt(data[1]);
3045 } catch (NumberFormatException e) {
3046 return;
3047 }
3048 }
Jason Monk207900c2014-04-25 15:00:09 -04003049 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003050 setGlobalProxy(p);
3051 }
3052 }
3053
Jason Monk207900c2014-04-25 15:00:09 -04003054 private void sendProxyBroadcast(ProxyInfo proxy) {
3055 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003056 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003057 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003058 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003059 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3060 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003061 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003062 final long ident = Binder.clearCallingIdentity();
3063 try {
3064 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3065 } finally {
3066 Binder.restoreCallingIdentity(ident);
3067 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003068 }
3069
3070 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003071 final private HashMap<Uri, Integer> mUriEventMap;
3072 final private Context mContext;
3073 final private Handler mHandler;
3074
3075 SettingsObserver(Context context, Handler handler) {
3076 super(null);
3077 mUriEventMap = new HashMap<Uri, Integer>();
3078 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003079 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003080 }
3081
Erik Klineda4bfa82015-04-30 12:58:40 +09003082 void observe(Uri uri, int what) {
3083 mUriEventMap.put(uri, what);
3084 final ContentResolver resolver = mContext.getContentResolver();
3085 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003086 }
3087
3088 @Override
3089 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003090 Slog.wtf(TAG, "Should never be reached.");
3091 }
3092
3093 @Override
3094 public void onChange(boolean selfChange, Uri uri) {
3095 final Integer what = mUriEventMap.get(uri);
3096 if (what != null) {
3097 mHandler.obtainMessage(what.intValue()).sendToTarget();
3098 } else {
3099 loge("No matching event to send for URI=" + uri);
3100 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003101 }
3102 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003103
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003104 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003105 Slog.d(TAG, s);
3106 }
3107
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003108 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003109 Slog.e(TAG, s);
3110 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003111
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003112 private static <T> T checkNotNull(T value, String message) {
3113 if (value == null) {
3114 throw new NullPointerException(message);
3115 }
3116 return value;
3117 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003118
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003119 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003120 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003121 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3122 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3123 *
3124 * @param oldPackage Package name of the application which currently controls VPN, which will
3125 * be replaced. If there is no such application, this should should either be
3126 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3127 * @param newPackage Package name of the application which should gain control of VPN, or
3128 * {@code null} to disable.
3129 * @param userId User for whom to prepare the new VPN.
3130 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003131 * @hide
3132 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003133 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003134 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3135 int userId) {
3136 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003137 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003138
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003139 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003140 Vpn vpn = mVpns.get(userId);
3141 if (vpn != null) {
3142 return vpn.prepare(oldPackage, newPackage);
3143 } else {
3144 return false;
3145 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003146 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003147 }
3148
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003149 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003150 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3151 * This method is used by system-privileged apps.
3152 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3153 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3154 *
3155 * @param packageName The package for which authorization state should change.
3156 * @param userId User for whom {@code packageName} is installed.
3157 * @param authorized {@code true} if this app should be able to start a VPN connection without
3158 * explicit user approval, {@code false} if not.
3159 *
Jeff Davidson05542602014-08-11 14:07:27 -07003160 * @hide
3161 */
3162 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003163 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3164 enforceCrossUserPermission(userId);
3165
Jeff Davidson05542602014-08-11 14:07:27 -07003166 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003167 Vpn vpn = mVpns.get(userId);
3168 if (vpn != null) {
3169 vpn.setPackageAuthorization(packageName, authorized);
3170 }
Jeff Davidson05542602014-08-11 14:07:27 -07003171 }
3172 }
3173
3174 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003175 * Configure a TUN interface and return its file descriptor. Parameters
3176 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003177 * and not available in ConnectivityManager. Permissions are checked in
3178 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003179 * @hide
3180 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003181 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003182 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003183 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003184 int user = UserHandle.getUserId(Binder.getCallingUid());
3185 synchronized(mVpns) {
3186 return mVpns.get(user).establish(config);
3187 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003188 }
3189
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003190 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003191 * Start legacy VPN, controlling native daemons as needed. Creates a
3192 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003193 */
3194 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003195 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003196 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003197 final LinkProperties egress = getActiveLinkProperties();
3198 if (egress == null) {
3199 throw new IllegalStateException("Missing active network connection");
3200 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003201 int user = UserHandle.getUserId(Binder.getCallingUid());
3202 synchronized(mVpns) {
3203 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3204 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003205 }
3206
3207 /**
3208 * Return the information of the ongoing legacy VPN. This method is used
3209 * by VpnSettings and not available in ConnectivityManager. Permissions
3210 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003211 */
3212 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003213 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3214 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003215 if (mLockdownEnabled) {
3216 return null;
3217 }
3218
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003219 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003220 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003221 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003222 }
3223
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003224 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003225 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3226 * and not available in ConnectivityManager.
3227 */
3228 @Override
3229 public VpnInfo[] getAllVpnInfo() {
3230 enforceConnectivityInternalPermission();
3231 if (mLockdownEnabled) {
3232 return new VpnInfo[0];
3233 }
3234
3235 synchronized(mVpns) {
3236 List<VpnInfo> infoList = new ArrayList<>();
3237 for (int i = 0; i < mVpns.size(); i++) {
3238 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3239 if (info != null) {
3240 infoList.add(info);
3241 }
3242 }
3243 return infoList.toArray(new VpnInfo[infoList.size()]);
3244 }
3245 }
3246
3247 /**
3248 * @return VPN information for accounting, or null if we can't retrieve all required
3249 * information, e.g primary underlying iface.
3250 */
3251 @Nullable
3252 private VpnInfo createVpnInfo(Vpn vpn) {
3253 VpnInfo info = vpn.getVpnInfo();
3254 if (info == null) {
3255 return null;
3256 }
3257 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3258 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3259 // the underlyingNetworks list.
3260 if (underlyingNetworks == null) {
3261 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3262 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3263 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3264 }
3265 } else if (underlyingNetworks.length > 0) {
3266 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3267 if (linkProperties != null) {
3268 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3269 }
3270 }
3271 return info.primaryUnderlyingIface == null ? null : info;
3272 }
3273
3274 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003275 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3276 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003277 * Permissions are checked in Vpn class.
3278 * @hide
3279 */
3280 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003281 public VpnConfig getVpnConfig(int userId) {
3282 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003283 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003284 Vpn vpn = mVpns.get(userId);
3285 if (vpn != null) {
3286 return vpn.getVpnConfig();
3287 } else {
3288 return null;
3289 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003290 }
3291 }
3292
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003293 @Override
3294 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003295 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3296 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3297 return false;
3298 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003299
3300 // Tear down existing lockdown if profile was removed
3301 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3302 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003303 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3304 final VpnProfile profile = VpnProfile.decode(
3305 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003306 if (profile == null) {
3307 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3308 setLockdownTracker(null);
3309 return true;
3310 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003311 int user = UserHandle.getUserId(Binder.getCallingUid());
3312 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003313 Vpn vpn = mVpns.get(user);
3314 if (vpn == null) {
3315 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3316 return false;
3317 }
3318 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003319 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003320 } else {
3321 setLockdownTracker(null);
3322 }
3323
3324 return true;
3325 }
3326
3327 /**
3328 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3329 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3330 */
3331 private void setLockdownTracker(LockdownVpnTracker tracker) {
3332 // Shutdown any existing tracker
3333 final LockdownVpnTracker existing = mLockdownTracker;
3334 mLockdownTracker = null;
3335 if (existing != null) {
3336 existing.shutdown();
3337 }
3338
3339 try {
3340 if (tracker != null) {
3341 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003342 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003343 mLockdownTracker = tracker;
3344 mLockdownTracker.init();
3345 } else {
3346 mNetd.setFirewallEnabled(false);
3347 }
3348 } catch (RemoteException e) {
3349 // ignored; NMS lives inside system_server
3350 }
3351 }
3352
3353 private void throwIfLockdownEnabled() {
3354 if (mLockdownEnabled) {
3355 throw new IllegalStateException("Unavailable in lockdown mode");
3356 }
3357 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003358
Robin Lee244ce8e2016-01-05 18:03:46 +00003359 /**
3360 * Sets up or tears down the always-on VPN for user {@param user} as appropriate.
3361 *
3362 * @return {@code false} in case of errors; {@code true} otherwise.
3363 */
3364 private boolean updateAlwaysOnVpn(int user) {
3365 final String lockdownPackage = getAlwaysOnVpnPackage(user);
3366 if (lockdownPackage == null) {
3367 return true;
3368 }
3369
3370 // Create an intent to start the VPN service declared in the app's manifest.
3371 Intent serviceIntent = new Intent(VpnConfig.SERVICE_INTERFACE);
3372 serviceIntent.setPackage(lockdownPackage);
3373
3374 try {
3375 return mContext.startServiceAsUser(serviceIntent, UserHandle.of(user)) != null;
3376 } catch (RuntimeException e) {
3377 return false;
3378 }
3379 }
3380
3381 @Override
Robin Leedc679712016-05-03 13:23:03 +01003382 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003383 enforceConnectivityInternalPermission();
3384 enforceCrossUserPermission(userId);
3385
3386 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3387 if (LockdownVpnTracker.isEnabled()) {
3388 return false;
3389 }
3390
3391 // If the current VPN package is the same as the new one, this is a no-op
3392 final String oldPackage = getAlwaysOnVpnPackage(userId);
3393 if (TextUtils.equals(oldPackage, packageName)) {
3394 return true;
3395 }
3396
3397 synchronized (mVpns) {
3398 Vpn vpn = mVpns.get(userId);
3399 if (vpn == null) {
3400 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3401 return false;
3402 }
3403 if (!vpn.setAlwaysOnPackage(packageName)) {
3404 return false;
3405 }
3406 if (!updateAlwaysOnVpn(userId)) {
3407 vpn.setAlwaysOnPackage(null);
3408 return false;
3409 }
3410 }
3411 return true;
3412 }
3413
3414 @Override
3415 public String getAlwaysOnVpnPackage(int userId) {
3416 enforceConnectivityInternalPermission();
3417 enforceCrossUserPermission(userId);
3418
3419 synchronized (mVpns) {
3420 Vpn vpn = mVpns.get(userId);
3421 if (vpn == null) {
3422 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3423 return null;
3424 }
3425 return vpn.getAlwaysOnPackage();
3426 }
3427 }
3428
Wink Savilleab9321d2013-06-29 21:10:57 -07003429 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003430 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003431 // TODO: Remove? Any reason to trigger a provisioning check?
3432 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003433 }
3434
3435 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003436 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003437
Paul Jensen89e0f092014-09-15 15:59:36 -04003438 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003439 Intent intent = new Intent(action);
3440 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003441 // Concatenate the range of types onto the range of NetIDs.
3442 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003443 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003444 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003445 }
3446
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003447 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003448 * Show or hide network provisioning notifications.
3449 *
3450 * We use notifications for two purposes: to notify that a network requires sign in
3451 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3452 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3453 * particular network we can display the notification type that was most recently requested.
3454 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3455 * might first display NO_INTERNET, and then when the captive portal check completes, display
3456 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003457 *
3458 * @param id an identifier that uniquely identifies this notification. This must match
3459 * between show and hide calls. We use the NetID value but for legacy callers
3460 * we concatenate the range of types with the range of NetIDs.
3461 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003462 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003463 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3464 boolean highPriority) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003465 if (VDBG || (DBG && visible)) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003466 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3467 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003468 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003469 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003470
3471 Resources r = Resources.getSystem();
3472 NotificationManager notificationManager = (NotificationManager) mContext
3473 .getSystemService(Context.NOTIFICATION_SERVICE);
3474
3475 if (visible) {
3476 CharSequence title;
3477 CharSequence details;
3478 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003479 if (notifyType == NotificationType.NO_INTERNET &&
3480 networkType == ConnectivityManager.TYPE_WIFI) {
3481 title = r.getString(R.string.wifi_no_internet, 0);
3482 details = r.getString(R.string.wifi_no_internet_detailed);
3483 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3484 } else if (notifyType == NotificationType.SIGN_IN) {
3485 switch (networkType) {
3486 case ConnectivityManager.TYPE_WIFI:
3487 title = r.getString(R.string.wifi_available_sign_in, 0);
3488 details = r.getString(R.string.network_available_sign_in_detailed,
3489 extraInfo);
3490 icon = R.drawable.stat_notify_wifi_in_range;
3491 break;
3492 case ConnectivityManager.TYPE_MOBILE:
3493 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3494 title = r.getString(R.string.network_available_sign_in, 0);
3495 // TODO: Change this to pull from NetworkInfo once a printable
3496 // name has been added to it
3497 details = mTelephonyManager.getNetworkOperatorName();
3498 icon = R.drawable.stat_notify_rssi_in_range;
3499 break;
3500 default:
3501 title = r.getString(R.string.network_available_sign_in, 0);
3502 details = r.getString(R.string.network_available_sign_in_detailed,
3503 extraInfo);
3504 icon = R.drawable.stat_notify_rssi_in_range;
3505 break;
3506 }
3507 } else {
3508 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3509 + getNetworkTypeName(networkType));
3510 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003511 }
3512
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003513 Notification notification = new Notification.Builder(mContext)
3514 .setWhen(0)
3515 .setSmallIcon(icon)
3516 .setAutoCancel(true)
3517 .setTicker(title)
3518 .setColor(mContext.getColor(
3519 com.android.internal.R.color.system_notification_accent_color))
3520 .setContentTitle(title)
3521 .setContentText(details)
3522 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003523 .setLocalOnly(true)
3524 .setPriority(highPriority ?
3525 Notification.PRIORITY_HIGH :
3526 Notification.PRIORITY_DEFAULT)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003527 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003528 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003529 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003530
Wink Saville948282b2013-08-29 08:55:16 -07003531 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003532 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003533 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003534 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003535 npe.printStackTrace();
3536 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003537 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003538 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003539 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003540 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003541 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003542 npe.printStackTrace();
3543 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003544 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003545 }
3546
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003547 /** Location to an updatable file listing carrier provisioning urls.
3548 * An example:
3549 *
3550 * <?xml version="1.0" encoding="utf-8"?>
3551 * <provisioningUrls>
3552 * <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 -07003553 * </provisioningUrls>
3554 */
3555 private static final String PROVISIONING_URL_PATH =
3556 "/data/misc/radio/provisioning_urls.xml";
3557 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003558
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003559 /** XML tag for root element. */
3560 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3561 /** XML tag for individual url */
3562 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003563 /** XML attribute for mcc */
3564 private static final String ATTR_MCC = "mcc";
3565 /** XML attribute for mnc */
3566 private static final String ATTR_MNC = "mnc";
3567
Paul Jensen434dde82015-06-11 09:43:30 -04003568 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003569 FileReader fileReader = null;
3570 XmlPullParser parser = null;
3571 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003572
3573 try {
3574 fileReader = new FileReader(mProvisioningUrlFile);
3575 parser = Xml.newPullParser();
3576 parser.setInput(fileReader);
3577 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3578
3579 while (true) {
3580 XmlUtils.nextElement(parser);
3581
3582 String element = parser.getName();
3583 if (element == null) break;
3584
Paul Jensen434dde82015-06-11 09:43:30 -04003585 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003586 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3587 try {
3588 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3589 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3590 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3591 parser.next();
3592 if (parser.getEventType() == XmlPullParser.TEXT) {
3593 return parser.getText();
3594 }
3595 }
3596 }
3597 } catch (NumberFormatException e) {
3598 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3599 }
3600 }
3601 }
3602 return null;
3603 } catch (FileNotFoundException e) {
3604 loge("Carrier Provisioning Urls file not found");
3605 } catch (XmlPullParserException e) {
3606 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3607 } catch (IOException e) {
3608 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3609 } finally {
3610 if (fileReader != null) {
3611 try {
3612 fileReader.close();
3613 } catch (IOException e) {}
3614 }
3615 }
3616 return null;
3617 }
3618
Wink Saville42d4f082013-07-20 20:31:59 -07003619 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003620 public String getMobileProvisioningUrl() {
3621 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003622 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003623 if (TextUtils.isEmpty(url)) {
3624 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003625 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003626 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003627 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003628 }
Wink Saville8cf35602013-07-10 23:00:07 -07003629 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003630 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003631 String phoneNumber = mTelephonyManager.getLine1Number();
3632 if (TextUtils.isEmpty(phoneNumber)) {
3633 phoneNumber = "0000000000";
3634 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003635 url = String.format(url,
3636 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3637 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003638 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003639 }
3640
Wink Savilleab9321d2013-06-29 21:10:57 -07003641 return url;
3642 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003643
Wink Saville948282b2013-08-29 08:55:16 -07003644 @Override
3645 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003646 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003647 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003648 final long ident = Binder.clearCallingIdentity();
3649 try {
3650 setProvNotificationVisible(visible, networkType, action);
3651 } finally {
3652 Binder.restoreCallingIdentity(ident);
3653 }
Wink Saville948282b2013-08-29 08:55:16 -07003654 }
Wink Saville7788c612013-08-29 14:57:08 -07003655
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003656 @Override
3657 public void setAirplaneMode(boolean enable) {
3658 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003659 final long ident = Binder.clearCallingIdentity();
3660 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003661 final ContentResolver cr = mContext.getContentResolver();
3662 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3663 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3664 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003665 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003666 } finally {
3667 Binder.restoreCallingIdentity(ident);
3668 }
3669 }
3670
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003671 private void onUserStart(int userId) {
3672 synchronized(mVpns) {
3673 Vpn userVpn = mVpns.get(userId);
3674 if (userVpn != null) {
3675 loge("Starting user already has a VPN");
3676 return;
3677 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003678 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003679 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003680 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003681 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3682 updateLockdownVpn();
3683 } else {
3684 updateAlwaysOnVpn(userId);
3685 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003686 }
3687
3688 private void onUserStop(int userId) {
3689 synchronized(mVpns) {
3690 Vpn userVpn = mVpns.get(userId);
3691 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003692 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003693 return;
3694 }
3695 mVpns.delete(userId);
3696 }
3697 }
3698
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003699 private void onUserAdded(int userId) {
3700 synchronized(mVpns) {
3701 final int vpnsSize = mVpns.size();
3702 for (int i = 0; i < vpnsSize; i++) {
3703 Vpn vpn = mVpns.valueAt(i);
3704 vpn.onUserAdded(userId);
3705 }
3706 }
3707 }
3708
3709 private void onUserRemoved(int userId) {
3710 synchronized(mVpns) {
3711 final int vpnsSize = mVpns.size();
3712 for (int i = 0; i < vpnsSize; i++) {
3713 Vpn vpn = mVpns.valueAt(i);
3714 vpn.onUserRemoved(userId);
3715 }
3716 }
3717 }
3718
Robin Lee89e7a692016-02-29 14:38:17 +00003719 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003720 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3721 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3722 updateLockdownVpn();
3723 } else {
3724 updateAlwaysOnVpn(userId);
3725 }
3726 }
3727
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003728 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3729 @Override
3730 public void onReceive(Context context, Intent intent) {
3731 final String action = intent.getAction();
3732 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3733 if (userId == UserHandle.USER_NULL) return;
3734
Robin Lee323f29d2016-05-04 16:38:06 +01003735 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003736 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003737 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003738 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003739 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3740 onUserAdded(userId);
3741 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3742 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003743 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3744 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003745 }
3746 }
3747 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003748
Robert Greenwalta67be032014-05-16 15:49:14 -07003749 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3750 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003751 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3752 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003753
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003754 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3755 // Map from UID to number of NetworkRequests that UID has filed.
3756 @GuardedBy("mUidToNetworkRequestCount")
3757 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3758
Robert Greenwalta67be032014-05-16 15:49:14 -07003759 private static class NetworkFactoryInfo {
3760 public final String name;
3761 public final Messenger messenger;
3762 public final AsyncChannel asyncChannel;
3763
3764 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3765 this.name = name;
3766 this.messenger = messenger;
3767 this.asyncChannel = asyncChannel;
3768 }
3769 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003770
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003771 /**
Erik Kline371c7b72016-03-22 17:04:20 +09003772 * A NetworkRequest as registered by an application can be one of three
3773 * types:
3774 *
3775 * - "listen", for which the framework will issue callbacks about any
3776 * and all networks that match the specified NetworkCapabilities,
3777 *
3778 * - "request", capable of causing a specific network to be created
3779 * first (e.g. a telephony DUN request), the framework will issue
3780 * callbacks about the single, highest scoring current network
3781 * (if any) that matches the specified NetworkCapabilities, or
3782 *
3783 * - "track the default network", a hybrid of the two designed such
3784 * that the framework will issue callbacks for the single, highest
3785 * scoring current network (if any) that matches the capabilities of
3786 * the default Internet request (mDefaultRequest), but which cannot
3787 * cause the framework to either create or retain the existence of
3788 * any specific network.
3789 *
3790 */
3791 private static enum NetworkRequestType {
3792 LISTEN,
3793 TRACK_DEFAULT,
3794 REQUEST
3795 };
3796
3797 /**
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003798 * Tracks info about the requester.
3799 * Also used to notice when the calling process dies so we can self-expire
3800 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003801 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003802 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003803 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003804 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003805 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003806 final int mPid;
3807 final int mUid;
3808 final Messenger messenger;
Erik Kline371c7b72016-03-22 17:04:20 +09003809 private final NetworkRequestType mType;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003810
Erik Kline371c7b72016-03-22 17:04:20 +09003811 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, NetworkRequestType type) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003812 request = r;
3813 mPendingIntent = pi;
3814 messenger = null;
3815 mBinder = null;
3816 mPid = getCallingPid();
3817 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003818 mType = type;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003819 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003820 }
3821
Erik Kline371c7b72016-03-22 17:04:20 +09003822 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, NetworkRequestType type) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003823 super();
3824 messenger = m;
3825 request = r;
3826 mBinder = binder;
3827 mPid = getCallingPid();
3828 mUid = getCallingUid();
Erik Kline371c7b72016-03-22 17:04:20 +09003829 mType = type;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003830 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003831 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003832
3833 try {
3834 mBinder.linkToDeath(this, 0);
3835 } catch (RemoteException e) {
3836 binderDied();
3837 }
3838 }
3839
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003840 private void enforceRequestCountLimit() {
3841 synchronized (mUidToNetworkRequestCount) {
3842 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3843 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3844 throw new IllegalArgumentException("Too many NetworkRequests filed");
3845 }
3846 mUidToNetworkRequestCount.put(mUid, networkRequests);
3847 }
3848 }
3849
Erik Kline371c7b72016-03-22 17:04:20 +09003850 private String typeString() {
3851 switch (mType) {
3852 case LISTEN: return "Listen";
3853 case REQUEST: return "Request";
3854 case TRACK_DEFAULT: return "Track default";
3855 default:
3856 return "unknown type";
3857 }
3858 }
3859
Robert Greenwalt9258c642014-03-26 16:47:06 -07003860 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003861 if (mBinder != null) {
3862 mBinder.unlinkToDeath(this, 0);
3863 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003864 }
3865
3866 public void binderDied() {
3867 log("ConnectivityService NetworkRequestInfo binderDied(" +
3868 request + ", " + mBinder + ")");
3869 releaseNetworkRequest(request);
3870 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003871
Erik Kline371c7b72016-03-22 17:04:20 +09003872 /**
3873 * Returns true iff. the contained NetworkRequest is one that:
3874 *
3875 * - should be associated with at most one satisfying network
3876 * at a time;
3877 *
3878 * - should cause a network to be kept up if it is the only network
3879 * which can satisfy the NetworkReqeust.
3880 *
3881 * For full detail of how isRequest() is used for pairing Networks with
3882 * NetworkRequests read rematchNetworkAndRequests().
3883 *
3884 * TODO: Rename to something more properly descriptive.
3885 */
3886 public boolean isRequest() {
3887 return (mType == NetworkRequestType.TRACK_DEFAULT) ||
3888 (mType == NetworkRequestType.REQUEST);
3889 }
3890
Robert Greenwalta67be032014-05-16 15:49:14 -07003891 public String toString() {
Erik Kline371c7b72016-03-22 17:04:20 +09003892 return typeString() +
Erik Kline7523eb32015-07-09 18:24:03 +09003893 " from uid/pid:" + mUid + "/" + mPid +
3894 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003895 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003896 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003897 }
3898
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003899 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3900 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3901 if (badCapability != null) {
3902 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003903 }
3904 }
3905
Erik Kline9d598e12015-07-13 16:37:51 +09003906 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003907 final SortedSet<Integer> thresholds = new TreeSet();
3908 synchronized (nai) {
3909 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3910 if (nri.request.networkCapabilities.hasSignalStrength() &&
3911 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3912 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3913 }
3914 }
3915 }
Erik Kline9d598e12015-07-13 16:37:51 +09003916 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003917 }
3918
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003919 private void updateSignalStrengthThresholds(
3920 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3921 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003922 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003923 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3924
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003925 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003926 String detail;
3927 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3928 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3929 } else {
3930 detail = reason;
3931 }
3932 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3933 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3934 }
3935
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003936 nai.asyncChannel.sendMessage(
3937 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003938 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003939 }
3940
Robert Greenwalt9258c642014-03-26 16:47:06 -07003941 @Override
3942 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003943 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Erik Kline371c7b72016-03-22 17:04:20 +09003944 final NetworkRequestType type = (networkCapabilities == null)
3945 ? NetworkRequestType.TRACK_DEFAULT
3946 : NetworkRequestType.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09003947 // If the requested networkCapabilities is null, take them instead from
3948 // the default network request. This allows callers to keep track of
3949 // the system default network.
Erik Kline371c7b72016-03-22 17:04:20 +09003950 if (type == NetworkRequestType.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09003951 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
3952 enforceAccessPermission();
3953 } else {
3954 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3955 enforceNetworkRequestPermissions(networkCapabilities);
3956 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003957 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003958 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003959
Robert Greenwalt6078b502014-06-11 16:05:07 -07003960 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003961 throw new IllegalArgumentException("Bad timeout specified");
3962 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003963
Etan Cohenddb9ef02015-11-18 10:56:15 -08003964 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
3965 .equals(networkCapabilities.getNetworkSpecifier())) {
3966 throw new IllegalArgumentException("Invalid network specifier - must not be '"
3967 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
3968 }
3969
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003970 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3971 nextNetworkRequestId());
Erik Kline371c7b72016-03-22 17:04:20 +09003972 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder, type);
Erik Kline7523eb32015-07-09 18:24:03 +09003973 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003974
3975 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003976 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003977 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003978 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003979 }
3980 return networkRequest;
3981 }
3982
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003983 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003984 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003985 enforceConnectivityInternalPermission();
3986 } else {
3987 enforceChangePermission();
3988 }
3989 }
3990
fenglub15e72b2015-03-20 11:29:56 -07003991 @Override
fengludb571472015-04-21 17:12:05 -07003992 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003993 enforceAccessPermission();
3994 NetworkAgentInfo nai = null;
3995 if (network == null) {
3996 return false;
3997 }
3998 synchronized (mNetworkForNetId) {
3999 nai = mNetworkForNetId.get(network.netId);
4000 }
4001 if (nai != null) {
4002 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4003 return true;
4004 }
4005 return false;
4006 }
4007
4008
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004009 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
4010 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004011 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004012 final int uidRules;
4013 final int uid = Binder.getCallingUid();
4014 synchronized(mRulesLock) {
4015 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4016 }
Felipe Lemed31a97f2016-05-06 14:53:50 -07004017 if ((uidRules & RULE_ALLOW_ALL) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004018 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004019 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004020 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004021 }
4022 }
4023 }
4024
Robert Greenwalt9258c642014-03-26 16:47:06 -07004025 @Override
4026 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4027 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004028 checkNotNull(operation, "PendingIntent cannot be null.");
4029 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4030 enforceNetworkRequestPermissions(networkCapabilities);
4031 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004032 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004033
4034 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
4035 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004036 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004037 NetworkRequestType.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09004038 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004039 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4040 nri));
4041 return networkRequest;
4042 }
4043
Jeremy Joslin79294842014-12-03 17:15:28 -08004044 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4045 mHandler.sendMessageDelayed(
4046 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4047 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4048 }
4049
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004050 @Override
4051 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004052 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004053 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4054 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004055 }
4056
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004057 // In order to implement the compatibility measure for pre-M apps that call
4058 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4059 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4060 // This ensures it has permission to do so.
4061 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4062 if (nc == null) {
4063 return false;
4064 }
4065 int[] transportTypes = nc.getTransportTypes();
4066 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4067 return false;
4068 }
4069 try {
4070 mContext.enforceCallingOrSelfPermission(
4071 android.Manifest.permission.ACCESS_WIFI_STATE,
4072 "ConnectivityService");
4073 } catch (SecurityException e) {
4074 return false;
4075 }
4076 return true;
4077 }
4078
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 @Override
4080 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4081 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004082 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4083 enforceAccessPermission();
4084 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004085
Erik Kline7523eb32015-07-09 18:24:03 +09004086 NetworkRequest networkRequest = new NetworkRequest(
4087 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004088 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
Erik Kline371c7b72016-03-22 17:04:20 +09004089 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004090 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004091
4092 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4093 return networkRequest;
4094 }
4095
4096 @Override
4097 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4098 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004099 checkNotNull(operation, "PendingIntent cannot be null.");
4100 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4101 enforceAccessPermission();
4102 }
4103
Erik Kline7523eb32015-07-09 18:24:03 +09004104 NetworkRequest networkRequest = new NetworkRequest(
4105 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04004106 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
Erik Kline371c7b72016-03-22 17:04:20 +09004107 NetworkRequestType.LISTEN);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004108 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004109
4110 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004111 }
4112
4113 @Override
4114 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04004115 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
4116 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 }
4118
4119 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004120 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004121 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004122 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4123 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004124 }
4125
Robert Greenwalta67be032014-05-16 15:49:14 -07004126 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004127 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004128 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4129 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4130 }
4131
4132 @Override
4133 public void unregisterNetworkFactory(Messenger messenger) {
4134 enforceConnectivityInternalPermission();
4135 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4136 }
4137
4138 private void handleUnregisterNetworkFactory(Messenger messenger) {
4139 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4140 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004141 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004142 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004143 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004144 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004145 }
4146
Robert Greenwalt7b816022014-04-18 15:25:25 -07004147 /**
4148 * NetworkAgentInfo supporting a request by requestId.
4149 * These have already been vetted (their Capabilities satisfy the request)
4150 * and the are the highest scored network available.
4151 * the are keyed off the Requests requestId.
4152 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004153 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004154 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4155 new SparseArray<NetworkAgentInfo>();
4156
Paul Jensen31a94f42015-02-13 14:18:39 -05004157 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4158 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004159 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4160 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004161 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4162 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4163 // there may not be a strict 1:1 correlation between the two.
4164 @GuardedBy("mNetworkForNetId")
4165 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004166
Robert Greenwalt7b816022014-04-18 15:25:25 -07004167 // NetworkAgentInfo keyed off its connecting messenger
4168 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004169 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004170 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4171 new HashMap<Messenger, NetworkAgentInfo>();
4172
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004173 @GuardedBy("mBlockedAppUids")
4174 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4175
Paul Jensen2c311d62014-11-17 12:34:51 -05004176 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004177 private final NetworkRequest mDefaultRequest;
4178
Erik Klineda4bfa82015-04-30 12:58:40 +09004179 // Request used to optionally keep mobile data active even when higher
4180 // priority networks like Wi-Fi are active.
4181 private final NetworkRequest mDefaultMobileDataRequest;
4182
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004183 private NetworkAgentInfo getDefaultNetwork() {
4184 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4185 }
4186
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004187 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004188 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004189 }
4190
Paul Jensen31a94f42015-02-13 14:18:39 -05004191 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004192 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004193 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004194 enforceConnectivityInternalPermission();
4195
Paul Jensen2c311d62014-11-17 12:34:51 -05004196 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4197 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004198 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004199 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4200 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004201 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004202 synchronized (this) {
4203 nai.networkMonitor.systemReady = mSystemReady;
4204 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07004205 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004206 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004207 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004208 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004209 }
4210
4211 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4212 if (VDBG) log("Got NetworkAgent Messenger");
4213 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004214 synchronized (mNetworkForNetId) {
4215 mNetworkForNetId.put(na.network.netId, na);
4216 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004217 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4218 NetworkInfo networkInfo = na.networkInfo;
4219 na.networkInfo = null;
4220 updateNetworkInfo(na, networkInfo);
4221 }
4222
4223 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4224 LinkProperties newLp = networkAgent.linkProperties;
4225 int netId = networkAgent.network.netId;
4226
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004227 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4228 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004229 if (networkAgent.clatd != null) {
4230 networkAgent.clatd.fixupLinkProperties(oldLp);
4231 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004232
Paul Jensen992f2522014-04-28 10:33:11 -04004233 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004234 updateMtu(newLp, oldLp);
4235 // TODO - figure out what to do for clat
4236// for (LinkProperties lp : newLp.getStackedLinks()) {
4237// updateMtu(lp, null);
4238// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004239 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004240
Erik Kline94887872016-04-05 13:30:49 +09004241 updateRoutes(newLp, oldLp, netId);
4242 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004243
Paul Jensen3b759822014-05-13 11:44:01 -04004244 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004245 if (isDefaultNetwork(networkAgent)) {
4246 handleApplyDefaultProxy(newLp.getHttpProxy());
4247 } else {
4248 updateProxy(newLp, oldLp, networkAgent);
4249 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004250 // TODO - move this check to cover the whole function
4251 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004252 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004253 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4254 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004255
4256 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004257 }
4258
Lorenzo Colitti95439462014-10-09 13:44:48 +09004259 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4260 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4261 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004262
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004263 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004264 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4265 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004266 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004267 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004268 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004269 }
Paul Jensen992f2522014-04-28 10:33:11 -04004270
4271 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4272 CompareResult<String> interfaceDiff = new CompareResult<String>();
4273 if (oldLp != null) {
4274 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4275 } else if (newLp != null) {
4276 interfaceDiff.added = newLp.getAllInterfaceNames();
4277 }
4278 for (String iface : interfaceDiff.added) {
4279 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004280 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004281 mNetd.addInterfaceToNetwork(iface, netId);
4282 } catch (Exception e) {
4283 loge("Exception adding interface: " + e);
4284 }
4285 }
4286 for (String iface : interfaceDiff.removed) {
4287 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004288 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004289 mNetd.removeInterfaceFromNetwork(iface, netId);
4290 } catch (Exception e) {
4291 loge("Exception removing interface: " + e);
4292 }
4293 }
4294 }
4295
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004296 /**
4297 * Have netd update routes from oldLp to newLp.
4298 * @return true if routes changed between oldLp and newLp
4299 */
4300 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004301 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4302 if (oldLp != null) {
4303 routeDiff = oldLp.compareAllRoutes(newLp);
4304 } else if (newLp != null) {
4305 routeDiff.added = newLp.getAllRoutes();
4306 }
4307
4308 // add routes before removing old in case it helps with continuous connectivity
4309
4310 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4311 for (RouteInfo route : routeDiff.added) {
4312 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004313 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004314 try {
4315 mNetd.addRoute(netId, route);
4316 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004317 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4318 loge("Exception in addRoute for non-gateway: " + e);
4319 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004320 }
4321 }
4322 for (RouteInfo route : routeDiff.added) {
4323 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004324 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004325 try {
4326 mNetd.addRoute(netId, route);
4327 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004328 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4329 loge("Exception in addRoute for gateway: " + e);
4330 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 }
4332 }
4333
4334 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004335 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004336 try {
4337 mNetd.removeRoute(netId, route);
4338 } catch (Exception e) {
4339 loge("Exception in removeRoute: " + e);
4340 }
4341 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004342 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004343 }
Erik Kline41368502015-06-17 13:19:54 +09004344
Erik Kline94887872016-04-05 13:30:49 +09004345 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4346 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4347 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004348 }
Erik Kline94887872016-04-05 13:30:49 +09004349
4350 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004351 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004352 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004353 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004354 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4355 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004356 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004357 }
4358 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4359 if (defaultNai != null && defaultNai.network.netId == netId) {
4360 setDefaultDnsSystemProperties(dnses);
4361 }
4362 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004363 }
4364
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004365 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4366 int last = 0;
4367 for (InetAddress dns : dnses) {
4368 ++last;
4369 String key = "net.dns" + last;
4370 String value = dns.getHostAddress();
4371 SystemProperties.set(key, value);
4372 }
4373 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4374 String key = "net.dns" + i;
4375 SystemProperties.set(key, "");
4376 }
4377 mNumDnsEntries = last;
4378 }
4379
Paul Jensen3d194ea2015-06-16 14:27:36 -04004380 /**
4381 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4382 * augmented with any stateful capabilities implied from {@code networkAgent}
4383 * (e.g., validated status and captive portal status).
4384 *
Paul Jensene0988542015-06-25 15:30:08 -04004385 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004386 * @param networkCapabilities the new network capabilities.
4387 */
Paul Jensene0988542015-06-25 15:30:08 -04004388 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004389 // Don't modify caller's NetworkCapabilities.
4390 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004391 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004392 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4393 } else {
4394 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4395 }
Paul Jensene0988542015-06-25 15:30:08 -04004396 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004397 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4398 } else {
4399 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4400 }
Paul Jensene0988542015-06-25 15:30:08 -04004401 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4402 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004403 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4404 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4405 try {
4406 mNetd.setNetworkPermission(nai.network.netId,
4407 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4408 null : NetworkManagementService.PERMISSION_SYSTEM);
4409 } catch (RemoteException e) {
4410 loge("Exception in setNetworkPermission: " + e);
4411 }
4412 }
Paul Jensene0988542015-06-25 15:30:08 -04004413 synchronized (nai) {
4414 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004415 }
Paul Jensene0988542015-06-25 15:30:08 -04004416 rematchAllNetworksAndRequests(nai, oldScore);
4417 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004418 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004419 }
4420
Paul Jensenc8b9a742014-09-30 15:37:41 -04004421 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4422 for (int i = 0; i < nai.networkRequests.size(); i++) {
4423 NetworkRequest nr = nai.networkRequests.valueAt(i);
4424 // Don't send listening requests to factories. b/17393458
4425 if (!isRequest(nr)) continue;
4426 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4427 }
4428 }
4429
Robert Greenwalt7b816022014-04-18 15:25:25 -07004430 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4431 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004432 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004433 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4434 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004435 }
4436 }
4437
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004438 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4439 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004440 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004441 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004442 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4443 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004444 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004445 sendIntent(nri.mPendingIntent, intent);
4446 }
4447 // else not handled
4448 }
4449
4450 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4451 mPendingIntentWakeLock.acquire();
4452 try {
4453 if (DBG) log("Sending " + pendingIntent);
4454 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4455 } catch (PendingIntent.CanceledException e) {
4456 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4457 mPendingIntentWakeLock.release();
4458 releasePendingNetworkRequest(pendingIntent);
4459 }
4460 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4461 }
4462
4463 @Override
4464 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4465 String resultData, Bundle resultExtras) {
4466 if (DBG) log("Finished sending " + pendingIntent);
4467 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004468 // Release with a delay so the receiving client has an opportunity to put in its
4469 // own request.
4470 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004471 }
4472
Robert Greenwalt9258c642014-03-26 16:47:06 -07004473 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004474 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004475 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004476 Bundle bundle = new Bundle();
4477 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4478 new NetworkRequest(nri.request));
4479 Message msg = Message.obtain();
4480 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4481 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4482 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4483 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004484 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004485 case ConnectivityManager.CALLBACK_LOSING: {
4486 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4487 break;
4488 }
4489 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4490 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4491 new NetworkCapabilities(networkAgent.networkCapabilities));
4492 break;
4493 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004494 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004495 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4496 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004497 break;
4498 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004499 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004500 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004501 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004502 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004503 if (VDBG) {
4504 log("sending notification " + notifyTypeToName(notificationType) +
4505 " for " + nri.request);
4506 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004507 nri.messenger.send(msg);
4508 } catch (RemoteException e) {
4509 // may occur naturally in the race of binder death.
4510 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4511 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004512 }
4513
Paul Jensenc8b9a742014-09-30 15:37:41 -04004514 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4515 for (int i = 0; i < nai.networkRequests.size(); i++) {
4516 NetworkRequest nr = nai.networkRequests.valueAt(i);
4517 // Ignore listening requests.
4518 if (!isRequest(nr)) continue;
4519 loge("Dead network still had at least " + nr);
4520 break;
4521 }
4522 nai.asyncChannel.disconnect();
4523 }
4524
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4526 if (oldNetwork == null) {
4527 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4528 return;
4529 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004530 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4531 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004532 }
4533
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004534 private void makeDefault(NetworkAgentInfo newNetwork, NetworkAgentInfo prevNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004535 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004536 setupDataActivityTracking(newNetwork);
4537 try {
4538 mNetd.setDefaultNetId(newNetwork.network.netId);
4539 } catch (Exception e) {
4540 loge("Exception setting default network :" + e);
4541 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004542 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004543 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004544 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004545 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Hugo Benichi5f16f762016-04-20 12:09:33 +09004546 logDefaultNetworkEvent(newNetwork, prevNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004547 }
4548
Paul Jensen2161a8e2014-09-11 11:00:39 -04004549 // Handles a network appearing or improving its score.
4550 //
4551 // - Evaluates all current NetworkRequests that can be
4552 // satisfied by newNetwork, and reassigns to newNetwork
4553 // any such requests for which newNetwork is the best.
4554 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004555 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004556 // needed. A network is needed if it is the best network for
4557 // one or more NetworkRequests, or if it is a VPN.
4558 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004559 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004560 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004561 //
4562 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4563 // networks that have no chance (i.e. even if validated)
4564 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004565 //
4566 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4567 // it does not remove NetworkRequests that other Networks could better satisfy.
4568 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4569 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4570 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004571 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004572 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004573 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4574 // performed to tear down unvalidated networks that have no chance (i.e. even if
4575 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004576 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004577 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Robin Lee585e2482016-05-01 23:00:00 +01004578 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004579 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004580 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004581 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004582 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004583 // Find and migrate to this Network any NetworkRequests for
4584 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004585 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004586 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004587 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004588 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004589 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4590 final boolean satisfies = newNetwork.satisfies(nri.request);
4591 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004592 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004593 log("Network " + newNetwork.name() + " was already satisfying" +
4594 " request " + nri.request.requestId + ". No change.");
4595 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004596 keep = true;
4597 continue;
4598 }
4599
4600 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004601 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004602 if (satisfies) {
Erik Kline371c7b72016-03-22 17:04:20 +09004603 if (!nri.isRequest()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004604 // This is not a request, it's a callback listener.
4605 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004606 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004607 continue;
4608 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004609
Robert Greenwalt7b816022014-04-18 15:25:25 -07004610 // next check if it's better than any current network we're using for
4611 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004612 if (VDBG) {
4613 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004614 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4615 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004616 }
4617 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004618 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004619 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004620 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004621 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004622 currentNetwork.networkRequests.remove(nri.request.requestId);
4623 currentNetwork.networkLingered.add(nri.request);
4624 affectedNetworks.add(currentNetwork);
4625 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004626 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004627 }
Paul Jensen573a0352015-01-08 10:49:34 -05004628 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004629 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004630 if (!newNetwork.addRequest(nri.request)) {
4631 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4632 }
4633 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004634 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004635 // Tell NetworkFactories about the new score, so they can stop
4636 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004637 // TODO - this could get expensive if we have alot of requests for this
4638 // network. Think about if there is a way to reduce this. Push
4639 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004640 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004641 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004642 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004643 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004644 }
4645 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004646 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4647 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4648 // mark it as no longer satisfying "nri". Because networks are processed by
4649 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4650 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4651 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4652 // This means this code doesn't have to handle the case where "currentNetwork" no
4653 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4654 if (DBG) {
4655 log("Network " + newNetwork.name() + " stopped satisfying" +
4656 " request " + nri.request.requestId);
4657 }
4658 newNetwork.networkRequests.remove(nri.request.requestId);
4659 if (currentNetwork == newNetwork) {
4660 mNetworkForRequestId.remove(nri.request.requestId);
4661 sendUpdatedScoreToFactories(nri.request, 0);
4662 } else {
Erik Kline371c7b72016-03-22 17:04:20 +09004663 if (nri.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004664 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4665 newNetwork.name() +
4666 " without updating mNetworkForRequestId or factories!");
4667 }
4668 }
4669 // TODO: technically, sending CALLBACK_LOST here is
4670 // incorrect if nri is a request (not a listen) and there
4671 // is a replacement network currently connected that can
4672 // satisfy it. However, the only capability that can both
4673 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4674 // so this code is only incorrect for a network that loses
4675 // the TRUSTED capability, which is a rare case.
4676 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004677 }
4678 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004679 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004680 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004681 if (nai.lingering) {
4682 // Already lingered. Nothing to do. This can only happen if "nai" is in
4683 // "affectedNetworks" twice. The reasoning being that to get added to
4684 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4685 // (i.e. not lingered) so it could have only been lingered by this loop.
4686 // unneeded(nai) will be false and we'll call unlinger() below which would
4687 // be bad, so handle it here.
4688 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004689 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004690 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004691 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004692 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004693 }
4694 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004695 if (isNewDefault) {
4696 // Notify system services that this network is up.
Pierre Imai6b4e15b2016-04-07 12:21:05 +09004697 makeDefault(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004698 synchronized (ConnectivityService.this) {
4699 // have a new default network, release the transition wakelock in
4700 // a second if it's held. The second pause is to allow apps
4701 // to reconnect over the new network
4702 if (mNetTransitionWakeLock.isHeld()) {
4703 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4704 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4705 mNetTransitionWakeLockSerialNumber, 0),
4706 1000);
4707 }
4708 }
4709 }
4710
4711 // do this after the default net is switched, but
4712 // before LegacyTypeTracker sends legacy broadcasts
4713 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4714
4715 if (isNewDefault) {
4716 // Maintain the illusion: since the legacy API only
4717 // understands one network at a time, we must pretend
4718 // that the current default network disconnected before
4719 // the new one connected.
4720 if (oldDefaultNetwork != null) {
4721 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4722 oldDefaultNetwork, true);
4723 }
4724 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4725 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4726 notifyLockdownVpn(newNetwork);
4727 }
4728
Robert Greenwalt7b816022014-04-18 15:25:25 -07004729 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004730 // Notify battery stats service about this network, both the normal
4731 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004732 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004733 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004734 final IBatteryStats bs = BatteryStatsService.getService();
4735 final int type = newNetwork.networkInfo.getType();
4736
4737 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4738 bs.noteNetworkInterfaceType(baseIface, type);
4739 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4740 final String stackedIface = stacked.getInterfaceName();
4741 bs.noteNetworkInterfaceType(stackedIface, type);
4742 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4743 }
4744 } catch (RemoteException ignored) {
4745 }
4746
Robert Greenwalt152ed372014-12-17 17:19:53 -08004747 // This has to happen after the notifyNetworkCallbacks as that tickles each
4748 // ConnectivityManager instance so that legacy requests correctly bind dns
4749 // requests to this network. The legacy users are listening for this bcast
4750 // and will generally do a dns request so they can ensureRouteToHost and if
4751 // they do that before the callbacks happen they'll use the default network.
4752 //
4753 // TODO: Is there still a race here? We send the broadcast
4754 // after sending the callback, but if the app can receive the
4755 // broadcast before the callback, it might still break.
4756 //
4757 // This *does* introduce a race where if the user uses the new api
4758 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4759 // they may get old info. Reverse this after the old startUsing api is removed.
4760 // This is on top of the multiple intent sequencing referenced in the todo above.
4761 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4762 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4763 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4764 // legacy type tracker filters out repeat adds
4765 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4766 }
4767 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004768
4769 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4770 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4771 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4772 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4773 if (newNetwork.isVPN()) {
4774 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4775 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004776 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004777 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4778 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004779 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004780 if (DBG) log("Reaping " + nai.name());
4781 teardownUnneededNetwork(nai);
4782 }
4783 }
4784 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004785 }
4786
Paul Jensen1c7ba022015-06-16 14:27:36 -04004787 /**
4788 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4789 * being disconnected.
4790 * @param changed If only one Network's score or capabilities have been modified since the last
4791 * time this function was called, pass this Network in this argument, otherwise pass
4792 * null.
4793 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4794 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4795 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4796 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4797 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004798 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004799 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004800 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4801 // to avoid the slowness. It is not simply enough to process just "changed", for
4802 // example in the case where "changed"'s score decreases and another network should begin
4803 // satifying a NetworkRequest that "changed" currently satisfies.
4804
4805 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4806 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4807 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004808 if (changed != null && oldScore < changed.getCurrentScore()) {
4809 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004810 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004811 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4812 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4813 // Rematch higher scoring networks first to prevent requests first matching a lower
4814 // scoring network and then a higher scoring network, which could produce multiple
4815 // callbacks and inadvertently unlinger networks.
4816 Arrays.sort(nais);
4817 for (NetworkAgentInfo nai : nais) {
4818 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004819 // Only reap the last time through the loop. Reaping before all rematching
4820 // is complete could incorrectly teardown a network that hasn't yet been
4821 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004822 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004823 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004824 }
4825 }
4826 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004827
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004828 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004829 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004830 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004831 // For now only update icons for default connection.
4832 // TODO: Update WiFi and cellular icons separately. b/17237507
4833 if (!isDefaultNetwork(nai)) return;
4834
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004835 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004836 // Don't repeat publish.
4837 if (newInetCondition == mDefaultInetConditionPublished) return;
4838
4839 mDefaultInetConditionPublished = newInetCondition;
4840 sendInetConditionBroadcast(nai.networkInfo);
4841 }
4842
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004843 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4844 if (mLockdownTracker != null) {
4845 if (nai != null && nai.isVPN()) {
4846 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4847 } else {
4848 mLockdownTracker.onNetworkInfoChanged();
4849 }
4850 }
4851 }
4852
Robert Greenwalt7b816022014-04-18 15:25:25 -07004853 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4854 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004855 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004856 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004857 synchronized (networkAgent) {
4858 oldInfo = networkAgent.networkInfo;
4859 networkAgent.networkInfo = newInfo;
4860 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004861 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004862
4863 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004864 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
4865 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
4866 notifyIfacesChangedForNetworkStats();
4867 } else if (VDBG) log("ignoring duplicate network state non-change");
4868 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004869 return;
4870 }
4871 if (DBG) {
4872 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4873 (oldInfo == null ? "null" : oldInfo.getState()) +
4874 " to " + state);
4875 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004876
Robin Lee585e2482016-05-01 23:00:00 +01004877 if (!networkAgent.created
4878 && (state == NetworkInfo.State.CONNECTED
4879 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004880 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004881 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004882 if (networkAgent.isVPN()) {
4883 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004884 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4885 (networkAgent.networkMisc == null ||
4886 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004887 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004888 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4889 networkAgent.networkCapabilities.hasCapability(
4890 NET_CAPABILITY_NOT_RESTRICTED) ?
4891 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004892 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004893 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004894 loge("Error creating network " + networkAgent.network.netId + ": "
4895 + e.getMessage());
4896 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004897 }
Paul Jenseneec75412014-08-04 12:21:19 -04004898 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01004899 }
4900
4901 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
4902 networkAgent.everConnected = true;
4903
Robert Greenwalt7b816022014-04-18 15:25:25 -07004904 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004905 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004906
Paul Jensenca8f16a2014-05-09 12:47:55 -04004907 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004908 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004909
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004910 if (networkAgent.isVPN()) {
4911 // Temporarily disable the default proxy (not global).
4912 synchronized (mProxyLock) {
4913 if (!mDefaultProxyDisabled) {
4914 mDefaultProxyDisabled = true;
4915 if (mGlobalProxy == null && mDefaultProxy != null) {
4916 sendProxyBroadcast(null);
4917 }
4918 }
4919 }
4920 // TODO: support proxy per network.
4921 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004922
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004923 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4924 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4925 // capabilities, so it only needs to be done once on initial connect, not every time the
4926 // network's capabilities change. Note that we do this before rematching the network,
4927 // so we could decide to tear it down immediately afterwards. That's fine though - on
4928 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4929 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004930 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004931
Paul Jensen2161a8e2014-09-11 11:00:39 -04004932 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004933 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004934
4935 // This has to happen after matching the requests, because callbacks are just requests.
4936 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004937 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004938 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004939 if (networkAgent.isVPN()) {
4940 synchronized (mProxyLock) {
4941 if (mDefaultProxyDisabled) {
4942 mDefaultProxyDisabled = false;
4943 if (mGlobalProxy == null && mDefaultProxy != null) {
4944 sendProxyBroadcast(mDefaultProxy);
4945 }
4946 }
4947 }
4948 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004949 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4950 state == NetworkInfo.State.SUSPENDED) {
4951 // going into or coming out of SUSPEND: rescore and notify
4952 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004953 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004954 }
4955 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4956 ConnectivityManager.CALLBACK_SUSPENDED :
4957 ConnectivityManager.CALLBACK_RESUMED));
4958 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004959 }
4960 }
4961
Robert Greenwaltac96c522014-06-03 16:43:57 -07004962 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004963 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004964 if (score < 0) {
4965 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4966 "). Bumping score to min of 0");
4967 score = 0;
4968 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004969
Paul Jensen2161a8e2014-09-11 11:00:39 -04004970 final int oldScore = nai.getCurrentScore();
4971 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004972
Paul Jensen85cf78e2015-06-25 13:25:07 -04004973 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004974
Paul Jensenc8b9a742014-09-30 15:37:41 -04004975 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004976 }
4977
Robert Greenwalt9258c642014-03-26 16:47:06 -07004978 // notify only this one new request of the current state
4979 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4980 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4981 // TODO - read state from monitor to decide what to send.
4982// if (nai.networkMonitor.isLingering()) {
4983// notifyType = NetworkCallbacks.LOSING;
4984// } else if (nai.networkMonitor.isEvaluating()) {
4985// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4986// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004987 if (nri.mPendingIntent == null) {
4988 callCallbackForRequest(nri, nai, notifyType);
4989 } else {
4990 sendPendingIntentForRequest(nri, nai, notifyType);
4991 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004992 }
4993
Robert Greenwalt8d482522015-06-24 13:23:42 -07004994 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004995 // The NetworkInfo we actually send out has no bearing on the real
4996 // state of affairs. For example, if the default connection is mobile,
4997 // and a request for HIPRI has just gone away, we need to pretend that
4998 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4999 // the state to DISCONNECTED, even though the network is of type MOBILE
5000 // and is still connected.
5001 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5002 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005003 if (state != DetailedState.DISCONNECTED) {
5004 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005005 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005006 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005007 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005008 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5009 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5010 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5011 if (info.isFailover()) {
5012 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5013 nai.networkInfo.setFailover(false);
5014 }
5015 if (info.getReason() != null) {
5016 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5017 }
5018 if (info.getExtraInfo() != null) {
5019 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5020 }
5021 NetworkAgentInfo newDefaultAgent = null;
5022 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005023 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005024 if (newDefaultAgent != null) {
5025 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5026 newDefaultAgent.networkInfo);
5027 } else {
5028 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5029 }
5030 }
5031 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5032 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005033 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005034 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005035 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005036 }
5037 }
5038 }
5039
Robert Greenwalt7b816022014-04-18 15:25:25 -07005040 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005041 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005042 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07005043 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
5044 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5045 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005046 if (nri.mPendingIntent == null) {
5047 callCallbackForRequest(nri, networkAgent, notifyType);
5048 } else {
5049 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5050 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005051 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005052 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005053
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005054 private String notifyTypeToName(int notifyType) {
5055 switch (notifyType) {
5056 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5057 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5058 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5059 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5060 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5061 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5062 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5063 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5064 }
5065 return "UNKNOWN";
5066 }
5067
Jeff Sharkey69736342014-12-08 14:50:12 -08005068 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005069 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5070 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005071 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005072 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005073 try {
5074 mStatsService.forceUpdateIfaces();
5075 } catch (Exception ignored) {
5076 }
5077 }
5078
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005079 @Override
5080 public boolean addVpnAddress(String address, int prefixLength) {
5081 throwIfLockdownEnabled();
5082 int user = UserHandle.getUserId(Binder.getCallingUid());
5083 synchronized (mVpns) {
5084 return mVpns.get(user).addAddress(address, prefixLength);
5085 }
5086 }
5087
5088 @Override
5089 public boolean removeVpnAddress(String address, int prefixLength) {
5090 throwIfLockdownEnabled();
5091 int user = UserHandle.getUserId(Binder.getCallingUid());
5092 synchronized (mVpns) {
5093 return mVpns.get(user).removeAddress(address, prefixLength);
5094 }
5095 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005096
5097 @Override
5098 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5099 throwIfLockdownEnabled();
5100 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005101 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005102 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005103 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005104 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005105 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005106 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005107 }
5108 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005109 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005110
5111 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005112 public String getCaptivePortalServerUrl() {
5113 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5114 }
5115
5116 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005117 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5118 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5119 enforceKeepalivePermission();
5120 mKeepaliveTracker.startNattKeepalive(
5121 getNetworkAgentInfoForNetwork(network),
5122 intervalSeconds, messenger, binder,
5123 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5124 }
5125
5126 @Override
5127 public void stopKeepalive(Network network, int slot) {
5128 mHandler.sendMessage(mHandler.obtainMessage(
5129 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5130 }
5131
5132 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005133 public void factoryReset() {
5134 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005135
5136 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5137 return;
5138 }
5139
Robin Lee3b3dd942015-05-12 18:14:58 +01005140 final int userId = UserHandle.getCallingUserId();
5141
Stuart Scottf1fb3972015-04-02 18:00:02 -07005142 // Turn airplane mode off
5143 setAirplaneMode(false);
5144
Stuart Scotte3e314d2015-04-20 14:07:45 -07005145 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5146 // Untether
5147 for (String tether : getTetheredIfaces()) {
5148 untether(tether);
5149 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005150 }
5151
Stuart Scotte3e314d2015-04-20 14:07:45 -07005152 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
5153 // Turn VPN off
5154 VpnConfig vpnConfig = getVpnConfig(userId);
5155 if (vpnConfig != null) {
5156 if (vpnConfig.legacy) {
5157 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5158 } else {
5159 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5160 // in the future without user intervention.
5161 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005162
Stuart Scotte3e314d2015-04-20 14:07:45 -07005163 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
5164 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005165 }
5166 }
5167 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005168
5169 @VisibleForTesting
5170 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5171 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5172 return new NetworkMonitor(context, handler, nai, defaultRequest);
5173 }
Erik Kline48f12f22016-04-14 17:30:59 +09005174
Hugo Benichi5f16f762016-04-20 12:09:33 +09005175 private static void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
5176 int newNetid = NETID_UNSET;
5177 int prevNetid = NETID_UNSET;
5178 int[] transports = new int[0];
5179 boolean hadIPv4 = false;
5180 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005181
Hugo Benichi5f16f762016-04-20 12:09:33 +09005182 if (newNai != null) {
5183 newNetid = newNai.network.netId;
5184 transports = newNai.networkCapabilities.getTransportTypes();
5185 }
5186 if (prevNai != null) {
5187 prevNetid = prevNai.network.netId;
5188 final LinkProperties lp = prevNai.linkProperties;
5189 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5190 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5191 }
5192
5193 DefaultNetworkEvent.logEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6);
Erik Kline48f12f22016-04-14 17:30:59 +09005194 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005195}