blob: cea7a4b683cf12d3457b7d1ad07318b6076fcdee [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 Leme46c4fc32016-05-04 09:21:43 -070033import static android.net.NetworkPolicyManager.RULE_NONE;
Felipe Leme781ba142016-05-09 16:24:48 -070034import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070035import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060036import static android.net.NetworkPolicyManager.RULE_TEMPORARY_ALLOW_METERED;
Felipe Leme46c4fc32016-05-04 09:21:43 -070037import static android.net.NetworkPolicyManager.uidRulesToString;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060038
Wenchao Tongf5ea3402015-03-04 13:26:38 -080039import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080040import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090041import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070042import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.ContentResolver;
45import android.content.Context;
46import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070047import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070049import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090050import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070051import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090053import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080054import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070055import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070056import android.net.INetworkPolicyListener;
57import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070058import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080059import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070060import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070061import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070062import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070063import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070067import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070068import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070069import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070070import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070071import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070072import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040073import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070074import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040075import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040076import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090077import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090078import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090079import android.net.metrics.NetworkEvent;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080081import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070082import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040083import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070085import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070086import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070087import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080088import android.os.Looper;
89import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070090import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070091import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070092import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070093import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070094import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080095import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090096import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080097import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070098import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040099import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700101import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700102import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700103import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700104import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600105import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700106import android.util.LocalLog;
107import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600108import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700109import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800110import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700111import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500112import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700113import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700114import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800115
Wink Savilleab9321d2013-06-29 21:10:57 -0700116import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400117import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400118import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700119import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700120import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700121import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700122import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800123import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700124import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700125import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700126import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900127import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900128import com.android.internal.util.WakeupMessage;
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;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900134import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700135import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600136import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400137import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900138import com.android.server.connectivity.NetworkNotificationManager;
139import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400140import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700141import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800142import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700143import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700144import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700145import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600146
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700147import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700148
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700149import org.xmlpull.v1.XmlPullParser;
150import org.xmlpull.v1.XmlPullParserException;
151
152import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700154import java.io.FileNotFoundException;
155import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700156import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700158import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700159import java.net.InetAddress;
160import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700161import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700162import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700163import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700164import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700165import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700166import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700167import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700168import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700169import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600170import java.util.SortedSet;
171import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
173/**
174 * @hide
175 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800176public class ConnectivityService extends IConnectivityManager.Stub
177 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900178 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900180 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700181 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
Jake Hamby786e71a2014-02-06 14:43:50 -0800183 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900184 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700185
Jeff Sharkey899223b2012-08-04 15:24:58 -0700186 // TODO: create better separation between radio types and network types
187
Robert Greenwalt42acef32009-08-12 16:08:25 -0700188 // how long to wait before switching back to a radio's default network
189 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
190 // system property that can override the above value
191 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
192 "android.telephony.apn-restore";
193
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900194 // How long to wait before putting up a "This network doesn't have an Internet connection,
195 // connect anyway?" dialog after the user selects a network that doesn't validate.
196 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
197
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900198 // Default to 30s linger time-out. Modifiable only for testing.
199 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
200 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
201 @VisibleForTesting
202 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
203
Jeremy Joslin79294842014-12-03 17:15:28 -0800204 // How long to delay to removal of a pending intent based request.
205 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
206 private final int mReleasePendingIntentDelayMs;
207
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800208 private Tethering mTethering;
209
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700210 private final PermissionMonitor mPermissionMonitor;
211
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700212 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700213
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700214 @GuardedBy("mVpns")
215 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700216
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700217 private boolean mLockdownEnabled;
218 private LockdownVpnTracker mLockdownTracker;
219
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700220 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
221 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600223 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700224 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700225 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600226 @GuardedBy("mRulesLock")
227 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
228 /** Flag indicating if background data is restricted. */
229 @GuardedBy("mRulesLock")
230 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700231
Erik Klineda4bfa82015-04-30 12:58:40 +0900232 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700234 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700235 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800237 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800238
239 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700240 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700242 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800243 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700244 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700245
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700246 private String mCurrentTcpBufferSizes;
247
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700248 private static final int ENABLED = 1;
249 private static final int DISABLED = 0;
250
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900251 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900252 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
253 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900254
Paul Jensenb10e37f2014-11-25 12:33:08 -0500255 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400256 // Tear down networks that have no chance (e.g. even if validated) of becoming
257 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 // all networks have been rematched against all NetworkRequests.
259 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400260 // Don't reap networks. This should be passed when some networks have not yet been
261 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500262 DONT_REAP
263 };
264
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700265 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266 * used internally to change our mobile data enabled flag
267 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700268 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700269
270 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700271 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700272 * from one net to another. Clear happens when we get a new
273 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
274 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700275 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700276 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700277
Robert Greenwalt434203a2010-10-11 16:00:27 -0700278 /**
279 * used internally to reload global proxy settings
280 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700281 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700282
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700283 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400284 * PAC manager has received new port.
285 */
286 private static final int EVENT_PROXY_HAS_CHANGED = 16;
287
Robert Greenwalte049c232014-04-11 15:53:27 -0700288 /**
289 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700290 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700291 */
292 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
293
Robert Greenwalt7b816022014-04-18 15:25:25 -0700294 /**
295 * used internally when registering NetworkAgents
296 * obj = Messenger
297 */
298 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
299
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 /**
301 * used to add a network request
302 * includes a NetworkRequestInfo
303 */
304 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
305
306 /**
307 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900308 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700309 * cancel it.
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
313
314 /**
315 * used to add a network listener - no request
316 * includes a NetworkRequestInfo
317 */
318 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
319
320 /**
321 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400322 * arg1 = UID of caller
323 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700324 */
325 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
326
Robert Greenwalta67be032014-05-16 15:49:14 -0700327 /**
328 * used internally when registering NetworkFactories
329 * obj = Messenger
330 */
331 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
332
Robert Greenwalt27711812014-06-25 16:45:57 -0700333 /**
334 * used internally to expire a wakelock when transitioning
335 * from one net to another. Expire happens when we fail to find
336 * a new network (typically after 1 minute) -
337 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
338 * a replacement network.
339 */
340 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
341
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700342 /**
343 * Used internally to indicate the system is ready.
344 */
345 private static final int EVENT_SYSTEM_READY = 25;
346
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800347 /**
348 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400349 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800350 */
351 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
352
353 /**
354 * used to remove a pending intent and its associated network request.
355 * arg1 = UID of caller
356 * obj = PendingIntent
357 */
358 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
359
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900360 /**
361 * used to specify whether a network should be used even if unvalidated.
362 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
363 * arg2 = whether to remember this choice in the future (1 or 0)
364 * obj = network
365 */
366 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
367
368 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900369 * used to specify whether a network should not be penalized when it becomes unvalidated.
370 */
371 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
372
373 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900374 * used to ask the user to confirm a connection to an unvalidated network.
375 * obj = network
376 */
377 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700378
Erik Klineda4bfa82015-04-30 12:58:40 +0900379 /**
380 * used internally to (re)configure mobile data always-on settings.
381 */
382 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
383
Paul Jensen694f2b82015-06-17 14:15:39 -0400384 /**
385 * used to add a network listener with a pending intent
386 * obj = NetworkRequestInfo
387 */
388 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
389
Erik Klineacdd6392016-07-07 16:50:58 +0900390 /**
391 * Indicates a caller has requested to have its callback invoked with
392 * the latest LinkProperties or NetworkCapabilities.
393 *
394 * arg1 = UID of caller
395 * obj = NetworkRequest
396 */
397 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
398 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
399
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900400 /**
401 * Used internally to (re)configure avoid bad wifi setting.
402 */
403 private static final int EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI = 34;
404
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900405 /** Handler thread used for both of the handlers below. */
406 @VisibleForTesting
407 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700408 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700409 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700410 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700411 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700412
Mike Lockwood0f79b542009-08-14 14:18:49 -0400413 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800414 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400415
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700416 private PowerManager.WakeLock mNetTransitionWakeLock;
417 private String mNetTransitionWakeLockCausedBy = "";
418 private int mNetTransitionWakeLockSerialNumber;
419 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800420 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700421
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700422 // used in DBG mode to track inet condition reports
423 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
424 private ArrayList mInetLog;
425
Robert Greenwalt434203a2010-10-11 16:00:27 -0700426 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400427 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700428 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700429 private boolean mDefaultProxyDisabled = false;
430
Robert Greenwalt434203a2010-10-11 16:00:27 -0700431 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400432 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700433
Jason Monk602b2322013-07-03 17:04:33 -0400434 private PacManager mPacManager = null;
435
Erik Klineda4bfa82015-04-30 12:58:40 +0900436 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700437
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400438 private UserManager mUserManager;
439
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700440 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700441 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700442
Robert Greenwalt50393202011-06-21 17:26:14 -0700443 // the set of network types that can only be enabled by system/sig apps
444 List mProtectedNetworks;
445
John Spurlockbf991a82013-06-24 14:20:23 -0400446 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700447
Wink Savilleab9321d2013-06-29 21:10:57 -0700448 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400449
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900450 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900451 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900452 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900453
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700454 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
455 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700456 private final static int MAX_NET_ID = 65535;
457 private int mNextNetId = MIN_NET_ID;
458
Robert Greenwalt34524f02014-05-18 16:22:10 -0700459 // sequence number of NetworkRequests
460 private int mNextNetworkRequestId = 1;
461
Erik Kline7523eb32015-07-09 18:24:03 +0900462 // NetworkRequest activity String log entries.
463 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
464 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
465
Hugo Benichic2ae2872016-07-11 11:05:12 +0900466 // NetworkInfo blocked and unblocked String log entries
467 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
468 private static final int MAX_NETWORK_INFO_LOGS = 100;
469 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
470
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700471 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
472 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400473 private static class ValidationLog {
474 final Network mNetwork;
475 final String mNetworkExtraInfo;
476 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700477
Paul Jensen0808eb82016-06-03 13:51:21 -0400478 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
479 mNetwork = network;
480 mNetworkExtraInfo = networkExtraInfo;
481 mLog = log;
482 }
483 }
484 private final ArrayDeque<ValidationLog> mValidationLogs =
485 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
486
487 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700488 synchronized(mValidationLogs) {
489 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
490 mValidationLogs.removeLast();
491 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400492 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700493 }
494 }
495
Hugo Benichif9fdf872016-07-28 17:53:06 +0900496 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900497
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700498 /**
499 * Implements support for the legacy "one network per network type" model.
500 *
501 * We used to have a static array of NetworkStateTrackers, one for each
502 * network type, but that doesn't work any more now that we can have,
503 * for example, more that one wifi network. This class stores all the
504 * NetworkAgentInfo objects that support a given type, but the legacy
505 * API will only see the first one.
506 *
507 * It serves two main purposes:
508 *
509 * 1. Provide information about "the network for a given type" (since this
510 * API only supports one).
511 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
512 * the first network for a given type changes, or if the default network
513 * changes.
514 */
515 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900517 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900518 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900519
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700520 /**
521 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
522 * Each list holds references to all NetworkAgentInfos that are used to
523 * satisfy requests for that network type.
524 *
525 * This array is built out at startup such that an unsupported network
526 * doesn't get an ArrayList instance, making this a tristate:
527 * unsupported, supported but not active and active.
528 *
529 * The actual lists are populated when we scan the network types that
530 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900531 *
532 * Threading model:
533 * - addSupportedType() is only called in the constructor
534 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
535 * They are therefore not thread-safe with respect to each other.
536 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
537 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
538 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700539 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900540 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700541
542 public LegacyTypeTracker() {
543 mTypeLists = (ArrayList<NetworkAgentInfo>[])
544 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
545 }
546
547 public void addSupportedType(int type) {
548 if (mTypeLists[type] != null) {
549 throw new IllegalStateException(
550 "legacy list for type " + type + "already initialized");
551 }
552 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
553 }
554
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700555 public boolean isTypeSupported(int type) {
556 return isNetworkTypeValid(type) && mTypeLists[type] != null;
557 }
558
559 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900560 synchronized (mTypeLists) {
561 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
562 return mTypeLists[type].get(0);
563 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900565 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700566 }
567
Robert Greenwalt8d482522015-06-24 13:23:42 -0700568 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900569 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900570 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700571 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900572 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900573 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900574 }
575 }
576
577 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700578 public void add(int type, NetworkAgentInfo nai) {
579 if (!isTypeSupported(type)) {
580 return; // Invalid network type.
581 }
582 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
583
584 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
585 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700586 return;
587 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900588 synchronized (mTypeLists) {
589 list.add(nai);
590 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900591
592 // 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 +0900593 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900594 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700595 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
596 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 }
599
Lorenzo Colittia793a672014-07-31 23:20:17 +0900600 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900601 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
603 if (list == null || list.isEmpty()) {
604 return;
605 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900606 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607
Hugo Benichi78caa2582016-06-21 09:48:07 +0900608 synchronized (mTypeLists) {
609 if (!list.remove(nai)) {
610 return;
611 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900612 }
613
Robert Greenwalt8d482522015-06-24 13:23:42 -0700614 final DetailedState state = DetailedState.DISCONNECTED;
615
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900616 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700617 maybeLogBroadcast(nai, state, type, wasDefault);
618 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900619 }
620
621 if (!list.isEmpty() && wasFirstNetwork) {
622 if (DBG) log("Other network available for type " + type +
623 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900624 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700625 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
626 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900627 }
628 }
629
630 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900631 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
632 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700633 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900634 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700635 }
636 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700637
Robert Greenwalt8d482522015-06-24 13:23:42 -0700638 // send out another legacy broadcast - currently only used for suspend/unsuspend
639 // toggle
640 public void update(NetworkAgentInfo nai) {
641 final boolean isDefault = isDefaultNetwork(nai);
642 final DetailedState state = nai.networkInfo.getDetailedState();
643 for (int type = 0; type < mTypeLists.length; type++) {
644 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700645 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900646 final boolean isFirst = contains && (nai == list.get(0));
647 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700648 maybeLogBroadcast(nai, state, type, isDefault);
649 sendLegacyNetworkBroadcast(nai, state, type);
650 }
651 }
652 }
653
Lorenzo Colittia793a672014-07-31 23:20:17 +0900654 private String naiToString(NetworkAgentInfo nai) {
655 String name = (nai != null) ? nai.name() : "null";
656 String state = (nai.networkInfo != null) ?
657 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
658 "???/???";
659 return name + " " + state;
660 }
661
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700662 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900663 pw.println("mLegacyTypeTracker:");
664 pw.increaseIndent();
665 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700666 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900667 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700668 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900669 pw.println();
670 pw.println("Current state:");
671 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900672 synchronized (mTypeLists) {
673 for (int type = 0; type < mTypeLists.length; type++) {
674 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
675 for (NetworkAgentInfo nai : mTypeLists[type]) {
676 pw.println(type + " " + naiToString(nai));
677 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900678 }
679 }
680 pw.decreaseIndent();
681 pw.decreaseIndent();
682 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700683 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700684 }
685 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
686
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900687 @VisibleForTesting
688 protected HandlerThread createHandlerThread() {
689 return new HandlerThread("ConnectivityServiceThread");
690 }
691
Jeff Sharkey899223b2012-08-04 15:24:58 -0700692 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700693 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900694 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
695 }
696
697 @VisibleForTesting
698 protected ConnectivityService(Context context, INetworkManagementService netManager,
699 INetworkStatsService statsService, INetworkPolicyManager policyManager,
700 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800701 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800702
Hugo Benichif9fdf872016-07-28 17:53:06 +0900703 mMetricsLog = logger;
Erik Klineda4bfa82015-04-30 12:58:40 +0900704 mDefaultRequest = createInternetRequestForTransport(-1);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900705 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900706 mNetworkRequests.put(mDefaultRequest, defaultNRI);
707 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900708
709 mDefaultMobileDataRequest = createInternetRequestForTransport(
710 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700711
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900712 mHandlerThread = createHandlerThread();
713 mHandlerThread.start();
714 mHandler = new InternalHandler(mHandlerThread.getLooper());
715 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700716
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800717 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800718 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
719 String id = Settings.Secure.getString(context.getContentResolver(),
720 Settings.Secure.ANDROID_ID);
721 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700722 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800723 SystemProperties.set("net.hostname", name);
724 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800725 }
726
Jeremy Joslin79294842014-12-03 17:15:28 -0800727 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
728 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
729
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900730 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
731
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700732 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700733 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800734 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700735 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700736 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700737 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700738
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700739 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600740 mPolicyManager.setConnectivityListener(mPolicyListener);
741 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700742 } catch (RemoteException e) {
743 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700744 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700745 }
746
747 final PowerManager powerManager = (PowerManager) context.getSystemService(
748 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700749 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
750 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
751 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800752 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700753
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700754 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700755
Wink Saville51f456f2013-04-23 14:26:51 -0700756 // TODO: What is the "correct" way to do determine if this is a wifi only device?
757 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
758 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700759 String[] naStrings = context.getResources().getStringArray(
760 com.android.internal.R.array.networkAttributes);
761 for (String naString : naStrings) {
762 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700763 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700764 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700765 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800766 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700767 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700768 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700769 }
Wink Saville51f456f2013-04-23 14:26:51 -0700770 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
771 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
772 n.type);
773 continue;
774 }
Wink Saville975c8482011-04-07 14:23:45 -0700775 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800776 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700777 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700778 continue;
779 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700780 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700781
Wink Saville975c8482011-04-07 14:23:45 -0700782 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700783 mNetworksDefined++;
784 } catch(Exception e) {
785 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700786 }
787 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700788
789 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
790 if (mNetConfigs[TYPE_VPN] == null) {
791 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
792 // don't need to add TYPE_VPN to mNetConfigs.
793 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
794 mNetworksDefined++; // used only in the log() statement below.
795 }
796
Wink Saville5e56bc52013-07-29 15:00:57 -0700797 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700798
Robert Greenwalt50393202011-06-21 17:26:14 -0700799 mProtectedNetworks = new ArrayList<Integer>();
800 int[] protectedNetworks = context.getResources().getIntArray(
801 com.android.internal.R.array.config_protectedNetworks);
802 for (int p : protectedNetworks) {
803 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
804 mProtectedNetworks.add(p);
805 } else {
806 if (DBG) loge("Ignoring protectedNetwork " + p);
807 }
808 }
809
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700810 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
811 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700812
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800813 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800814
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700815 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
816
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700817 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700818 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100819 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700820 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700821 intentFilter.addAction(Intent.ACTION_USER_ADDED);
822 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000823 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700824 mContext.registerReceiverAsUser(
825 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900826
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700827 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700828 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700829 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700830 } catch (RemoteException e) {
831 loge("Error registering observer :" + e);
832 }
833
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700834 if (DBG) {
835 mInetLog = new ArrayList();
836 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700837
Erik Klineda4bfa82015-04-30 12:58:40 +0900838 mSettingsObserver = new SettingsObserver(mContext, mHandler);
839 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800840
John Spurlockbf991a82013-06-24 14:20:23 -0400841 mDataConnectionStats = new DataConnectionStats(mContext);
842 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400843
Jason Monkdecd2952013-10-10 14:02:51 -0400844 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700845
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400846 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900847
848 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900849 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
850 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900851
852 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
853 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
854 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
855 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
856 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
857 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
858 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900859
860 intentFilter = new IntentFilter();
861 intentFilter.addAction(Intent.ACTION_CONFIGURATION_CHANGED);
862 mContext.registerReceiverAsUser(new BroadcastReceiver() {
863 public void onReceive(Context context, Intent intent) {
864 mHandler.sendEmptyMessage(EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
865 }
866 }, UserHandle.ALL, intentFilter, null, null);
867 updateAvoidBadWifi();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700869
Erik Klineda4bfa82015-04-30 12:58:40 +0900870 private NetworkRequest createInternetRequestForTransport(int transportType) {
871 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900872 netCap.addCapability(NET_CAPABILITY_INTERNET);
873 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900874 if (transportType > -1) {
875 netCap.addTransportType(transportType);
876 }
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900877 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(),
878 NetworkRequest.Type.REQUEST);
Erik Klineda4bfa82015-04-30 12:58:40 +0900879 }
880
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900881 // Used only for testing.
882 // TODO: Delete this and either:
883 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
884 // changing ContentResolver to make registerContentObserver non-final).
885 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
886 // by subclassing SettingsObserver.
887 @VisibleForTesting
888 void updateMobileDataAlwaysOn() {
889 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
890 }
891
Erik Klineda4bfa82015-04-30 12:58:40 +0900892 private void handleMobileDataAlwaysOn() {
893 final boolean enable = (Settings.Global.getInt(
894 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
895 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
896 if (enable == isEnabled) {
897 return; // Nothing to do.
898 }
899
900 if (enable) {
901 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900902 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900903 } else {
904 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
905 }
906 }
907
908 private void registerSettingsCallbacks() {
909 // Watch for global HTTP proxy changes.
910 mSettingsObserver.observe(
911 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
912 EVENT_APPLY_GLOBAL_HTTP_PROXY);
913
914 // Watch for whether or not to keep mobile data always on.
915 mSettingsObserver.observe(
916 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
917 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +0900918
919 // Watch for whether to automatically switch away from wifi networks that lose Internet
920 // access.
921 mSettingsObserver.observe(
922 Settings.Global.getUriFor(Settings.Global.NETWORK_AVOID_BAD_WIFI),
923 EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900924 }
925
Robert Greenwalt34524f02014-05-18 16:22:10 -0700926 private synchronized int nextNetworkRequestId() {
927 return mNextNetworkRequestId++;
928 }
929
Paul Jensen67b0b072015-06-10 11:22:17 -0400930 @VisibleForTesting
931 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400932 synchronized (mNetworkForNetId) {
933 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
934 int netId = mNextNetId;
935 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
936 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500937 if (!mNetIdInUse.get(netId)) {
938 mNetIdInUse.put(netId, true);
939 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400940 }
941 }
942 }
943 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700944 }
945
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600946 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800947 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600948 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
949 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800950 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600951 state = nai.getNetworkState();
952 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800953 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600954 final NetworkInfo info = new NetworkInfo(networkType, 0,
955 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800956 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
957 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600958 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
959 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800960 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600961 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600962 return state;
963 } else {
964 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400966 }
967
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800968 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
969 if (network == null) {
970 return null;
971 }
972 synchronized (mNetworkForNetId) {
973 return mNetworkForNetId.get(network.netId);
974 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600975 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800976
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900977 private Network[] getVpnUnderlyingNetworks(int uid) {
978 if (!mLockdownEnabled) {
979 int user = UserHandle.getUserId(uid);
980 synchronized (mVpns) {
981 Vpn vpn = mVpns.get(user);
982 if (vpn != null && vpn.appliesToUid(uid)) {
983 return vpn.getUnderlyingNetworks();
984 }
985 }
986 }
987 return null;
988 }
989
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800990 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400991 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800992
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900993 final Network[] networks = getVpnUnderlyingNetworks(uid);
994 if (networks != null) {
995 // getUnderlyingNetworks() returns:
996 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
997 // empty array => the VPN explicitly said "no default network".
998 // non-empty array => the VPN specified one or more default networks; we use the
999 // first one.
1000 if (networks.length > 0) {
1001 nai = getNetworkAgentInfoForNetwork(networks[0]);
1002 } else {
1003 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001004 }
1005 }
1006
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001007 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001008 return nai.getNetworkState();
1009 } else {
1010 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001011 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001012 }
1013
1014 /**
1015 * Check if UID should be blocked from using the network with the given LinkProperties.
1016 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001017 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1018 boolean ignoreBlocked) {
1019 // Networks aren't blocked when ignoring blocked status
1020 if (ignoreBlocked) return false;
1021 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001022 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001023
1024 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001025 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001026
Robin Lee17e61832016-05-09 13:46:28 +01001027 synchronized (mVpns) {
1028 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1029 if (vpn != null && vpn.isBlockingUid(uid)) {
1030 return true;
1031 }
1032 }
1033
Robert Greenwalt12e67352014-05-13 21:41:06 -07001034 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001035 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001036 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001037 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001038 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001039
Felipe Lemed31a97f2016-05-06 14:53:50 -07001040 boolean allowed = true;
1041 // Check Data Saver Mode first...
1042 if (networkMetered) {
1043 if ((uidRules & RULE_REJECT_METERED) != 0) {
1044 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1045 // Explicitly blacklisted.
1046 allowed = false;
1047 } else {
1048 allowed = !mRestrictBackground
1049 || (uidRules & RULE_ALLOW_METERED) != 0
1050 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1051 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1052 + " mRestrictBackground=" + mRestrictBackground
1053 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1054 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1055 + ": " + allowed);
1056 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001057 }
Felipe Leme781ba142016-05-09 16:24:48 -07001058 // ...then power restrictions.
1059 if (allowed) {
1060 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001061 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001062 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001063 }
1064 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001065 }
1066
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001067 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001068 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1069 return;
1070 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001071 boolean removed = false;
1072 boolean added = false;
1073 synchronized (mBlockedAppUids) {
1074 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1075 added = true;
1076 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1077 removed = true;
1078 }
1079 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001080 if (added) {
1081 log("Returning blocked NetworkInfo to uid=" + uid);
1082 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1083 } else if (removed) {
1084 log("Returning unblocked NetworkInfo to uid=" + uid);
1085 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1086 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001087 }
1088
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001089 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001090 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1091 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1092 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1093 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001094 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001095 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001096 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1097
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001098 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001099 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001100 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001101 if (mLockdownTracker != null) {
1102 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001103 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001104
1105 // TODO: apply metered state closer to NetworkAgentInfo
1106 final long token = Binder.clearCallingIdentity();
1107 try {
1108 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1109 } catch (RemoteException e) {
1110 } finally {
1111 Binder.restoreCallingIdentity(token);
1112 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001113 }
1114
1115 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001116 * Return NetworkInfo for the active (i.e., connected) network interface.
1117 * It is assumed that at most one network is active at a time. If more
1118 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001119 * @return the info for the active network, or {@code null} if none is
1120 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001121 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001122 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001123 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001124 enforceAccessPermission();
1125 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001126 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001127 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001128 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1129 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 }
1131
Paul Jensen31a94f42015-02-13 14:18:39 -05001132 @Override
1133 public Network getActiveNetwork() {
1134 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001135 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001136 }
1137
1138 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001139 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001140 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001141 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001142 }
1143
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001144 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001145 final int user = UserHandle.getUserId(uid);
1146 int vpnNetId = NETID_UNSET;
1147 synchronized (mVpns) {
1148 final Vpn vpn = mVpns.get(user);
1149 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1150 }
1151 NetworkAgentInfo nai;
1152 if (vpnNetId != NETID_UNSET) {
1153 synchronized (mNetworkForNetId) {
1154 nai = mNetworkForNetId.get(vpnNetId);
1155 }
1156 if (nai != null) return nai.network;
1157 }
1158 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001159 if (nai != null
1160 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1161 nai = null;
1162 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001163 return nai != null ? nai.network : null;
1164 }
1165
Lorenzo Colitti18660282016-07-04 12:55:44 +09001166 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001167 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1168 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001169 final int uid = Binder.getCallingUid();
1170 NetworkState state = getUnfilteredActiveNetworkState(uid);
1171 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001172 }
1173
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001174 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001175 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001176 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001177 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001178 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001179 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001180 }
1181
1182 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 public NetworkInfo getNetworkInfo(int networkType) {
1184 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001185 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001186 if (getVpnUnderlyingNetworks(uid) != null) {
1187 // A VPN is active, so we may need to return one of its underlying networks. This
1188 // information is not available in LegacyTypeTracker, so we have to get it from
1189 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001190 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001191 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001192 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001193 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001194 }
1195 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001196 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001197 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001198 }
1199
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001200 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001201 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001202 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001203 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001204 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001205 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001206 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001207 return state.networkInfo;
1208 } else {
1209 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001210 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001211 }
1212
1213 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001214 public NetworkInfo[] getAllNetworkInfo() {
1215 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001216 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001217 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1218 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001219 NetworkInfo info = getNetworkInfo(networkType);
1220 if (info != null) {
1221 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001222 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001223 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001224 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 }
1226
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001227 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001228 public Network getNetworkForType(int networkType) {
1229 enforceAccessPermission();
1230 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001231 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1232 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001233 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001234 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001235 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001236 }
1237
1238 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001239 public Network[] getAllNetworks() {
1240 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001241 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001242 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001243 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001244 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001245 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001246 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001247 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001248 }
1249
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001250 @Override
1251 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1252 // The basic principle is: if an app's traffic could possibly go over a
1253 // network, without the app doing anything multinetwork-specific,
1254 // (hence, by "default"), then include that network's capabilities in
1255 // the array.
1256 //
1257 // In the normal case, app traffic only goes over the system's default
1258 // network connection, so that's the only network returned.
1259 //
1260 // With a VPN in force, some app traffic may go into the VPN, and thus
1261 // over whatever underlying networks the VPN specifies, while other app
1262 // traffic may go over the system default network (e.g.: a split-tunnel
1263 // VPN, or an app disallowed by the VPN), so the set of networks
1264 // returned includes the VPN's underlying networks and the system
1265 // default.
1266 enforceAccessPermission();
1267
1268 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1269
1270 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001271 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001272 if (nc != null) {
1273 result.put(nai.network, nc);
1274 }
1275
1276 if (!mLockdownEnabled) {
1277 synchronized (mVpns) {
1278 Vpn vpn = mVpns.get(userId);
1279 if (vpn != null) {
1280 Network[] networks = vpn.getUnderlyingNetworks();
1281 if (networks != null) {
1282 for (Network network : networks) {
1283 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001284 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001285 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001286 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001287 }
1288 }
1289 }
1290 }
1291 }
1292 }
1293
1294 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1295 out = result.values().toArray(out);
1296 return out;
1297 }
1298
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001299 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001300 public boolean isNetworkSupported(int networkType) {
1301 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001302 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001303 }
1304
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001305 /**
1306 * Return LinkProperties for the active (i.e., connected) default
1307 * network interface. It is assumed that at most one default network
1308 * is active at a time. If more than one is active, it is indeterminate
1309 * which will be returned.
1310 * @return the ip properties for the active network, or {@code null} if
1311 * none is active
1312 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001313 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001314 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001315 enforceAccessPermission();
1316 final int uid = Binder.getCallingUid();
1317 NetworkState state = getUnfilteredActiveNetworkState(uid);
1318 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001319 }
1320
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001321 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001322 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001323 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001324 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1325 if (nai != null) {
1326 synchronized (nai) {
1327 return new LinkProperties(nai.linkProperties);
1328 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001329 }
1330 return null;
1331 }
1332
Robert Greenwalt12e67352014-05-13 21:41:06 -07001333 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001334 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001335 public LinkProperties getLinkProperties(Network network) {
1336 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001337 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001338 if (nai != null) {
1339 synchronized (nai) {
1340 return new LinkProperties(nai.linkProperties);
1341 }
1342 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001343 return null;
1344 }
1345
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001346 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001347 if (nai != null) {
1348 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001349 if (nai.networkCapabilities != null) {
1350 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001351 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001352 }
1353 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001354 return null;
1355 }
1356
1357 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001358 public NetworkCapabilities getNetworkCapabilities(Network network) {
1359 enforceAccessPermission();
1360 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1361 }
1362
1363 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001364 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001365 // Require internal since we're handing out IMSI details
1366 enforceConnectivityInternalPermission();
1367
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001368 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001369 for (Network network : getAllNetworks()) {
1370 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1371 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001372 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001373 }
1374 }
1375 return result.toArray(new NetworkState[result.size()]);
1376 }
1377
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001378 @Override
1379 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1380 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001381 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001382 final long token = Binder.clearCallingIdentity();
1383 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001384 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1385 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001386 try {
1387 return mPolicyManager.getNetworkQuotaInfo(state);
1388 } catch (RemoteException e) {
1389 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001390 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001391 return null;
1392 } finally {
1393 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001394 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001395 }
1396
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001397 @Override
1398 public boolean isActiveNetworkMetered() {
1399 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001400
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001401 final NetworkInfo info = getActiveNetworkInfo();
1402 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001403 }
1404
Jeff Sharkey216c1812012-08-05 14:29:23 -07001405 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1406 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001407 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001408 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001409 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001410 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001411 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001412
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001413 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 * Ensure that a network route exists to deliver traffic to the specified
1415 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001416 * @param networkType the type of the network over which traffic to the
1417 * specified host is to be routed
1418 * @param hostAddress the IP address of the host to which the route is
1419 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001420 * @return {@code true} on success, {@code false} on failure
1421 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001422 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001423 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001425 if (mProtectedNetworks.contains(networkType)) {
1426 enforceConnectivityInternalPermission();
1427 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001428
Chad Brubakerc0234532014-02-14 13:24:29 -08001429 InetAddress addr;
1430 try {
1431 addr = InetAddress.getByAddress(hostAddress);
1432 } catch (UnknownHostException e) {
1433 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1434 return false;
1435 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001436
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001437 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001438 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 return false;
1440 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001441
1442 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1443 if (nai == null) {
1444 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1445 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1446 } else {
1447 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1448 }
1449 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001450 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001451
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001452 DetailedState netState;
1453 synchronized (nai) {
1454 netState = nai.networkInfo.getDetailedState();
1455 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001456
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001457 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001458 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001459 log("requestRouteToHostAddress on down network "
1460 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001461 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001462 }
1463 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001464 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001465
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001466 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001467 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001468 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001469 LinkProperties lp;
1470 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001471 synchronized (nai) {
1472 lp = nai.linkProperties;
1473 netId = nai.network.netId;
1474 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001475 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001476 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1477 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001478 } finally {
1479 Binder.restoreCallingIdentity(token);
1480 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001481 }
1482
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001483 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001484 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001485 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001486 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001487 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001488 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001489 if (bestRoute.getGateway().equals(addr)) {
1490 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001491 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001492 } else {
1493 // if we will connect to this through another route, add a direct route
1494 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001495 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001496 }
1497 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001498 if (DBG) log("Adding legacy route " + bestRoute +
1499 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001500 try {
1501 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1502 } catch (Exception e) {
1503 // never crash - catch them all
1504 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001505 return false;
1506 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001507 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 }
1509
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001510 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1511 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001512 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001513 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001514 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001515 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001516 }
1517
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001518 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001519 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001520 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001521 if (oldRules == uidRules) return;
1522
Felipe Leme781ba142016-05-09 16:24:48 -07001523 if (uidRules == RULE_NONE) {
1524 mUidRules.delete(uid);
1525 } else {
1526 mUidRules.put(uid, uidRules);
1527 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001528 }
1529
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001530 // TODO: notify UID when it has requested targeted updates
1531 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001532
1533 @Override
1534 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001535 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001536 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001537 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001538 }
1539
1540 synchronized (mRulesLock) {
1541 mMeteredIfaces.clear();
1542 for (String iface : meteredIfaces) {
1543 mMeteredIfaces.add(iface);
1544 }
1545 }
1546 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001547
1548 @Override
1549 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1550 // caller is NPMS, since we only register with them
1551 if (LOGD_RULES) {
1552 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1553 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001554
1555 synchronized (mRulesLock) {
1556 mRestrictBackground = restrictBackground;
1557 }
1558
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001559 if (restrictBackground) {
1560 log("onRestrictBackgroundChanged(true): disabling tethering");
1561 mTethering.untetherAll();
1562 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001563 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001564
1565 @Override
1566 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1567 if (LOGD_RULES) {
1568 // caller is NPMS, since we only register with them
1569 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1570 + whitelisted + ")");
1571 }
1572 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001573 @Override
1574 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1575 if (LOGD_RULES) {
1576 // caller is NPMS, since we only register with them
1577 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1578 + blacklisted + ")");
1579 }
1580 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001581 };
1582
Robin Lee3b3dd942015-05-12 18:14:58 +01001583 /**
1584 * Require that the caller is either in the same user or has appropriate permission to interact
1585 * across users.
1586 *
1587 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1588 */
1589 private void enforceCrossUserPermission(int userId) {
1590 if (userId == UserHandle.getCallingUserId()) {
1591 // Not a cross-user call.
1592 return;
1593 }
1594 mContext.enforceCallingOrSelfPermission(
1595 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1596 "ConnectivityService");
1597 }
1598
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001599 private void enforceInternetPermission() {
1600 mContext.enforceCallingOrSelfPermission(
1601 android.Manifest.permission.INTERNET,
1602 "ConnectivityService");
1603 }
1604
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001606 mContext.enforceCallingOrSelfPermission(
1607 android.Manifest.permission.ACCESS_NETWORK_STATE,
1608 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001609 }
1610
1611 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001612 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001613 }
1614
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001615 private void enforceTetherAccessPermission() {
1616 mContext.enforceCallingOrSelfPermission(
1617 android.Manifest.permission.ACCESS_NETWORK_STATE,
1618 "ConnectivityService");
1619 }
1620
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001621 private void enforceConnectivityInternalPermission() {
1622 mContext.enforceCallingOrSelfPermission(
1623 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1624 "ConnectivityService");
1625 }
1626
Hugo Benichi514da602016-07-19 15:59:27 +09001627 private void enforceConnectivityRestrictedNetworksPermission() {
1628 try {
1629 mContext.enforceCallingOrSelfPermission(
1630 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1631 "ConnectivityService");
1632 return;
1633 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1634 enforceConnectivityInternalPermission();
1635 }
1636
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001637 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001638 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001639 }
1640
Lorenzo Colitti18660282016-07-04 12:55:44 +09001641 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001642 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001643 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001644 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001645 }
1646
1647 private void sendInetConditionBroadcast(NetworkInfo info) {
1648 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1649 }
1650
Wink Saville628b0852011-08-04 15:01:58 -07001651 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001652 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001653 info = new NetworkInfo(info);
1654 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001655 }
1656
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001657 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001658 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001659 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 if (info.isFailover()) {
1661 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1662 info.setFailover(false);
1663 }
1664 if (info.getReason() != null) {
1665 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1666 }
1667 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001668 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1669 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001670 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001671 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001672 return intent;
1673 }
1674
1675 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1676 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1677 }
1678
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001679 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001680 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1681 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1682 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001683 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001684 final long ident = Binder.clearCallingIdentity();
1685 try {
1686 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1687 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1688 } finally {
1689 Binder.restoreCallingIdentity(ident);
1690 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001691 }
1692
Mike Lockwood0f79b542009-08-14 14:18:49 -04001693 private void sendStickyBroadcast(Intent intent) {
1694 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001695 if (!mSystemReady) {
1696 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001697 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001698 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001699 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001700 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001701 }
1702
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001703 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001704 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001705 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001706 final NetworkInfo ni = intent.getParcelableExtra(
1707 ConnectivityManager.EXTRA_NETWORK_INFO);
1708 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1709 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1710 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001711 } else {
1712 BroadcastOptions opts = BroadcastOptions.makeBasic();
1713 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1714 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001715 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001716 final IBatteryStats bs = BatteryStatsService.getService();
1717 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001718 bs.noteConnectivityChanged(intent.getIntExtra(
1719 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1720 ni != null ? ni.getState().toString() : "?");
1721 } catch (RemoteException e) {
1722 }
1723 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001724 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001725 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001726 } finally {
1727 Binder.restoreCallingIdentity(ident);
1728 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001729 }
1730 }
1731
1732 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001733 loadGlobalProxy();
1734
Mike Lockwood0f79b542009-08-14 14:18:49 -04001735 synchronized(this) {
1736 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001737 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001738 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001739 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001740 }
1741 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001742 // load the global proxy at startup
1743 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001744
Robin Lee244ce8e2016-01-05 18:03:46 +00001745 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1746 // for user to unlock device too.
1747 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001748
Erik Klineda4bfa82015-04-30 12:58:40 +09001749 // Configure whether mobile data is always on.
1750 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1751
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001752 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001753
1754 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001755 }
1756
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001758 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001759 *
1760 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001761 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001762 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001763 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1764 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001765
1766 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001767 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001768
Robert Greenwalt7b816022014-04-18 15:25:25 -07001769 if (networkAgent.networkCapabilities.hasTransport(
1770 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001771 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1772 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001773 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001774 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001775 } else if (networkAgent.networkCapabilities.hasTransport(
1776 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001777 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1778 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001779 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001780 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001781 } else {
1782 // do not track any other networks
1783 timeout = 0;
1784 }
1785
Robert Greenwalt7b816022014-04-18 15:25:25 -07001786 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001787 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001788 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001789 } catch (Exception e) {
1790 // You shall not crash!
1791 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001792 }
1793 }
1794 }
1795
1796 /**
1797 * Remove data activity tracking when network disconnects.
1798 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001799 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1800 final String iface = networkAgent.linkProperties.getInterfaceName();
1801 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001802
Robert Greenwalt7b816022014-04-18 15:25:25 -07001803 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1804 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001805 try {
1806 // the call fails silently if no idletimer setup for this interface
1807 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001808 } catch (Exception e) {
1809 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001810 }
1811 }
1812 }
1813
1814 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001815 * Reads the network specific MTU size from reources.
1816 * and set it on it's iface.
1817 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001818 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1819 final String iface = newLp.getInterfaceName();
1820 final int mtu = newLp.getMtu();
1821 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1822 if (VDBG) log("identical MTU - not setting");
1823 return;
1824 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001825
Robert Greenwalt43074032014-08-15 17:53:05 -07001826 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001827 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001828 return;
1829 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001830
w1997615afd812014-08-05 15:18:11 -07001831 // Cannot set MTU without interface name
1832 if (TextUtils.isEmpty(iface)) {
1833 loge("Setting MTU size with null iface.");
1834 return;
1835 }
1836
Robert Greenwalt7b816022014-04-18 15:25:25 -07001837 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001838 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001839 mNetd.setMtu(iface, mtu);
1840 } catch (Exception e) {
1841 Slog.e(TAG, "exception in setMtu()" + e);
1842 }
1843 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001844
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001845 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001846 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1847
1848 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001849 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001850 protected int getDefaultTcpRwnd() {
1851 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1852 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001853
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001854 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1855 if (isDefaultNetwork(nai) == false) {
1856 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001857 }
1858
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001859 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1860 String[] values = null;
1861 if (tcpBufferSizes != null) {
1862 values = tcpBufferSizes.split(",");
1863 }
1864
1865 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001866 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001867 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1868 values = tcpBufferSizes.split(",");
1869 }
1870
1871 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1872
1873 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001874 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001875
1876 final String prefix = "/sys/kernel/ipv4/tcp_";
1877 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1878 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1879 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1880 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1881 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1882 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1883 mCurrentTcpBufferSizes = tcpBufferSizes;
1884 } catch (IOException e) {
1885 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001886 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001887
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001888 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001889 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001890 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1891 if (rwndValue != 0) {
1892 SystemProperties.set(sysctlKey, rwndValue.toString());
1893 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001894 }
1895
Mattias Falk8b47b362011-08-23 14:15:13 +02001896 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001897 /*
1898 * Tell the VMs to toss their DNS caches
1899 */
1900 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1901 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001902 /*
1903 * Connectivity events can happen before boot has completed ...
1904 */
1905 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001906 final long ident = Binder.clearCallingIdentity();
1907 try {
1908 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1909 } finally {
1910 Binder.restoreCallingIdentity(ident);
1911 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001912 }
1913
Robert Greenwalt562cc542014-05-15 18:07:26 -07001914 @Override
1915 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001916 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1917 NETWORK_RESTORE_DELAY_PROP_NAME);
1918 if(restoreDefaultNetworkDelayStr != null &&
1919 restoreDefaultNetworkDelayStr.length() != 0) {
1920 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001921 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001922 } catch (NumberFormatException e) {
1923 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001924 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001925 // if the system property isn't set, use the value for the apn type
1926 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1927
1928 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1929 (mNetConfigs[networkType] != null)) {
1930 ret = mNetConfigs[networkType].restoreTime;
1931 }
1932 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001933 }
1934
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001935 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001936 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001937 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001938 }
1939 return false;
1940 }
1941
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001942 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1943 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1944 final long DIAG_TIME_MS = 5000;
1945 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1946 // Start gathering diagnostic information.
1947 netDiags.add(new NetworkDiagnostics(
1948 nai.network,
1949 new LinkProperties(nai.linkProperties), // Must be a copy.
1950 DIAG_TIME_MS));
1951 }
1952
1953 for (NetworkDiagnostics netDiag : netDiags) {
1954 pw.println();
1955 netDiag.waitForMeasurements();
1956 netDiag.dump(pw);
1957 }
1958 }
1959
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001961 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1962 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001963 if (mContext.checkCallingOrSelfPermission(
1964 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001966 pw.println("Permission Denial: can't dump ConnectivityService " +
1967 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1968 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 return;
1970 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001971
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001972 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001973 dumpNetworkDiagnostics(pw);
1974 return;
1975 }
Erik Kline379747a2015-06-05 17:47:34 +09001976
Lorenzo Colittie3805462015-06-03 11:18:24 +09001977 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001978 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001979 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001980 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001981 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001982 pw.println();
1983
Paul Jensen85cf78e2015-06-25 13:25:07 -04001984 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001985 pw.print("Active default network: ");
1986 if (defaultNai == null) {
1987 pw.println("none");
1988 } else {
1989 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001990 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001991 pw.println();
1992
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001993 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001994 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001995 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1996 pw.println(nai.toString());
1997 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001998 pw.println(String.format("Requests: %d request/%d total",
1999 nai.numRequestNetworkRequests(), nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002000 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002001 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2002 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002003 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002004 pw.decreaseIndent();
2005 pw.println("Lingered:");
2006 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002007 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002008 pw.decreaseIndent();
2009 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002010 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002011 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002012 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002013
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002014 pw.println("Metered Interfaces:");
2015 pw.increaseIndent();
2016 for (String value : mMeteredIfaces) {
2017 pw.println(value);
2018 }
2019 pw.decreaseIndent();
2020 pw.println();
2021
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002022 pw.print("Restrict background: ");
2023 pw.println(mRestrictBackground);
2024 pw.println();
2025
Felipe Leme46c4fc32016-05-04 09:21:43 -07002026 pw.println("Status for known UIDs:");
2027 pw.increaseIndent();
2028 final int size = mUidRules.size();
2029 for (int i = 0; i < size; i++) {
2030 final int uid = mUidRules.keyAt(i);
2031 pw.print("UID=");
2032 pw.print(uid);
2033 final int uidRules = mUidRules.get(uid, RULE_NONE);
2034 pw.print(" rules=");
2035 pw.print(uidRulesToString(uidRules));
2036 pw.println();
2037 }
2038 pw.println();
2039 pw.decreaseIndent();
2040
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002041 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002042 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002043 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2044 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002045 }
2046 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002047 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002048
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002049 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002050
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002051 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002052 pw.print("mNetTransitionWakeLock: currently " +
2053 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2054 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2055 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2056 } else {
2057 pw.println(", last requested never");
2058 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002059 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002060
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002061 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002062 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002063
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002064 pw.println();
2065 mKeepaliveTracker.dump(pw);
2066
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002067 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002068 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002069
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002070 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09002071 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002072 pw.println();
2073 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002074 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002075 for(int i = 0; i < mInetLog.size(); i++) {
2076 pw.println(mInetLog.get(i));
2077 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002078 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002079 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002080
2081 if (argsContain(args, "--short") == false) {
2082 pw.println();
2083 synchronized (mValidationLogs) {
2084 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002085 for (ValidationLog p : mValidationLogs) {
2086 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002087 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002088 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002089 pw.decreaseIndent();
2090 }
2091 }
Erik Kline7523eb32015-07-09 18:24:03 +09002092
2093 pw.println();
2094 pw.println("mNetworkRequestInfoLogs (most recent first):");
2095 pw.increaseIndent();
2096 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2097 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002098
2099 pw.println();
2100 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2101 pw.increaseIndent();
2102 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2103 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002104 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002105 }
2106
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002107 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002108 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002109 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002110 if (officialNai != null && officialNai.equals(nai)) return true;
2111 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002112 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002113 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002114 " - " + nai);
2115 }
2116 return false;
2117 }
2118
Robert Greenwalt42acef32009-08-12 16:08:25 -07002119 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002120 private class NetworkStateTrackerHandler extends Handler {
2121 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002122 super(looper);
2123 }
2124
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002125 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002126 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002127 default:
2128 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002129 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002130 handleAsyncChannelHalfConnect(msg);
2131 break;
2132 }
2133 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2134 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2135 if (nai != null) nai.asyncChannel.disconnect();
2136 break;
2137 }
2138 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2139 handleAsyncChannelDisconnected(msg);
2140 break;
2141 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002142 }
2143 return true;
2144 }
2145
2146 private void maybeHandleNetworkAgentMessage(Message msg) {
2147 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2148 if (nai == null) {
2149 if (VDBG) {
2150 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2151 log(String.format("%s from unknown NetworkAgent", what));
2152 }
2153 return;
2154 }
2155
2156 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002157 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002158 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2159 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2160 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2161 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002162 }
Robin Lee585e2482016-05-01 23:00:00 +01002163 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002164 networkCapabilities)) {
2165 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2166 + nai.networkCapabilities + " -> " + networkCapabilities);
2167 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002168 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002169 break;
2170 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002171 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002172 if (VDBG) {
2173 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002174 "; created=" + nai.created +
2175 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002176 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002177 LinkProperties oldLp = nai.linkProperties;
2178 synchronized (nai) {
2179 nai.linkProperties = (LinkProperties)msg.obj;
2180 }
Robin Lee585e2482016-05-01 23:00:00 +01002181 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002182 break;
2183 }
2184 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002185 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002186 updateNetworkInfo(nai, info);
2187 break;
2188 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002189 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002190 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002191 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002192 break;
2193 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002194 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002195 try {
2196 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002197 } catch (Exception e) {
2198 // Never crash!
2199 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002200 }
2201 break;
2202 }
2203 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002204 try {
2205 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002206 } catch (Exception e) {
2207 // Never crash!
2208 loge("Exception in removeVpnUidRanges: " + e);
2209 }
2210 break;
2211 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002212 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002213 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2214 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002215 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002216 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002217 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002218 break;
2219 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002220 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002221 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2222 break;
2223 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002224 }
2225 }
2226
2227 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2228 switch (msg.what) {
2229 default:
2230 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002231 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002232 final NetworkAgentInfo nai;
2233 synchronized (mNetworkForNetId) {
2234 nai = mNetworkForNetId.get(msg.arg2);
2235 }
2236 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002237 final boolean valid =
2238 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002239 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002240 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2241 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002242 if (valid != nai.lastValidated) {
2243 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002244 nai.lastValidated = valid;
2245 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002246 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002247 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2248 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002249 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002250 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002251 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002252 Bundle redirectUrlBundle = new Bundle();
2253 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002254 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002255 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002256 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002257 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002258 if (wasValidated && !nai.lastValidated) {
2259 handleNetworkUnvalidated(nai);
2260 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002261 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002262 break;
2263 }
Paul Jensen869868be2014-05-15 10:33:05 -04002264 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002265 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002266 final boolean visible = (msg.arg1 != 0);
2267 final NetworkAgentInfo nai;
2268 synchronized (mNetworkForNetId) {
2269 nai = mNetworkForNetId.get(netId);
2270 }
2271 // If captive portal status has changed, update capabilities.
2272 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002273 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002274 nai.lastCaptivePortalDetected = visible;
2275 nai.everCaptivePortalDetected |= visible;
Hugo Benichif15b2822016-09-15 18:18:48 +09002276 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002277 }
2278 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002279 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002280 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002281 if (nai == null) {
2282 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2283 break;
2284 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002285 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002286 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002287 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002288 }
Paul Jensen869868be2014-05-15 10:33:05 -04002289 }
Paul Jensen869868be2014-05-15 10:33:05 -04002290 break;
2291 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002292 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002293 return true;
2294 }
2295
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002296 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2297 switch (msg.what) {
2298 default:
2299 return false;
2300 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2301 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2302 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2303 handleLingerComplete(nai);
2304 }
2305 break;
2306 }
2307 }
2308 return true;
2309 }
2310
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002311 @Override
2312 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002313 if (!maybeHandleAsyncChannelMessage(msg) &&
2314 !maybeHandleNetworkMonitorMessage(msg) &&
2315 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002316 maybeHandleNetworkAgentMessage(msg);
2317 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002318 }
2319 }
2320
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002321 private void updateLingerState(NetworkAgentInfo nai, long now) {
2322 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2323 // 2. If the network was lingering and there are now requests, unlinger it.
2324 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2325 // one lingered request, start lingering.
2326 nai.updateLingerTimer();
2327 if (nai.isLingering() && nai.numRequestNetworkRequests() > 0) {
2328 if (DBG) log("Unlingering " + nai.name());
2329 nai.unlinger();
2330 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
2331 } else if (unneeded(nai) && nai.getLingerExpiry() > 0) { // unneeded() calls isLingering()
2332 int lingerTime = (int) (nai.getLingerExpiry() - now);
2333 if (DBG) {
2334 Log.d(TAG, "Lingering " + nai.name() + " for " + lingerTime + "ms");
2335 }
2336 nai.linger();
2337 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2338 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2339 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002340 }
2341
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342 private void handleAsyncChannelHalfConnect(Message msg) {
2343 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002344 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002345 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2346 if (VDBG) log("NetworkFactory connected");
2347 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002348 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002349 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002350 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002351 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002352 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 }
2354 } else {
2355 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002356 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002357 }
2358 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2359 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2360 if (VDBG) log("NetworkAgent connected");
2361 // A network agent has requested a connection. Establish the connection.
2362 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2363 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2364 } else {
2365 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002366 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002367 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002368 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002369 synchronized (mNetworkForNetId) {
2370 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002371 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002372 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002373 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002374 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002375 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002376 }
2377 }
2378 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002379
Robert Greenwalt7b816022014-04-18 15:25:25 -07002380 private void handleAsyncChannelDisconnected(Message msg) {
2381 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2382 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002383 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002384 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002385 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002386 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002387 // TODO - if we move the logic to the network agent (have them disconnect
2388 // because they lost all their requests or because their score isn't good)
2389 // then they would disconnect organically, report their new state and then
2390 // disconnect the channel.
2391 if (nai.networkInfo.isConnected()) {
2392 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2393 null, null);
2394 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002395 final boolean wasDefault = isDefaultNetwork(nai);
2396 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002397 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002398 // Log default network disconnection before required book-keeping.
2399 // Let rematchAllNetworksAndRequests() below record a new default network event
2400 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2401 // whose timestamps tell how long it takes to recover a default network.
2402 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002403 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002404 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002405 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2406 // by other networks that are already connected. Perhaps that can be done by
2407 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2408 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002409 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002410 mKeepaliveTracker.handleStopAllKeepalives(nai,
2411 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002412 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002413 mNetworkAgentInfos.remove(msg.replyTo);
2414 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002415 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002416 // Remove the NetworkAgent, but don't mark the netId as
2417 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002418 mNetworkForNetId.remove(nai.network.netId);
2419 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002420 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002421 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2422 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002423 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2424 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2425 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002426 sendUpdatedScoreToFactories(request, 0);
2427 }
2428 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002429 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002430 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002431 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002432 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002433 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002434 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002435 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002436 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002437 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002438 if (nai.created) {
2439 // Tell netd to clean up the configuration for this network
2440 // (routing rules, DNS, etc).
2441 // This may be slow as it requires a lot of netd shelling out to ip and
2442 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2443 // after we've rematched networks with requests which should make a potential
2444 // fallback network the default or requested a new network from the
2445 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2446 // long time.
2447 try {
2448 mNetd.removeNetwork(nai.network.netId);
2449 } catch (Exception e) {
2450 loge("Exception removing network: " + e);
2451 }
2452 }
2453 synchronized (mNetworkForNetId) {
2454 mNetIdInUse.delete(nai.network.netId);
2455 }
2456 } else {
2457 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2458 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002459 }
2460 }
2461
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002462 // If this method proves to be too slow then we can maintain a separate
2463 // pendingIntent => NetworkRequestInfo map.
2464 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2465 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2466 Intent intent = pendingIntent.getIntent();
2467 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2468 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2469 if (existingPendingIntent != null &&
2470 existingPendingIntent.getIntent().filterEquals(intent)) {
2471 return entry.getValue();
2472 }
2473 }
2474 return null;
2475 }
2476
2477 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2478 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2479
2480 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2481 if (existingRequest != null) { // remove the existing request.
2482 if (DBG) log("Replacing " + existingRequest.request + " with "
2483 + nri.request + " because their intents matched.");
2484 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2485 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002486 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002487 }
2488
Erik Klineda4bfa82015-04-30 12:58:40 +09002489 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002490 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002491 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002492 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002493 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002494 if (nri.request.networkCapabilities.hasSignalStrength() &&
2495 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2496 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002497 }
2498 }
2499 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002500 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002501 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002502 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002503 }
2504 }
2505
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002506 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2507 int callingUid) {
2508 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2509 if (nri != null) {
2510 handleReleaseNetworkRequest(nri.request, callingUid);
2511 }
2512 }
2513
Paul Jensen99364842014-12-09 11:43:45 -05002514 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002515 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2516 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002517 private boolean unneeded(NetworkAgentInfo nai) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002518 if (!nai.everConnected || nai.isVPN() ||
2519 nai.isLingering() || nai.numRequestNetworkRequests() > 0) {
2520 return false;
2521 }
Paul Jensene0988542015-06-25 15:30:08 -04002522 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2523 // If this Network is already the highest scoring Network for a request, or if
2524 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002525 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002526 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002527 // Note that this catches two important cases:
2528 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2529 // is currently satisfying the request. This is desirable when
2530 // cellular ends up validating but WiFi does not.
2531 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002532 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002533 // WiFi ends up validating and out scoring cellular.
2534 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2535 nai.getCurrentScoreAsValidated())) {
2536 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002537 }
2538 }
Paul Jensene0988542015-06-25 15:30:08 -04002539 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002540 }
2541
Erik Klineacdd6392016-07-07 16:50:58 +09002542 private NetworkRequestInfo getNriForAppRequest(
2543 NetworkRequest request, int callingUid, String requestedOperation) {
2544 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2545
Robert Greenwalt9258c642014-03-26 16:47:06 -07002546 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002547 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002548 log(String.format("UID %d attempted to %s for unowned request %s",
2549 callingUid, requestedOperation, nri));
2550 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002551 }
Erik Klineacdd6392016-07-07 16:50:58 +09002552 }
2553
2554 return nri;
2555 }
2556
2557 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2558 String description, int callbackType) {
2559 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2560 if (nri == null) return;
2561
2562 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2563 // The network that is satisfying this request may have changed since
2564 // the application requested the update.
2565 //
2566 // - If the request is no longer satisfied, don't send any updates.
2567 // - If the request is satisfied by a different network, it is the
2568 // caller's responsibility to check that the Network object in the
2569 // callback matches the network that was returned in the last
2570 // onAvailable() callback for this request.
2571 if (nai == null) return;
2572 callCallbackForRequest(nri, nai, callbackType, 0);
2573 }
2574
2575 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2576 handleRequestCallbackUpdate(request, callingUid,
2577 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2578 }
2579
2580 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2581 handleRequestCallbackUpdate(request, callingUid,
2582 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2583 }
2584
2585 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2586 final NetworkRequestInfo nri = getNriForAppRequest(
2587 request, callingUid, "release NetworkRequest");
2588 if (nri == null) return;
2589
2590 if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
2591 nri.unlinkDeathRecipient();
2592 mNetworkRequests.remove(request);
2593 synchronized (mUidToNetworkRequestCount) {
2594 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2595 if (requests < 1) {
2596 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2597 nri.mUid);
2598 } else if (requests == 1) {
2599 mUidToNetworkRequestCount.removeAt(
2600 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2601 } else {
2602 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2603 }
2604 }
2605 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2606 if (nri.request.isRequest()) {
2607 boolean wasKept = false;
2608 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2609 if (nai != null) {
2610 nai.removeRequest(nri.request.requestId);
2611 if (VDBG) {
2612 log(" Removing from current network " + nai.name() +
2613 ", leaving " + nai.numNetworkRequests() + " requests.");
2614 }
2615 // If there are still lingered requests on this network, don't tear it down,
2616 // but resume lingering instead.
2617 updateLingerState(nai, SystemClock.elapsedRealtime());
2618 if (unneeded(nai)) {
2619 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2620 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002621 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002622 wasKept = true;
2623 }
2624 mNetworkForRequestId.remove(nri.request.requestId);
2625 }
2626
2627 // TODO: remove this code once we know that the Slog.wtf is never hit.
2628 //
2629 // Find all networks that are satisfying this request and remove the request
2630 // from their request lists.
2631 // TODO - it's my understanding that for a request there is only a single
2632 // network satisfying it, so this loop is wasteful
2633 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2634 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2635 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2636 otherNai.name() + ", but mNetworkAgentInfos says " +
2637 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002638 }
2639 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002640
Erik Klineacdd6392016-07-07 16:50:58 +09002641 // Maintain the illusion. When this request arrived, we might have pretended
2642 // that a network connected to serve it, even though the network was already
2643 // connected. Now that this request has gone away, we might have to pretend
2644 // that the network disconnected. LegacyTypeTracker will generate that
2645 // phantom disconnect for this type.
2646 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2647 boolean doRemove = true;
2648 if (wasKept) {
2649 // check if any of the remaining requests for this network are for the
2650 // same legacy type - if so, don't remove the nai
2651 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2652 NetworkRequest otherRequest = nai.requestAt(i);
2653 if (otherRequest.legacyType == nri.request.legacyType &&
2654 otherRequest.isRequest()) {
2655 if (DBG) log(" still have other legacy request - leaving");
2656 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002657 }
2658 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002659 }
2660
Erik Klineacdd6392016-07-07 16:50:58 +09002661 if (doRemove) {
2662 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002663 }
2664 }
Erik Klineacdd6392016-07-07 16:50:58 +09002665
2666 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2667 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2668 nri.request);
2669 }
2670 } else {
2671 // listens don't have a singular affectedNetwork. Check all networks to see
2672 // if this listen request applies and remove it.
2673 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2674 nai.removeRequest(nri.request.requestId);
2675 if (nri.request.networkCapabilities.hasSignalStrength() &&
2676 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2677 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2678 }
2679 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002680 }
Erik Klineacdd6392016-07-07 16:50:58 +09002681 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002682 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002683
Lorenzo Colitti18660282016-07-04 12:55:44 +09002684 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002685 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2686 enforceConnectivityInternalPermission();
2687 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2688 accept ? 1 : 0, always ? 1: 0, network));
2689 }
2690
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002691 @Override
2692 public void setAvoidUnvalidated(Network network) {
2693 enforceConnectivityInternalPermission();
2694 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2695 }
2696
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002697 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2698 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2699 " accept=" + accept + " always=" + always);
2700
2701 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2702 if (nai == null) {
2703 // Nothing to do.
2704 return;
2705 }
2706
2707 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002708 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002709 return;
2710 }
2711
2712 if (!nai.networkMisc.explicitlySelected) {
2713 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2714 }
2715
2716 if (accept != nai.networkMisc.acceptUnvalidated) {
2717 int oldScore = nai.getCurrentScore();
2718 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002719 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002720 sendUpdatedScoreToFactories(nai);
2721 }
2722
2723 if (always) {
2724 nai.asyncChannel.sendMessage(
2725 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2726 }
2727
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002728 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002729 // Tell the NetworkAgent to not automatically reconnect to the network.
2730 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2731 // Teardown the nework.
2732 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002733 }
2734
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002735 }
2736
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002737 private void handleSetAvoidUnvalidated(Network network) {
2738 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2739 if (nai == null || nai.lastValidated) {
2740 // Nothing to do. The network either disconnected or revalidated.
2741 return;
2742 }
2743 if (!nai.avoidUnvalidated) {
2744 int oldScore = nai.getCurrentScore();
2745 nai.avoidUnvalidated = true;
2746 rematchAllNetworksAndRequests(nai, oldScore);
2747 sendUpdatedScoreToFactories(nai);
2748 }
2749 }
2750
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002751 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002752 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002753 mHandler.sendMessageDelayed(
2754 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2755 PROMPT_UNVALIDATED_DELAY_MS);
2756 }
2757
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002758 private boolean mAvoidBadWifi = true;
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002759
Hugo Benichic8e9e122016-09-14 23:23:08 +00002760 public boolean avoidBadWifi() {
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002761 return mAvoidBadWifi;
2762 }
2763
2764 @VisibleForTesting
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002765 /** Whether the device or carrier configuration disables avoiding bad wifi by default. */
2766 public boolean configRestrictsAvoidBadWifi() {
2767 return mContext.getResources().getInteger(R.integer.config_networkAvoidBadWifi) == 0;
2768 }
2769
2770 /** Whether we should display a notification when wifi becomes unvalidated. */
2771 public boolean shouldNotifyWifiUnvalidated() {
2772 return configRestrictsAvoidBadWifi() &&
2773 Settings.Global.getString(mContext.getContentResolver(),
2774 Settings.Global.NETWORK_AVOID_BAD_WIFI) == null;
2775 }
2776
2777 private boolean updateAvoidBadWifi() {
2778 boolean settingAvoidBadWifi = "1".equals(Settings.Global.getString(
2779 mContext.getContentResolver(), Settings.Global.NETWORK_AVOID_BAD_WIFI));
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002780
2781 boolean prev = mAvoidBadWifi;
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002782 mAvoidBadWifi = settingAvoidBadWifi || !configRestrictsAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002783 return mAvoidBadWifi != prev;
Hugo Benichic8e9e122016-09-14 23:23:08 +00002784 }
2785
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002786 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
2787 boolean configRestrict = configRestrictsAvoidBadWifi();
2788 if (!configRestrict) {
2789 pw.println("Bad Wi-Fi avoidance: unrestricted");
2790 return;
2791 }
2792
2793 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2794 pw.increaseIndent();
2795 pw.println("Config restrict: " + configRestrict);
2796
2797 String value = Settings.Global.getString(
2798 mContext.getContentResolver(), Settings.Global.NETWORK_AVOID_BAD_WIFI);
2799 String description;
2800 // Can't use a switch statement because strings are legal case labels, but null is not.
2801 if ("0".equals(value)) {
2802 description = "get stuck";
2803 } else if (value == null) {
2804 description = "prompt";
2805 } else if ("1".equals(value)) {
2806 description = "avoid";
2807 } else {
2808 description = value + " (?)";
2809 }
2810 pw.println("User setting: " + description);
2811 pw.println("Network overrides:");
2812 pw.increaseIndent();
2813 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2814 if (nai.avoidUnvalidated) {
2815 pw.println(nai.name());
2816 }
2817 }
2818 pw.decreaseIndent();
2819 pw.decreaseIndent();
2820 }
2821
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002822 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2823 final String action;
2824 switch (type) {
2825 case NO_INTERNET:
2826 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2827 break;
2828 case LOST_INTERNET:
2829 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2830 break;
2831 default:
2832 Slog.wtf(TAG, "Unknown notification type " + type);
2833 return;
2834 }
2835
2836 Intent intent = new Intent(action);
2837 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2838 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2839 intent.setClassName("com.android.settings",
2840 "com.android.settings.wifi.WifiNoInternetDialog");
2841
2842 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2843 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2844 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2845 }
2846
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002847 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002848 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002849 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2850
2851 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2852 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002853 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002854 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002855 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2856 return;
2857 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002858 showValidationNotification(nai, NotificationType.NO_INTERNET);
2859 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002860
Lorenzo Colitti73b209382016-09-15 22:18:09 +09002861 // TODO: Delete this like updateMobileDataAlwaysOn above.
2862 @VisibleForTesting
2863 void updateNetworkAvoidBadWifi() {
2864 mHandler.sendEmptyMessage(EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI);
2865 }
2866
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002867 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2868 NetworkCapabilities nc = nai.networkCapabilities;
2869 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002870
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002871 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) && shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002872 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2873 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002874 }
2875
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002876 private class InternalHandler extends Handler {
2877 public InternalHandler(Looper looper) {
2878 super(looper);
2879 }
2880
2881 @Override
2882 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002883 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002884 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002885 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002886 String causedBy = null;
2887 synchronized (ConnectivityService.this) {
2888 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2889 mNetTransitionWakeLock.isHeld()) {
2890 mNetTransitionWakeLock.release();
2891 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002892 } else {
2893 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002894 }
2895 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002896 if (VDBG) {
2897 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2898 log("Failed to find a new network - expiring NetTransition Wakelock");
2899 } else {
2900 log("NetTransition Wakelock (" +
2901 (causedBy == null ? "unknown" : causedBy) +
2902 " cleared because we found a replacement network");
2903 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002904 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002905 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002906 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002907 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002908 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002909 break;
2910 }
Jason Monkdecd2952013-10-10 14:02:51 -04002911 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002912 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002913 break;
2914 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002915 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002916 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2917 break;
2918 }
2919 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2920 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002921 break;
2922 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002923 case EVENT_REGISTER_NETWORK_AGENT: {
2924 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2925 break;
2926 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002927 case EVENT_REGISTER_NETWORK_REQUEST:
2928 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002929 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002930 break;
2931 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002932 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2933 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002934 handleRegisterNetworkRequestWithIntent(msg);
2935 break;
2936 }
2937 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2938 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2939 break;
2940 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002941 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002942 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002943 break;
2944 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002945 case EVENT_SET_ACCEPT_UNVALIDATED: {
2946 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2947 break;
2948 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002949 case EVENT_SET_AVOID_UNVALIDATED: {
2950 handleSetAvoidUnvalidated((Network) msg.obj);
2951 break;
2952 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002953 case EVENT_PROMPT_UNVALIDATED: {
2954 handlePromptUnvalidated((Network) msg.obj);
2955 break;
2956 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002957 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2958 handleMobileDataAlwaysOn();
2959 break;
2960 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002961 case EVENT_CONFIGURE_NETWORK_AVOID_BAD_WIFI: {
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002962 if (updateAvoidBadWifi()) {
2963 rematchAllNetworksAndRequests(null, 0);
2964 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002965 break;
2966 }
Erik Klineacdd6392016-07-07 16:50:58 +09002967 case EVENT_REQUEST_LINKPROPERTIES:
2968 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2969 break;
2970 case EVENT_REQUEST_NETCAPABILITIES:
2971 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2972 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002973 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2974 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2975 mKeepaliveTracker.handleStartKeepalive(msg);
2976 break;
2977 }
2978 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2979 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2980 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2981 int slot = msg.arg1;
2982 int reason = msg.arg2;
2983 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2984 break;
2985 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002986 case EVENT_SYSTEM_READY: {
2987 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2988 nai.networkMonitor.systemReady = true;
2989 }
2990 break;
2991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002992 }
2993 }
2994 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002995
2996 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002997 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002998 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002999 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003000 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003001 final int status = mTethering.tether(iface);
3002 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
3003 try {
3004 mPolicyManager.onTetheringChanged(iface, true);
3005 } catch (RemoteException e) {
3006 }
3007 }
3008 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003009 } else {
3010 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3011 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003012 }
3013
3014 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003015 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003016 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003017 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003018
3019 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003020 final int status = mTethering.untether(iface);
3021 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
3022 try {
3023 mPolicyManager.onTetheringChanged(iface, false);
3024 } catch (RemoteException e) {
3025 }
3026 }
3027 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003028 } else {
3029 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3030 }
3031 }
3032
3033 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003034 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003035 public int getLastTetherError(String iface) {
3036 enforceTetherAccessPermission();
3037
3038 if (isTetheringSupported()) {
3039 return mTethering.getLastTetherError(iface);
3040 } else {
3041 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3042 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003043 }
3044
3045 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003046 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003047 public String[] getTetherableUsbRegexs() {
3048 enforceTetherAccessPermission();
3049 if (isTetheringSupported()) {
3050 return mTethering.getTetherableUsbRegexs();
3051 } else {
3052 return new String[0];
3053 }
3054 }
3055
Lorenzo Colitti18660282016-07-04 12:55:44 +09003056 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003057 public String[] getTetherableWifiRegexs() {
3058 enforceTetherAccessPermission();
3059 if (isTetheringSupported()) {
3060 return mTethering.getTetherableWifiRegexs();
3061 } else {
3062 return new String[0];
3063 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003064 }
3065
Lorenzo Colitti18660282016-07-04 12:55:44 +09003066 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003067 public String[] getTetherableBluetoothRegexs() {
3068 enforceTetherAccessPermission();
3069 if (isTetheringSupported()) {
3070 return mTethering.getTetherableBluetoothRegexs();
3071 } else {
3072 return new String[0];
3073 }
3074 }
3075
Lorenzo Colitti18660282016-07-04 12:55:44 +09003076 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003077 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003078 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003079 if (isTetheringSupported()) {
3080 return mTethering.setUsbTethering(enable);
3081 } else {
3082 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3083 }
3084 }
3085
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003086 // TODO - move iface listing, queries, etc to new module
3087 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003088 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003089 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003090 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003091 return mTethering.getTetherableIfaces();
3092 }
3093
Lorenzo Colitti18660282016-07-04 12:55:44 +09003094 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003095 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003096 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003097 return mTethering.getTetheredIfaces();
3098 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003099
Lorenzo Colitti18660282016-07-04 12:55:44 +09003100 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003101 public String[] getTetheringErroredIfaces() {
3102 enforceTetherAccessPermission();
3103 return mTethering.getErroredIfaces();
3104 }
3105
Lorenzo Colitti18660282016-07-04 12:55:44 +09003106 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003107 public String[] getTetheredDhcpRanges() {
3108 enforceConnectivityInternalPermission();
3109 return mTethering.getTetheredDhcpRanges();
3110 }
3111
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003112 // if ro.tether.denied = true we default to no tethering
3113 // gservices could set the secure setting to 1 though to enable it on a build where it
3114 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003115 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003116 public boolean isTetheringSupported() {
3117 enforceTetherAccessPermission();
3118 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003119 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003120 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3121 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003122 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
3123 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003124 mTethering.getTetherableWifiRegexs().length != 0 ||
3125 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3126 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003127 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003128
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003129 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003130 public void startTethering(int type, ResultReceiver receiver,
3131 boolean showProvisioningUi) {
3132 ConnectivityManager.enforceTetherChangePermission(mContext);
3133 if (!isTetheringSupported()) {
3134 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3135 return;
3136 }
3137 mTethering.startTethering(type, receiver, showProvisioningUi);
3138 }
3139
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003140 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003141 public void stopTethering(int type) {
3142 ConnectivityManager.enforceTetherChangePermission(mContext);
3143 mTethering.stopTethering(type);
3144 }
3145
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003146 // Called when we lose the default network and have no replacement yet.
3147 // This will automatically be cleared after X seconds or a new default network
3148 // becomes CONNECTED, whichever happens first. The timer is started by the
3149 // first caller and not restarted by subsequent callers.
3150 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003151 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003152 synchronized (this) {
3153 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003154 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003155 mNetTransitionWakeLock.acquire();
3156 mNetTransitionWakeLockCausedBy = forWhom;
3157 }
3158 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003159 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003160 mNetTransitionWakeLockTimeout);
3161 return;
3162 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003163
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003164 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003165 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003166 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003167 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003168 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003169 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003170 }
3171
Lorenzo Colitti18660282016-07-04 12:55:44 +09003172 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003173 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003174 enforceAccessPermission();
3175 enforceInternetPermission();
3176
Paul Jensenbfd17b72015-04-07 12:43:13 -04003177 NetworkAgentInfo nai;
3178 if (network == null) {
3179 nai = getDefaultNetwork();
3180 } else {
3181 nai = getNetworkAgentInfoForNetwork(network);
3182 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003183 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3184 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3185 return;
3186 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003187 // Revalidate if the app report does not match our current validated state.
3188 if (hasConnectivity == nai.lastValidated) return;
3189 final int uid = Binder.getCallingUid();
3190 if (DBG) {
3191 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3192 ") by " + uid);
3193 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003194 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003195 // Validating a network that has not yet connected could result in a call to
3196 // rematchNetworkAndRequests() which is not meant to work on such networks.
3197 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003198
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003199 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003200
3201 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3202 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003203 }
3204
Paul Jensencee9b512015-05-06 07:32:40 -04003205 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003206 // this information is already available as a world read/writable jvm property
3207 // so this API change wouldn't have a benifit. It also breaks the passing
3208 // of proxy info to all the JVMs.
3209 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003210 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003211 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003212 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3213 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003214 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003215 }
3216
Lorenzo Colitti18660282016-07-04 12:55:44 +09003217 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003218 public ProxyInfo getProxyForNetwork(Network network) {
3219 if (network == null) return getDefaultProxy();
3220 final ProxyInfo globalProxy = getGlobalProxy();
3221 if (globalProxy != null) return globalProxy;
3222 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3223 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3224 // caller may not have.
3225 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3226 if (nai == null) return null;
3227 synchronized (nai) {
3228 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3229 if (proxyInfo == null) return null;
3230 return new ProxyInfo(proxyInfo);
3231 }
3232 }
3233
Paul Jensene0bef712014-12-10 15:12:18 -05003234 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3235 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3236 // proxy is null then there is no proxy in place).
3237 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3238 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3239 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3240 proxy = null;
3241 }
3242 return proxy;
3243 }
3244
3245 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3246 // better for determining if a new proxy broadcast is necessary:
3247 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3248 // avoid unnecessary broadcasts.
3249 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3250 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3251 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3252 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3253 // all set.
3254 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3255 a = canonicalizeProxyInfo(a);
3256 b = canonicalizeProxyInfo(b);
3257 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3258 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3259 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3260 }
3261
Jason Monk207900c2014-04-25 15:00:09 -04003262 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003263 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003264
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003265 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003266 if (proxyProperties == mGlobalProxy) return;
3267 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3268 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3269
3270 String host = "";
3271 int port = 0;
3272 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003273 String pacFileUrl = "";
3274 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003275 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003276 if (!proxyProperties.isValid()) {
3277 if (DBG)
3278 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3279 return;
3280 }
Jason Monk207900c2014-04-25 15:00:09 -04003281 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003282 host = mGlobalProxy.getHost();
3283 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003284 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003285 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003286 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003287 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003288 } else {
3289 mGlobalProxy = null;
3290 }
3291 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003292 final long token = Binder.clearCallingIdentity();
3293 try {
3294 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3295 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3296 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3297 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003298 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003299 } finally {
3300 Binder.restoreCallingIdentity(token);
3301 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003302
Jason Monkcf0f97a2014-10-02 15:39:38 -04003303 if (mGlobalProxy == null) {
3304 proxyProperties = mDefaultProxy;
3305 }
3306 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003307 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003308 }
3309
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003310 private void loadGlobalProxy() {
3311 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003312 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3313 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3314 String exclList = Settings.Global.getString(res,
3315 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003316 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3317 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003318 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003319 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003320 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003321 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003322 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003323 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003324 if (!proxyProperties.isValid()) {
3325 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3326 return;
3327 }
3328
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003329 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003330 mGlobalProxy = proxyProperties;
3331 }
3332 }
3333 }
3334
Jason Monk207900c2014-04-25 15:00:09 -04003335 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003336 // this information is already available as a world read/writable jvm property
3337 // so this API change wouldn't have a benifit. It also breaks the passing
3338 // of proxy info to all the JVMs.
3339 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003340 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003341 return mGlobalProxy;
3342 }
3343 }
3344
Jason Monk207900c2014-04-25 15:00:09 -04003345 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003346 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003347 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003348 proxy = null;
3349 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003350 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003351 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003352 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003353 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003354 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3355 return;
3356 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003357
3358 // This call could be coming from the PacManager, containing the port of the local
3359 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3360 // global (to get the correct local port), and send a broadcast.
3361 // TODO: Switch PacManager to have its own message to send back rather than
3362 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003363 if ((mGlobalProxy != null) && (proxy != null)
3364 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003365 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3366 mGlobalProxy = proxy;
3367 sendProxyBroadcast(mGlobalProxy);
3368 return;
3369 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003370 mDefaultProxy = proxy;
3371
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003372 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003373 if (!mDefaultProxyDisabled) {
3374 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003375 }
3376 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003377 }
3378
Paul Jensene0bef712014-12-10 15:12:18 -05003379 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3380 // This method gets called when any network changes proxy, but the broadcast only ever contains
3381 // the default proxy (even if it hasn't changed).
3382 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3383 // world where an app might be bound to a non-default network.
3384 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3385 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3386 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3387
3388 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3389 sendProxyBroadcast(getDefaultProxy());
3390 }
3391 }
3392
Robert Greenwalt434203a2010-10-11 16:00:27 -07003393 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003394 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3395 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003396 if (!TextUtils.isEmpty(proxy)) {
3397 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003398 if (data.length == 0) {
3399 return;
3400 }
3401
Robert Greenwalt434203a2010-10-11 16:00:27 -07003402 String proxyHost = data[0];
3403 int proxyPort = 8080;
3404 if (data.length > 1) {
3405 try {
3406 proxyPort = Integer.parseInt(data[1]);
3407 } catch (NumberFormatException e) {
3408 return;
3409 }
3410 }
Jason Monk207900c2014-04-25 15:00:09 -04003411 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003412 setGlobalProxy(p);
3413 }
3414 }
3415
Jason Monk207900c2014-04-25 15:00:09 -04003416 private void sendProxyBroadcast(ProxyInfo proxy) {
3417 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003418 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003419 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003420 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003421 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3422 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003423 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003424 final long ident = Binder.clearCallingIdentity();
3425 try {
3426 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3427 } finally {
3428 Binder.restoreCallingIdentity(ident);
3429 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003430 }
3431
3432 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003433 final private HashMap<Uri, Integer> mUriEventMap;
3434 final private Context mContext;
3435 final private Handler mHandler;
3436
3437 SettingsObserver(Context context, Handler handler) {
3438 super(null);
3439 mUriEventMap = new HashMap<Uri, Integer>();
3440 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003441 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003442 }
3443
Erik Klineda4bfa82015-04-30 12:58:40 +09003444 void observe(Uri uri, int what) {
3445 mUriEventMap.put(uri, what);
3446 final ContentResolver resolver = mContext.getContentResolver();
3447 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003448 }
3449
3450 @Override
3451 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003452 Slog.wtf(TAG, "Should never be reached.");
3453 }
3454
3455 @Override
3456 public void onChange(boolean selfChange, Uri uri) {
3457 final Integer what = mUriEventMap.get(uri);
3458 if (what != null) {
3459 mHandler.obtainMessage(what.intValue()).sendToTarget();
3460 } else {
3461 loge("No matching event to send for URI=" + uri);
3462 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003463 }
3464 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003465
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003466 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003467 Slog.d(TAG, s);
3468 }
3469
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003470 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003471 Slog.e(TAG, s);
3472 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003473
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003474 private static <T> T checkNotNull(T value, String message) {
3475 if (value == null) {
3476 throw new NullPointerException(message);
3477 }
3478 return value;
3479 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003480
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003481 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003482 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003483 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3484 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3485 *
3486 * @param oldPackage Package name of the application which currently controls VPN, which will
3487 * be replaced. If there is no such application, this should should either be
3488 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3489 * @param newPackage Package name of the application which should gain control of VPN, or
3490 * {@code null} to disable.
3491 * @param userId User for whom to prepare the new VPN.
3492 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003493 * @hide
3494 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003495 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003496 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3497 int userId) {
3498 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003499 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003500
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003501 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003502 Vpn vpn = mVpns.get(userId);
3503 if (vpn != null) {
3504 return vpn.prepare(oldPackage, newPackage);
3505 } else {
3506 return false;
3507 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003508 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003509 }
3510
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003511 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003512 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3513 * This method is used by system-privileged apps.
3514 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3515 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3516 *
3517 * @param packageName The package for which authorization state should change.
3518 * @param userId User for whom {@code packageName} is installed.
3519 * @param authorized {@code true} if this app should be able to start a VPN connection without
3520 * explicit user approval, {@code false} if not.
3521 *
Jeff Davidson05542602014-08-11 14:07:27 -07003522 * @hide
3523 */
3524 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003525 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3526 enforceCrossUserPermission(userId);
3527
Jeff Davidson05542602014-08-11 14:07:27 -07003528 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003529 Vpn vpn = mVpns.get(userId);
3530 if (vpn != null) {
3531 vpn.setPackageAuthorization(packageName, authorized);
3532 }
Jeff Davidson05542602014-08-11 14:07:27 -07003533 }
3534 }
3535
3536 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003537 * Configure a TUN interface and return its file descriptor. Parameters
3538 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003539 * and not available in ConnectivityManager. Permissions are checked in
3540 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003541 * @hide
3542 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003543 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003544 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003545 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003546 int user = UserHandle.getUserId(Binder.getCallingUid());
3547 synchronized(mVpns) {
3548 return mVpns.get(user).establish(config);
3549 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003550 }
3551
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003552 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003553 * Start legacy VPN, controlling native daemons as needed. Creates a
3554 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003555 */
3556 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003557 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003558 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003559 final LinkProperties egress = getActiveLinkProperties();
3560 if (egress == null) {
3561 throw new IllegalStateException("Missing active network connection");
3562 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003563 int user = UserHandle.getUserId(Binder.getCallingUid());
3564 synchronized(mVpns) {
3565 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3566 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003567 }
3568
3569 /**
3570 * Return the information of the ongoing legacy VPN. This method is used
3571 * by VpnSettings and not available in ConnectivityManager. Permissions
3572 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003573 */
3574 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003575 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3576 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003577
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003578 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003579 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003580 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003581 }
3582
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003583 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003584 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3585 * and not available in ConnectivityManager.
3586 */
3587 @Override
3588 public VpnInfo[] getAllVpnInfo() {
3589 enforceConnectivityInternalPermission();
3590 if (mLockdownEnabled) {
3591 return new VpnInfo[0];
3592 }
3593
3594 synchronized(mVpns) {
3595 List<VpnInfo> infoList = new ArrayList<>();
3596 for (int i = 0; i < mVpns.size(); i++) {
3597 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3598 if (info != null) {
3599 infoList.add(info);
3600 }
3601 }
3602 return infoList.toArray(new VpnInfo[infoList.size()]);
3603 }
3604 }
3605
3606 /**
3607 * @return VPN information for accounting, or null if we can't retrieve all required
3608 * information, e.g primary underlying iface.
3609 */
3610 @Nullable
3611 private VpnInfo createVpnInfo(Vpn vpn) {
3612 VpnInfo info = vpn.getVpnInfo();
3613 if (info == null) {
3614 return null;
3615 }
3616 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3617 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3618 // the underlyingNetworks list.
3619 if (underlyingNetworks == null) {
3620 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3621 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3622 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3623 }
3624 } else if (underlyingNetworks.length > 0) {
3625 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3626 if (linkProperties != null) {
3627 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3628 }
3629 }
3630 return info.primaryUnderlyingIface == null ? null : info;
3631 }
3632
3633 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003634 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3635 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003636 * Permissions are checked in Vpn class.
3637 * @hide
3638 */
3639 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003640 public VpnConfig getVpnConfig(int userId) {
3641 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003642 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003643 Vpn vpn = mVpns.get(userId);
3644 if (vpn != null) {
3645 return vpn.getVpnConfig();
3646 } else {
3647 return null;
3648 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003649 }
3650 }
3651
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003652 @Override
3653 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003654 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3655 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3656 return false;
3657 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003658
3659 // Tear down existing lockdown if profile was removed
3660 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3661 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003662 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3663 final VpnProfile profile = VpnProfile.decode(
3664 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003665 if (profile == null) {
3666 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3667 setLockdownTracker(null);
3668 return true;
3669 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003670 int user = UserHandle.getUserId(Binder.getCallingUid());
3671 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003672 Vpn vpn = mVpns.get(user);
3673 if (vpn == null) {
3674 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3675 return false;
3676 }
3677 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003678 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003679 } else {
3680 setLockdownTracker(null);
3681 }
3682
3683 return true;
3684 }
3685
3686 /**
3687 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3688 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3689 */
3690 private void setLockdownTracker(LockdownVpnTracker tracker) {
3691 // Shutdown any existing tracker
3692 final LockdownVpnTracker existing = mLockdownTracker;
3693 mLockdownTracker = null;
3694 if (existing != null) {
3695 existing.shutdown();
3696 }
3697
3698 try {
3699 if (tracker != null) {
3700 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003701 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003702 mLockdownTracker = tracker;
3703 mLockdownTracker.init();
3704 } else {
3705 mNetd.setFirewallEnabled(false);
3706 }
3707 } catch (RemoteException e) {
3708 // ignored; NMS lives inside system_server
3709 }
3710 }
3711
3712 private void throwIfLockdownEnabled() {
3713 if (mLockdownEnabled) {
3714 throw new IllegalStateException("Unavailable in lockdown mode");
3715 }
3716 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003717
Robin Lee244ce8e2016-01-05 18:03:46 +00003718 /**
Robin Lee17e61832016-05-09 13:46:28 +01003719 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3720 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003721 *
Robin Lee17e61832016-05-09 13:46:28 +01003722 * @return {@code true} if the service was started, the service was already connected, or there
3723 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003724 */
Robin Lee17e61832016-05-09 13:46:28 +01003725 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003726 synchronized (mVpns) {
3727 Vpn vpn = mVpns.get(userId);
3728 if (vpn == null) {
3729 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3730 // exists already.
3731 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3732 return false;
3733 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003734
Robin Lee812800c2016-05-13 15:38:08 +01003735 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003736 }
3737 }
3738
3739 @Override
Robin Leedc679712016-05-03 13:23:03 +01003740 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003741 enforceConnectivityInternalPermission();
3742 enforceCrossUserPermission(userId);
3743
3744 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3745 if (LockdownVpnTracker.isEnabled()) {
3746 return false;
3747 }
3748
Robin Lee244ce8e2016-01-05 18:03:46 +00003749 synchronized (mVpns) {
3750 Vpn vpn = mVpns.get(userId);
3751 if (vpn == null) {
3752 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3753 return false;
3754 }
Robin Lee17e61832016-05-09 13:46:28 +01003755 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003756 return false;
3757 }
Robin Lee17e61832016-05-09 13:46:28 +01003758 if (!startAlwaysOnVpn(userId)) {
3759 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003760 return false;
3761 }
Robin Lee17e61832016-05-09 13:46:28 +01003762
Robin Lee812800c2016-05-13 15:38:08 +01003763 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003764 }
3765 return true;
3766 }
3767
3768 @Override
3769 public String getAlwaysOnVpnPackage(int userId) {
3770 enforceConnectivityInternalPermission();
3771 enforceCrossUserPermission(userId);
3772
3773 synchronized (mVpns) {
3774 Vpn vpn = mVpns.get(userId);
3775 if (vpn == null) {
3776 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3777 return null;
3778 }
3779 return vpn.getAlwaysOnPackage();
3780 }
3781 }
3782
Wink Savilleab9321d2013-06-29 21:10:57 -07003783 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003784 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003785 // TODO: Remove? Any reason to trigger a provisioning check?
3786 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003787 }
3788
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003789 /** Location to an updatable file listing carrier provisioning urls.
3790 * An example:
3791 *
3792 * <?xml version="1.0" encoding="utf-8"?>
3793 * <provisioningUrls>
3794 * <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 -07003795 * </provisioningUrls>
3796 */
3797 private static final String PROVISIONING_URL_PATH =
3798 "/data/misc/radio/provisioning_urls.xml";
3799 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003800
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003801 /** XML tag for root element. */
3802 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3803 /** XML tag for individual url */
3804 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003805 /** XML attribute for mcc */
3806 private static final String ATTR_MCC = "mcc";
3807 /** XML attribute for mnc */
3808 private static final String ATTR_MNC = "mnc";
3809
Paul Jensen434dde82015-06-11 09:43:30 -04003810 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003811 FileReader fileReader = null;
3812 XmlPullParser parser = null;
3813 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003814
3815 try {
3816 fileReader = new FileReader(mProvisioningUrlFile);
3817 parser = Xml.newPullParser();
3818 parser.setInput(fileReader);
3819 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3820
3821 while (true) {
3822 XmlUtils.nextElement(parser);
3823
3824 String element = parser.getName();
3825 if (element == null) break;
3826
Paul Jensen434dde82015-06-11 09:43:30 -04003827 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003828 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3829 try {
3830 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3831 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3832 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3833 parser.next();
3834 if (parser.getEventType() == XmlPullParser.TEXT) {
3835 return parser.getText();
3836 }
3837 }
3838 }
3839 } catch (NumberFormatException e) {
3840 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3841 }
3842 }
3843 }
3844 return null;
3845 } catch (FileNotFoundException e) {
3846 loge("Carrier Provisioning Urls file not found");
3847 } catch (XmlPullParserException e) {
3848 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3849 } catch (IOException e) {
3850 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3851 } finally {
3852 if (fileReader != null) {
3853 try {
3854 fileReader.close();
3855 } catch (IOException e) {}
3856 }
3857 }
3858 return null;
3859 }
3860
Wink Saville42d4f082013-07-20 20:31:59 -07003861 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003862 public String getMobileProvisioningUrl() {
3863 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003864 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003865 if (TextUtils.isEmpty(url)) {
3866 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003867 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003868 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003869 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003870 }
Wink Saville8cf35602013-07-10 23:00:07 -07003871 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003872 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003873 String phoneNumber = mTelephonyManager.getLine1Number();
3874 if (TextUtils.isEmpty(phoneNumber)) {
3875 phoneNumber = "0000000000";
3876 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003877 url = String.format(url,
3878 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3879 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003880 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003881 }
3882
Wink Savilleab9321d2013-06-29 21:10:57 -07003883 return url;
3884 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003885
Wink Saville948282b2013-08-29 08:55:16 -07003886 @Override
3887 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003888 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003889 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003890 final long ident = Binder.clearCallingIdentity();
3891 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003892 // Concatenate the range of types onto the range of NetIDs.
3893 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3894 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003895 } finally {
3896 Binder.restoreCallingIdentity(ident);
3897 }
Wink Saville948282b2013-08-29 08:55:16 -07003898 }
Wink Saville7788c612013-08-29 14:57:08 -07003899
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003900 @Override
3901 public void setAirplaneMode(boolean enable) {
3902 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003903 final long ident = Binder.clearCallingIdentity();
3904 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003905 final ContentResolver cr = mContext.getContentResolver();
3906 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3907 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3908 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003909 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003910 } finally {
3911 Binder.restoreCallingIdentity(ident);
3912 }
3913 }
3914
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003915 private void onUserStart(int userId) {
3916 synchronized(mVpns) {
3917 Vpn userVpn = mVpns.get(userId);
3918 if (userVpn != null) {
3919 loge("Starting user already has a VPN");
3920 return;
3921 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003922 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003923 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003924
3925 final ContentResolver cr = mContext.getContentResolver();
3926 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3927 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3928 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3929 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3930 if (alwaysOnPackage != null) {
3931 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3932 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003933 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003934 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3935 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003936 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003937 }
3938
3939 private void onUserStop(int userId) {
3940 synchronized(mVpns) {
3941 Vpn userVpn = mVpns.get(userId);
3942 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003943 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003944 return;
3945 }
Robin Lee17e61832016-05-09 13:46:28 +01003946 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003947 mVpns.delete(userId);
3948 }
3949 }
3950
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003951 private void onUserAdded(int userId) {
3952 synchronized(mVpns) {
3953 final int vpnsSize = mVpns.size();
3954 for (int i = 0; i < vpnsSize; i++) {
3955 Vpn vpn = mVpns.valueAt(i);
3956 vpn.onUserAdded(userId);
3957 }
3958 }
3959 }
3960
3961 private void onUserRemoved(int userId) {
3962 synchronized(mVpns) {
3963 final int vpnsSize = mVpns.size();
3964 for (int i = 0; i < vpnsSize; i++) {
3965 Vpn vpn = mVpns.valueAt(i);
3966 vpn.onUserRemoved(userId);
3967 }
3968 }
3969 }
3970
Robin Lee89e7a692016-02-29 14:38:17 +00003971 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003972 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3973 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3974 updateLockdownVpn();
3975 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003976 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003977 }
3978 }
3979
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003980 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3981 @Override
3982 public void onReceive(Context context, Intent intent) {
3983 final String action = intent.getAction();
3984 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3985 if (userId == UserHandle.USER_NULL) return;
3986
Robin Lee323f29d2016-05-04 16:38:06 +01003987 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003988 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003989 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003990 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003991 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3992 onUserAdded(userId);
3993 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3994 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003995 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3996 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003997 }
3998 }
3999 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004000
Robert Greenwalta67be032014-05-16 15:49:14 -07004001 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4002 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004003 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4004 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004005
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004006 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4007 // Map from UID to number of NetworkRequests that UID has filed.
4008 @GuardedBy("mUidToNetworkRequestCount")
4009 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4010
Robert Greenwalta67be032014-05-16 15:49:14 -07004011 private static class NetworkFactoryInfo {
4012 public final String name;
4013 public final Messenger messenger;
4014 public final AsyncChannel asyncChannel;
4015
4016 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4017 this.name = name;
4018 this.messenger = messenger;
4019 this.asyncChannel = asyncChannel;
4020 }
4021 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004022
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004023 private void ensureNetworkRequestHasType(NetworkRequest request) {
4024 if (request.type == NetworkRequest.Type.NONE) {
4025 throw new IllegalArgumentException(
4026 "All NetworkRequests in ConnectivityService must have a type");
4027 }
4028 }
4029
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004030 /**
4031 * Tracks info about the requester.
4032 * Also used to notice when the calling process dies so we can self-expire
4033 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004034 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004035 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004036 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004037 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004038 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004039 final int mPid;
4040 final int mUid;
4041 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004043 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004044 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004045 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004046 mPendingIntent = pi;
4047 messenger = null;
4048 mBinder = null;
4049 mPid = getCallingPid();
4050 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004051 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004052 }
4053
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004054 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004055 super();
4056 messenger = m;
4057 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004058 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004059 mBinder = binder;
4060 mPid = getCallingPid();
4061 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004062 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004063 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004064
4065 try {
4066 mBinder.linkToDeath(this, 0);
4067 } catch (RemoteException e) {
4068 binderDied();
4069 }
4070 }
4071
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004072 private void enforceRequestCountLimit() {
4073 synchronized (mUidToNetworkRequestCount) {
4074 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4075 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4076 throw new IllegalArgumentException("Too many NetworkRequests filed");
4077 }
4078 mUidToNetworkRequestCount.put(mUid, networkRequests);
4079 }
4080 }
4081
Robert Greenwalt9258c642014-03-26 16:47:06 -07004082 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004083 if (mBinder != null) {
4084 mBinder.unlinkToDeath(this, 0);
4085 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086 }
4087
4088 public void binderDied() {
4089 log("ConnectivityService NetworkRequestInfo binderDied(" +
4090 request + ", " + mBinder + ")");
4091 releaseNetworkRequest(request);
4092 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004093
4094 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004095 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004096 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004097 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004098 }
4099
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004100 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4101 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4102 if (badCapability != null) {
4103 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004104 }
4105 }
4106
Erik Kline9d598e12015-07-13 16:37:51 +09004107 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004108 final SortedSet<Integer> thresholds = new TreeSet();
4109 synchronized (nai) {
4110 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4111 if (nri.request.networkCapabilities.hasSignalStrength() &&
4112 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4113 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4114 }
4115 }
4116 }
Erik Kline9d598e12015-07-13 16:37:51 +09004117 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004118 }
4119
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004120 private void updateSignalStrengthThresholds(
4121 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4122 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004123 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004124 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4125
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004126 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004127 String detail;
4128 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4129 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4130 } else {
4131 detail = reason;
4132 }
4133 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4134 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4135 }
4136
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004137 nai.asyncChannel.sendMessage(
4138 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004139 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004140 }
4141
Robert Greenwalt9258c642014-03-26 16:47:06 -07004142 @Override
4143 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004144 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004145 final NetworkRequest.Type type = (networkCapabilities == null)
4146 ? NetworkRequest.Type.TRACK_DEFAULT
4147 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004148 // If the requested networkCapabilities is null, take them instead from
4149 // the default network request. This allows callers to keep track of
4150 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004151 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004152 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4153 enforceAccessPermission();
4154 } else {
4155 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4156 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004157 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4158 // of the app when the request is filed, but we never change the request if the app
4159 // changes network state. http://b/29964605
4160 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004161 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004162 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004163
Robert Greenwalt6078b502014-06-11 16:05:07 -07004164 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004165 throw new IllegalArgumentException("Bad timeout specified");
4166 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004167
Etan Cohenddb9ef02015-11-18 10:56:15 -08004168 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4169 .equals(networkCapabilities.getNetworkSpecifier())) {
4170 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4171 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4172 }
4173
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004174 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004175 nextNetworkRequestId(), type);
4176 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004177 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004178
4179 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004180 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004181 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004182 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004183 }
4184 return networkRequest;
4185 }
4186
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004187 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004188 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004189 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004190 } else {
4191 enforceChangePermission();
4192 }
4193 }
4194
fenglub15e72b2015-03-20 11:29:56 -07004195 @Override
fengludb571472015-04-21 17:12:05 -07004196 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004197 enforceAccessPermission();
4198 NetworkAgentInfo nai = null;
4199 if (network == null) {
4200 return false;
4201 }
4202 synchronized (mNetworkForNetId) {
4203 nai = mNetworkForNetId.get(network.netId);
4204 }
4205 if (nai != null) {
4206 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4207 return true;
4208 }
4209 return false;
4210 }
4211
Felipe Lemeee27cab2016-06-20 16:36:29 -07004212 private boolean isSystem(int uid) {
4213 return uid < Process.FIRST_APPLICATION_UID;
4214 }
fenglub15e72b2015-03-20 11:29:56 -07004215
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004216 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004217 final int uid = Binder.getCallingUid();
4218 if (isSystem(uid)) {
4219 return;
4220 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004221 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004222 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004223 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004224 synchronized(mRulesLock) {
4225 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4226 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004227 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4228 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004229 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004230 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004231 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004232 }
4233 }
4234 }
4235
Robert Greenwalt9258c642014-03-26 16:47:06 -07004236 @Override
4237 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4238 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004239 checkNotNull(operation, "PendingIntent cannot be null.");
4240 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4241 enforceNetworkRequestPermissions(networkCapabilities);
4242 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004243 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004244
4245 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004246 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4247 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004248 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004249 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4250 nri));
4251 return networkRequest;
4252 }
4253
Jeremy Joslin79294842014-12-03 17:15:28 -08004254 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4255 mHandler.sendMessageDelayed(
4256 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4257 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4258 }
4259
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004260 @Override
4261 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004262 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004263 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4264 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004265 }
4266
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004267 // In order to implement the compatibility measure for pre-M apps that call
4268 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4269 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4270 // This ensures it has permission to do so.
4271 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4272 if (nc == null) {
4273 return false;
4274 }
4275 int[] transportTypes = nc.getTransportTypes();
4276 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4277 return false;
4278 }
4279 try {
4280 mContext.enforceCallingOrSelfPermission(
4281 android.Manifest.permission.ACCESS_WIFI_STATE,
4282 "ConnectivityService");
4283 } catch (SecurityException e) {
4284 return false;
4285 }
4286 return true;
4287 }
4288
Robert Greenwalt9258c642014-03-26 16:47:06 -07004289 @Override
4290 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4291 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004292 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4293 enforceAccessPermission();
4294 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004295
Erik Kline7523eb32015-07-09 18:24:03 +09004296 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004297 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4298 NetworkRequest.Type.LISTEN);
4299 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004300 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004301
4302 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4303 return networkRequest;
4304 }
4305
4306 @Override
4307 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4308 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004309 checkNotNull(operation, "PendingIntent cannot be null.");
4310 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4311 enforceAccessPermission();
4312 }
4313
Erik Kline7523eb32015-07-09 18:24:03 +09004314 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004315 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4316 NetworkRequest.Type.LISTEN);
4317 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004318 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004319
4320 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004321 }
4322
4323 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004324 public void requestLinkProperties(NetworkRequest networkRequest) {
4325 ensureNetworkRequestHasType(networkRequest);
4326 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4327 mHandler.sendMessage(mHandler.obtainMessage(
4328 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4329 }
4330
4331 @Override
4332 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4333 ensureNetworkRequestHasType(networkRequest);
4334 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4335 mHandler.sendMessage(mHandler.obtainMessage(
4336 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4337 }
4338
4339 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004340 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004341 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004342 mHandler.sendMessage(mHandler.obtainMessage(
4343 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004344 }
4345
4346 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004347 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004348 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004349 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4350 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004351 }
4352
Robert Greenwalta67be032014-05-16 15:49:14 -07004353 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004354 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004355 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4356 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4357 }
4358
4359 @Override
4360 public void unregisterNetworkFactory(Messenger messenger) {
4361 enforceConnectivityInternalPermission();
4362 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4363 }
4364
4365 private void handleUnregisterNetworkFactory(Messenger messenger) {
4366 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4367 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004368 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004369 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004370 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004371 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004372 }
4373
Robert Greenwalt7b816022014-04-18 15:25:25 -07004374 /**
4375 * NetworkAgentInfo supporting a request by requestId.
4376 * These have already been vetted (their Capabilities satisfy the request)
4377 * and the are the highest scored network available.
4378 * the are keyed off the Requests requestId.
4379 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004380 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004381 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4382 new SparseArray<NetworkAgentInfo>();
4383
Paul Jensen31a94f42015-02-13 14:18:39 -05004384 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4385 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004386 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4387 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004388 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4389 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4390 // there may not be a strict 1:1 correlation between the two.
4391 @GuardedBy("mNetworkForNetId")
4392 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004393
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394 // NetworkAgentInfo keyed off its connecting messenger
4395 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004396 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004397 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4398 new HashMap<Messenger, NetworkAgentInfo>();
4399
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004400 @GuardedBy("mBlockedAppUids")
4401 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4402
Paul Jensen2c311d62014-11-17 12:34:51 -05004403 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004404 private final NetworkRequest mDefaultRequest;
4405
Erik Klineda4bfa82015-04-30 12:58:40 +09004406 // Request used to optionally keep mobile data active even when higher
4407 // priority networks like Wi-Fi are active.
4408 private final NetworkRequest mDefaultMobileDataRequest;
4409
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004410 private NetworkAgentInfo getDefaultNetwork() {
4411 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4412 }
4413
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004414 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004415 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004416 }
4417
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004418 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4419 return nri.request.requestId == mDefaultRequest.requestId;
4420 }
4421
Paul Jensen31a94f42015-02-13 14:18:39 -05004422 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004423 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004424 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004425 enforceConnectivityInternalPermission();
4426
Paul Jensen2c311d62014-11-17 12:34:51 -05004427 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4428 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004429 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004430 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4431 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004432 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004433 synchronized (this) {
4434 nai.networkMonitor.systemReady = mSystemReady;
4435 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004436 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4437 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004438 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004439 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004440 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004441 }
4442
4443 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4444 if (VDBG) log("Got NetworkAgent Messenger");
4445 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004446 synchronized (mNetworkForNetId) {
4447 mNetworkForNetId.put(na.network.netId, na);
4448 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004449 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4450 NetworkInfo networkInfo = na.networkInfo;
4451 na.networkInfo = null;
4452 updateNetworkInfo(na, networkInfo);
4453 }
4454
4455 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4456 LinkProperties newLp = networkAgent.linkProperties;
4457 int netId = networkAgent.network.netId;
4458
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004459 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4460 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004461 if (networkAgent.clatd != null) {
4462 networkAgent.clatd.fixupLinkProperties(oldLp);
4463 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004464
Paul Jensen992f2522014-04-28 10:33:11 -04004465 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004466 updateMtu(newLp, oldLp);
4467 // TODO - figure out what to do for clat
4468// for (LinkProperties lp : newLp.getStackedLinks()) {
4469// updateMtu(lp, null);
4470// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004471 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004472
Erik Kline94887872016-04-05 13:30:49 +09004473 updateRoutes(newLp, oldLp, netId);
4474 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004475
Paul Jensen3b759822014-05-13 11:44:01 -04004476 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004477 if (isDefaultNetwork(networkAgent)) {
4478 handleApplyDefaultProxy(newLp.getHttpProxy());
4479 } else {
4480 updateProxy(newLp, oldLp, networkAgent);
4481 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004482 // TODO - move this check to cover the whole function
4483 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004484 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004485 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4486 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004487
4488 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004489 }
4490
Lorenzo Colitti95439462014-10-09 13:44:48 +09004491 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4492 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4493 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004494
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004495 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004496 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4497 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004498 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004499 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004500 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004501 }
Paul Jensen992f2522014-04-28 10:33:11 -04004502
4503 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4504 CompareResult<String> interfaceDiff = new CompareResult<String>();
4505 if (oldLp != null) {
4506 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4507 } else if (newLp != null) {
4508 interfaceDiff.added = newLp.getAllInterfaceNames();
4509 }
4510 for (String iface : interfaceDiff.added) {
4511 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004512 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004513 mNetd.addInterfaceToNetwork(iface, netId);
4514 } catch (Exception e) {
4515 loge("Exception adding interface: " + e);
4516 }
4517 }
4518 for (String iface : interfaceDiff.removed) {
4519 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004520 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004521 mNetd.removeInterfaceFromNetwork(iface, netId);
4522 } catch (Exception e) {
4523 loge("Exception removing interface: " + e);
4524 }
4525 }
4526 }
4527
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004528 /**
4529 * Have netd update routes from oldLp to newLp.
4530 * @return true if routes changed between oldLp and newLp
4531 */
4532 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4534 if (oldLp != null) {
4535 routeDiff = oldLp.compareAllRoutes(newLp);
4536 } else if (newLp != null) {
4537 routeDiff.added = newLp.getAllRoutes();
4538 }
4539
4540 // add routes before removing old in case it helps with continuous connectivity
4541
4542 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4543 for (RouteInfo route : routeDiff.added) {
4544 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004545 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004546 try {
4547 mNetd.addRoute(netId, route);
4548 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004549 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4550 loge("Exception in addRoute for non-gateway: " + e);
4551 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004552 }
4553 }
4554 for (RouteInfo route : routeDiff.added) {
4555 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004556 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004557 try {
4558 mNetd.addRoute(netId, route);
4559 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004560 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4561 loge("Exception in addRoute for gateway: " + e);
4562 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004563 }
4564 }
4565
4566 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004567 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004568 try {
4569 mNetd.removeRoute(netId, route);
4570 } catch (Exception e) {
4571 loge("Exception in removeRoute: " + e);
4572 }
4573 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004574 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004575 }
Erik Kline41368502015-06-17 13:19:54 +09004576
Erik Kline94887872016-04-05 13:30:49 +09004577 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4578 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4579 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004580 }
Erik Kline94887872016-04-05 13:30:49 +09004581
4582 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004583 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004584 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004585 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004586 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4587 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004588 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004589 }
4590 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4591 if (defaultNai != null && defaultNai.network.netId == netId) {
4592 setDefaultDnsSystemProperties(dnses);
4593 }
4594 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004595 }
4596
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004597 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4598 int last = 0;
4599 for (InetAddress dns : dnses) {
4600 ++last;
4601 String key = "net.dns" + last;
4602 String value = dns.getHostAddress();
4603 SystemProperties.set(key, value);
4604 }
4605 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4606 String key = "net.dns" + i;
4607 SystemProperties.set(key, "");
4608 }
4609 mNumDnsEntries = last;
4610 }
4611
Paul Jensen3d194ea2015-06-16 14:27:36 -04004612 /**
4613 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4614 * augmented with any stateful capabilities implied from {@code networkAgent}
4615 * (e.g., validated status and captive portal status).
4616 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004617 * @param oldScore score of the network before any of the changes that prompted us
4618 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004619 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004620 * @param networkCapabilities the new network capabilities.
4621 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004622 private void updateCapabilities(
4623 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004624 // Don't modify caller's NetworkCapabilities.
4625 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004626 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004627 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4628 } else {
4629 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4630 }
Paul Jensene0988542015-06-25 15:30:08 -04004631 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004632 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4633 } else {
4634 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4635 }
Paul Jensene0988542015-06-25 15:30:08 -04004636 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
Paul Jensen487ffe72015-07-24 15:57:11 -04004637 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4638 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4639 try {
4640 mNetd.setNetworkPermission(nai.network.netId,
4641 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4642 null : NetworkManagementService.PERMISSION_SYSTEM);
4643 } catch (RemoteException e) {
4644 loge("Exception in setNetworkPermission: " + e);
4645 }
4646 }
Paul Jensene0988542015-06-25 15:30:08 -04004647 synchronized (nai) {
4648 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004649 }
Paul Jensene0988542015-06-25 15:30:08 -04004650 rematchAllNetworksAndRequests(nai, oldScore);
4651 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004652 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004653 }
4654
Paul Jensenc8b9a742014-09-30 15:37:41 -04004655 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004656 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4657 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004658 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004659 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004660 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4661 }
4662 }
4663
Robert Greenwalt7b816022014-04-18 15:25:25 -07004664 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4665 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004666 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004667 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4668 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004669 }
4670 }
4671
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004672 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4673 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004674 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004675 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004676 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4677 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004678 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004679 sendIntent(nri.mPendingIntent, intent);
4680 }
4681 // else not handled
4682 }
4683
4684 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4685 mPendingIntentWakeLock.acquire();
4686 try {
4687 if (DBG) log("Sending " + pendingIntent);
4688 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4689 } catch (PendingIntent.CanceledException e) {
4690 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4691 mPendingIntentWakeLock.release();
4692 releasePendingNetworkRequest(pendingIntent);
4693 }
4694 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4695 }
4696
4697 @Override
4698 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4699 String resultData, Bundle resultExtras) {
4700 if (DBG) log("Finished sending " + pendingIntent);
4701 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004702 // Release with a delay so the receiving client has an opportunity to put in its
4703 // own request.
4704 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004705 }
4706
Robert Greenwalt9258c642014-03-26 16:47:06 -07004707 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004708 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004709 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004710 Bundle bundle = new Bundle();
4711 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4712 new NetworkRequest(nri.request));
4713 Message msg = Message.obtain();
4714 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4715 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4716 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4717 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004718 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004719 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004720 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004721 break;
4722 }
4723 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4724 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4725 new NetworkCapabilities(networkAgent.networkCapabilities));
4726 break;
4727 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004728 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004729 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4730 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004731 break;
4732 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004733 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004734 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004735 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004736 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004737 if (VDBG) {
4738 log("sending notification " + notifyTypeToName(notificationType) +
4739 " for " + nri.request);
4740 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004741 nri.messenger.send(msg);
4742 } catch (RemoteException e) {
4743 // may occur naturally in the race of binder death.
4744 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4745 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004746 }
4747
Paul Jensenc8b9a742014-09-30 15:37:41 -04004748 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004749 if (nai.numRequestNetworkRequests() != 0) {
4750 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4751 NetworkRequest nr = nai.requestAt(i);
4752 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004753 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004754 loge("Dead network still had at least " + nr);
4755 break;
4756 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004757 }
4758 nai.asyncChannel.disconnect();
4759 }
4760
Robert Greenwalt7b816022014-04-18 15:25:25 -07004761 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4762 if (oldNetwork == null) {
4763 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4764 return;
4765 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004766 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004767
4768 // If we get here it means that the last linger timeout for this network expired. So there
4769 // must be no other active linger timers, and we must stop lingering.
4770 oldNetwork.clearLingerState();
4771
4772 if (unneeded(oldNetwork)) {
4773 teardownUnneededNetwork(oldNetwork);
4774 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004775 }
4776
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004777 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004778 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004779 setupDataActivityTracking(newNetwork);
4780 try {
4781 mNetd.setDefaultNetId(newNetwork.network.netId);
4782 } catch (Exception e) {
4783 loge("Exception setting default network :" + e);
4784 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004785 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004786 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004787 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004788 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004789 }
4790
Paul Jensen2161a8e2014-09-11 11:00:39 -04004791 // Handles a network appearing or improving its score.
4792 //
4793 // - Evaluates all current NetworkRequests that can be
4794 // satisfied by newNetwork, and reassigns to newNetwork
4795 // any such requests for which newNetwork is the best.
4796 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004797 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004798 // needed. A network is needed if it is the best network for
4799 // one or more NetworkRequests, or if it is a VPN.
4800 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004801 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004802 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004803 //
4804 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4805 // networks that have no chance (i.e. even if validated)
4806 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004807 //
4808 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4809 // it does not remove NetworkRequests that other Networks could better satisfy.
4810 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4811 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4812 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004813 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004814 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004815 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4816 // performed to tear down unvalidated networks that have no chance (i.e. even if
4817 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004818 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004819 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004820 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004821 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004822 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004823 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004824 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004825 // Find and migrate to this Network any NetworkRequests for
4826 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004827 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004828 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004829 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004830 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004831 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4832 final boolean satisfies = newNetwork.satisfies(nri.request);
4833 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004834 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004835 log("Network " + newNetwork.name() + " was already satisfying" +
4836 " request " + nri.request.requestId + ". No change.");
4837 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004838 keep = true;
4839 continue;
4840 }
4841
4842 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004843 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004844 if (satisfies) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004845 if (nri.request.isListen()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004846 // This is not a request, it's a callback listener.
4847 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004848 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004849 continue;
4850 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004851
Robert Greenwalt7b816022014-04-18 15:25:25 -07004852 // next check if it's better than any current network we're using for
4853 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004854 if (VDBG) {
4855 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004856 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4857 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004858 }
4859 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004860 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004861 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004862 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004863 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004864 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004865 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004866 affectedNetworks.add(currentNetwork);
4867 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004868 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004869 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004870 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004871 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004872 if (!newNetwork.addRequest(nri.request)) {
4873 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4874 }
4875 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004876 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004877 // Tell NetworkFactories about the new score, so they can stop
4878 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004879 // TODO - this could get expensive if we have alot of requests for this
4880 // network. Think about if there is a way to reduce this. Push
4881 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004882 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004883 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004884 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004885 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004886 if (currentNetwork != null) {
4887 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4888 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004889 }
4890 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004891 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004892 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4893 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004894 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004895 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4896 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4897 // This means this code doesn't have to handle the case where "currentNetwork" no
4898 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4899 if (DBG) {
4900 log("Network " + newNetwork.name() + " stopped satisfying" +
4901 " request " + nri.request.requestId);
4902 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004903 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004904 if (currentNetwork == newNetwork) {
4905 mNetworkForRequestId.remove(nri.request.requestId);
4906 sendUpdatedScoreToFactories(nri.request, 0);
4907 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004908 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004909 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4910 newNetwork.name() +
4911 " without updating mNetworkForRequestId or factories!");
4912 }
4913 }
4914 // TODO: technically, sending CALLBACK_LOST here is
4915 // incorrect if nri is a request (not a listen) and there
4916 // is a replacement network currently connected that can
4917 // satisfy it. However, the only capability that can both
4918 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4919 // so this code is only incorrect for a network that loses
4920 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004921 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004922 }
4923 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004924 if (isNewDefault) {
4925 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004926 makeDefault(newNetwork);
4927 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4928 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004929 synchronized (ConnectivityService.this) {
4930 // have a new default network, release the transition wakelock in
4931 // a second if it's held. The second pause is to allow apps
4932 // to reconnect over the new network
4933 if (mNetTransitionWakeLock.isHeld()) {
4934 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4935 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4936 mNetTransitionWakeLockSerialNumber, 0),
4937 1000);
4938 }
4939 }
4940 }
4941
4942 // do this after the default net is switched, but
4943 // before LegacyTypeTracker sends legacy broadcasts
4944 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4945
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004946 // Linger any networks that are no longer needed. This should be done after sending the
4947 // available callback for newNetwork.
4948 for (NetworkAgentInfo nai : affectedNetworks) {
4949 updateLingerState(nai, now);
4950 }
4951 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4952 // does not need to be done in any particular order.
4953 updateLingerState(newNetwork, now);
4954
Paul Jensencf4c2c62015-07-01 14:16:32 -04004955 if (isNewDefault) {
4956 // Maintain the illusion: since the legacy API only
4957 // understands one network at a time, we must pretend
4958 // that the current default network disconnected before
4959 // the new one connected.
4960 if (oldDefaultNetwork != null) {
4961 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4962 oldDefaultNetwork, true);
4963 }
4964 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4965 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4966 notifyLockdownVpn(newNetwork);
4967 }
4968
Robert Greenwalt7b816022014-04-18 15:25:25 -07004969 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004970 // Notify battery stats service about this network, both the normal
4971 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004972 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004973 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004974 final IBatteryStats bs = BatteryStatsService.getService();
4975 final int type = newNetwork.networkInfo.getType();
4976
4977 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4978 bs.noteNetworkInterfaceType(baseIface, type);
4979 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4980 final String stackedIface = stacked.getInterfaceName();
4981 bs.noteNetworkInterfaceType(stackedIface, type);
4982 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4983 }
4984 } catch (RemoteException ignored) {
4985 }
4986
Robert Greenwalt152ed372014-12-17 17:19:53 -08004987 // This has to happen after the notifyNetworkCallbacks as that tickles each
4988 // ConnectivityManager instance so that legacy requests correctly bind dns
4989 // requests to this network. The legacy users are listening for this bcast
4990 // and will generally do a dns request so they can ensureRouteToHost and if
4991 // they do that before the callbacks happen they'll use the default network.
4992 //
4993 // TODO: Is there still a race here? We send the broadcast
4994 // after sending the callback, but if the app can receive the
4995 // broadcast before the callback, it might still break.
4996 //
4997 // This *does* introduce a race where if the user uses the new api
4998 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4999 // they may get old info. Reverse this after the old startUsing api is removed.
5000 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005001 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5002 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005003 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005004 // legacy type tracker filters out repeat adds
5005 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5006 }
5007 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005008
5009 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5010 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5011 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5012 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5013 if (newNetwork.isVPN()) {
5014 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5015 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005016 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005017 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5018 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005019 if (unneeded(nai)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005020 if (nai.getLingerExpiry() > 0) {
5021 // This network has active linger timers and no requests, but is not
5022 // lingering. Linger it.
5023 //
5024 // One way (the only way?) this can happen if this network is unvalidated
5025 // and became unneeded due to another network improving its score to the
5026 // point where this network will no longer be able to satisfy any requests
5027 // even if it validates.
5028 updateLingerState(nai, now);
5029 } else {
5030 if (DBG) log("Reaping " + nai.name());
5031 teardownUnneededNetwork(nai);
5032 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005033 }
5034 }
5035 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005036 }
5037
Paul Jensen1c7ba022015-06-16 14:27:36 -04005038 /**
5039 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5040 * being disconnected.
5041 * @param changed If only one Network's score or capabilities have been modified since the last
5042 * time this function was called, pass this Network in this argument, otherwise pass
5043 * null.
5044 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5045 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5046 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5047 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5048 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005049 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005050 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005051 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5052 // to avoid the slowness. It is not simply enough to process just "changed", for
5053 // example in the case where "changed"'s score decreases and another network should begin
5054 // satifying a NetworkRequest that "changed" currently satisfies.
5055
5056 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5057 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5058 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005059 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005060 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005061 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005062 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005063 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5064 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5065 // Rematch higher scoring networks first to prevent requests first matching a lower
5066 // scoring network and then a higher scoring network, which could produce multiple
5067 // callbacks and inadvertently unlinger networks.
5068 Arrays.sort(nais);
5069 for (NetworkAgentInfo nai : nais) {
5070 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005071 // Only reap the last time through the loop. Reaping before all rematching
5072 // is complete could incorrectly teardown a network that hasn't yet been
5073 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005074 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005075 : ReapUnvalidatedNetworks.REAP,
5076 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005077 }
5078 }
5079 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005080
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005081 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005082 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005083 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005084 // For now only update icons for default connection.
5085 // TODO: Update WiFi and cellular icons separately. b/17237507
5086 if (!isDefaultNetwork(nai)) return;
5087
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005088 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005089 // Don't repeat publish.
5090 if (newInetCondition == mDefaultInetConditionPublished) return;
5091
5092 mDefaultInetConditionPublished = newInetCondition;
5093 sendInetConditionBroadcast(nai.networkInfo);
5094 }
5095
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005096 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5097 if (mLockdownTracker != null) {
5098 if (nai != null && nai.isVPN()) {
5099 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5100 } else {
5101 mLockdownTracker.onNetworkInfoChanged();
5102 }
5103 }
5104 }
5105
Robert Greenwalt7b816022014-04-18 15:25:25 -07005106 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5107 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005108 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005109 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005110 synchronized (networkAgent) {
5111 oldInfo = networkAgent.networkInfo;
5112 networkAgent.networkInfo = newInfo;
5113 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005114 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115
5116 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005117 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5118 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5119 notifyIfacesChangedForNetworkStats();
5120 } else if (VDBG) log("ignoring duplicate network state non-change");
5121 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005122 return;
5123 }
5124 if (DBG) {
5125 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5126 (oldInfo == null ? "null" : oldInfo.getState()) +
5127 " to " + state);
5128 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005129
Robin Lee585e2482016-05-01 23:00:00 +01005130 if (!networkAgent.created
5131 && (state == NetworkInfo.State.CONNECTED
5132 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005133 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005134 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005135 if (networkAgent.isVPN()) {
5136 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005137 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5138 (networkAgent.networkMisc == null ||
5139 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005140 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005141 mNetd.createPhysicalNetwork(networkAgent.network.netId,
5142 networkAgent.networkCapabilities.hasCapability(
5143 NET_CAPABILITY_NOT_RESTRICTED) ?
5144 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005145 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005146 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005147 loge("Error creating network " + networkAgent.network.netId + ": "
5148 + e.getMessage());
5149 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005150 }
Paul Jenseneec75412014-08-04 12:21:19 -04005151 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005152 }
5153
5154 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5155 networkAgent.everConnected = true;
5156
Robert Greenwalt7b816022014-04-18 15:25:25 -07005157 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005158 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005159
Paul Jensenca8f16a2014-05-09 12:47:55 -04005160 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005161 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005162
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005163 if (networkAgent.isVPN()) {
5164 // Temporarily disable the default proxy (not global).
5165 synchronized (mProxyLock) {
5166 if (!mDefaultProxyDisabled) {
5167 mDefaultProxyDisabled = true;
5168 if (mGlobalProxy == null && mDefaultProxy != null) {
5169 sendProxyBroadcast(null);
5170 }
5171 }
5172 }
5173 // TODO: support proxy per network.
5174 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005175
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005176 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5177 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5178 // capabilities, so it only needs to be done once on initial connect, not every time the
5179 // network's capabilities change. Note that we do this before rematching the network,
5180 // so we could decide to tear it down immediately afterwards. That's fine though - on
5181 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5182 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005183 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005184
Paul Jensen2161a8e2014-09-11 11:00:39 -04005185 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005186 final long now = SystemClock.elapsedRealtime();
5187 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005188
5189 // This has to happen after matching the requests, because callbacks are just requests.
5190 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005191 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005192 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005193 if (networkAgent.isVPN()) {
5194 synchronized (mProxyLock) {
5195 if (mDefaultProxyDisabled) {
5196 mDefaultProxyDisabled = false;
5197 if (mGlobalProxy == null && mDefaultProxy != null) {
5198 sendProxyBroadcast(mDefaultProxy);
5199 }
5200 }
5201 }
5202 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005203 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5204 state == NetworkInfo.State.SUSPENDED) {
5205 // going into or coming out of SUSPEND: rescore and notify
5206 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005207 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005208 }
5209 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5210 ConnectivityManager.CALLBACK_SUSPENDED :
5211 ConnectivityManager.CALLBACK_RESUMED));
5212 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005213 }
5214 }
5215
Robert Greenwaltac96c522014-06-03 16:43:57 -07005216 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005217 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005218 if (score < 0) {
5219 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5220 "). Bumping score to min of 0");
5221 score = 0;
5222 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005223
Paul Jensen2161a8e2014-09-11 11:00:39 -04005224 final int oldScore = nai.getCurrentScore();
5225 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005226
Paul Jensen85cf78e2015-06-25 13:25:07 -04005227 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005228
Paul Jensenc8b9a742014-09-30 15:37:41 -04005229 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005230 }
5231
Robert Greenwalt9258c642014-03-26 16:47:06 -07005232 // notify only this one new request of the current state
5233 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5234 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005235 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005236 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005237 } else {
5238 sendPendingIntentForRequest(nri, nai, notifyType);
5239 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005240 }
5241
Robert Greenwalt8d482522015-06-24 13:23:42 -07005242 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005243 // The NetworkInfo we actually send out has no bearing on the real
5244 // state of affairs. For example, if the default connection is mobile,
5245 // and a request for HIPRI has just gone away, we need to pretend that
5246 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5247 // the state to DISCONNECTED, even though the network is of type MOBILE
5248 // and is still connected.
5249 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5250 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005251 if (state != DetailedState.DISCONNECTED) {
5252 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005253 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005254 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005255 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005256 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5257 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5258 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5259 if (info.isFailover()) {
5260 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5261 nai.networkInfo.setFailover(false);
5262 }
5263 if (info.getReason() != null) {
5264 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5265 }
5266 if (info.getExtraInfo() != null) {
5267 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5268 }
5269 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005270 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005271 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005272 if (newDefaultAgent != null) {
5273 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5274 newDefaultAgent.networkInfo);
5275 } else {
5276 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5277 }
5278 }
5279 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5280 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005281 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005282 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005283 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005284 }
5285 }
5286 }
5287
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005288 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005289 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005290 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5291 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005292 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5293 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005294 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005295 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005296 } else {
5297 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5298 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005299 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005300 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005301
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005302 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5303 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5304 }
5305
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005306 private String notifyTypeToName(int notifyType) {
5307 switch (notifyType) {
5308 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5309 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5310 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5311 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5312 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5313 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5314 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5315 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5316 }
5317 return "UNKNOWN";
5318 }
5319
Jeff Sharkey69736342014-12-08 14:50:12 -08005320 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005321 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5322 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005323 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005324 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005325 try {
5326 mStatsService.forceUpdateIfaces();
5327 } catch (Exception ignored) {
5328 }
5329 }
5330
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005331 @Override
5332 public boolean addVpnAddress(String address, int prefixLength) {
5333 throwIfLockdownEnabled();
5334 int user = UserHandle.getUserId(Binder.getCallingUid());
5335 synchronized (mVpns) {
5336 return mVpns.get(user).addAddress(address, prefixLength);
5337 }
5338 }
5339
5340 @Override
5341 public boolean removeVpnAddress(String address, int prefixLength) {
5342 throwIfLockdownEnabled();
5343 int user = UserHandle.getUserId(Binder.getCallingUid());
5344 synchronized (mVpns) {
5345 return mVpns.get(user).removeAddress(address, prefixLength);
5346 }
5347 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005348
5349 @Override
5350 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5351 throwIfLockdownEnabled();
5352 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005353 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005354 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005355 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005356 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005357 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005358 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005359 }
5360 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005361 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005362
5363 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005364 public String getCaptivePortalServerUrl() {
5365 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5366 }
5367
5368 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005369 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5370 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5371 enforceKeepalivePermission();
5372 mKeepaliveTracker.startNattKeepalive(
5373 getNetworkAgentInfoForNetwork(network),
5374 intervalSeconds, messenger, binder,
5375 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5376 }
5377
5378 @Override
5379 public void stopKeepalive(Network network, int slot) {
5380 mHandler.sendMessage(mHandler.obtainMessage(
5381 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5382 }
5383
5384 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005385 public void factoryReset() {
5386 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005387
5388 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5389 return;
5390 }
5391
Robin Lee3b3dd942015-05-12 18:14:58 +01005392 final int userId = UserHandle.getCallingUserId();
5393
Stuart Scottf1fb3972015-04-02 18:00:02 -07005394 // Turn airplane mode off
5395 setAirplaneMode(false);
5396
Stuart Scotte3e314d2015-04-20 14:07:45 -07005397 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5398 // Untether
5399 for (String tether : getTetheredIfaces()) {
5400 untether(tether);
5401 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005402 }
5403
Stuart Scotte3e314d2015-04-20 14:07:45 -07005404 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005405 // Remove always-on package
5406 synchronized (mVpns) {
5407 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5408 if (alwaysOnPackage != null) {
5409 setAlwaysOnVpnPackage(userId, null, false);
5410 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5411 }
5412 }
5413
Stuart Scotte3e314d2015-04-20 14:07:45 -07005414 // Turn VPN off
5415 VpnConfig vpnConfig = getVpnConfig(userId);
5416 if (vpnConfig != null) {
5417 if (vpnConfig.legacy) {
5418 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5419 } else {
5420 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5421 // in the future without user intervention.
5422 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005423
Victor Changb04a5ea2016-05-30 20:36:30 +01005424 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005425 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005426 }
5427 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005428
5429 Settings.Global.putString(mContext.getContentResolver(),
5430 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005431 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005432
5433 @VisibleForTesting
5434 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5435 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5436 return new NetworkMonitor(context, handler, nai, defaultRequest);
5437 }
Erik Kline48f12f22016-04-14 17:30:59 +09005438
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005439 @VisibleForTesting
5440 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5441 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5442 }
5443
Hugo Benichicfddd682016-05-31 16:28:06 +09005444 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005445 int newNetid = NETID_UNSET;
5446 int prevNetid = NETID_UNSET;
5447 int[] transports = new int[0];
5448 boolean hadIPv4 = false;
5449 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005450
Hugo Benichi5f16f762016-04-20 12:09:33 +09005451 if (newNai != null) {
5452 newNetid = newNai.network.netId;
5453 transports = newNai.networkCapabilities.getTransportTypes();
5454 }
5455 if (prevNai != null) {
5456 prevNetid = prevNai.network.netId;
5457 final LinkProperties lp = prevNai.linkProperties;
5458 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5459 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5460 }
5461
Hugo Benichicfddd682016-05-31 16:28:06 +09005462 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5463 }
5464
5465 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5466 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005468}