blob: 989892f1296e9c17fa76779c5551ffddb7eb6003 [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;
Erik Kline065ab6e2016-10-02 18:02:14 +090080import android.net.util.AvoidBadWifiTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080082import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070083import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040084import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070086import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070088import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.Looper;
90import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070091import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070092import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070093import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070094import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070095import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080096import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090097import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070099import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400100import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800101import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700102import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700103import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700104import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700105import android.text.TextUtils;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600106import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700107import android.util.LocalLog;
108import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600109import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700110import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800111import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700112import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500113import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700114import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700115import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800116
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400119import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700120import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700121import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700123import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800124import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700125import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700126import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700127import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900128import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900129import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700130import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700131import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400132import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900133import com.android.server.connectivity.KeepaliveTracker;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900134import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900135import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700136import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600137import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400138import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900139import com.android.server.connectivity.NetworkNotificationManager;
140import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400141import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700142import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800143import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700144import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700145import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700146import com.android.server.net.LockdownVpnTracker;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600147
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700148import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700149
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700150import org.xmlpull.v1.XmlPullParser;
151import org.xmlpull.v1.XmlPullParserException;
152
153import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700155import java.io.FileNotFoundException;
156import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700157import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700159import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700160import java.net.InetAddress;
161import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700162import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700163import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700165import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700166import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700167import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700168import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700169import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700170import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600171import java.util.SortedSet;
172import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
174/**
175 * @hide
176 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800177public class ConnectivityService extends IConnectivityManager.Stub
178 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900179 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900181 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700182 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
Jake Hamby786e71a2014-02-06 14:43:50 -0800184 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900185 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700186
Jeff Sharkey899223b2012-08-04 15:24:58 -0700187 // TODO: create better separation between radio types and network types
188
Robert Greenwalt42acef32009-08-12 16:08:25 -0700189 // how long to wait before switching back to a radio's default network
190 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
191 // system property that can override the above value
192 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
193 "android.telephony.apn-restore";
194
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900195 // How long to wait before putting up a "This network doesn't have an Internet connection,
196 // connect anyway?" dialog after the user selects a network that doesn't validate.
197 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
198
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900199 // Default to 30s linger time-out. Modifiable only for testing.
200 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
201 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
202 @VisibleForTesting
203 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
204
Jeremy Joslin79294842014-12-03 17:15:28 -0800205 // How long to delay to removal of a pending intent based request.
206 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
207 private final int mReleasePendingIntentDelayMs;
208
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800209 private Tethering mTethering;
210
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700211 private final PermissionMonitor mPermissionMonitor;
212
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700213 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700214
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700215 @GuardedBy("mVpns")
216 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700217
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700218 private boolean mLockdownEnabled;
219 private LockdownVpnTracker mLockdownTracker;
220
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700221 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
222 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700223 /** Currently active network rules by UID. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600224 @GuardedBy("mRulesLock")
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700225 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700226 /** Set of ifaces that are costly. */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600227 @GuardedBy("mRulesLock")
228 private ArraySet<String> mMeteredIfaces = new ArraySet<>();
229 /** Flag indicating if background data is restricted. */
230 @GuardedBy("mRulesLock")
231 private boolean mRestrictBackground;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700232
Erik Klineda4bfa82015-04-30 12:58:40 +0900233 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700235 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700236 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800238 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800239
240 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700241 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700243 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800244 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700245 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700246
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700247 private String mCurrentTcpBufferSizes;
248
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700249 private static final int ENABLED = 1;
250 private static final int DISABLED = 0;
251
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900252 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900253 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
254 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900255
Paul Jensenb10e37f2014-11-25 12:33:08 -0500256 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400257 // Tear down networks that have no chance (e.g. even if validated) of becoming
258 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500259 // all networks have been rematched against all NetworkRequests.
260 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400261 // Don't reap networks. This should be passed when some networks have not yet been
262 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500263 DONT_REAP
264 };
265
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267 * used internally to change our mobile data enabled flag
268 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700269 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700270
271 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700272 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700273 * from one net to another. Clear happens when we get a new
274 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
275 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700276 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700277 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700278
Robert Greenwalt434203a2010-10-11 16:00:27 -0700279 /**
280 * used internally to reload global proxy settings
281 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700282 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700283
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700284 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400285 * PAC manager has received new port.
286 */
287 private static final int EVENT_PROXY_HAS_CHANGED = 16;
288
Robert Greenwalte049c232014-04-11 15:53:27 -0700289 /**
290 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700291 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700292 */
293 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
294
Robert Greenwalt7b816022014-04-18 15:25:25 -0700295 /**
296 * used internally when registering NetworkAgents
297 * obj = Messenger
298 */
299 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
300
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 /**
302 * used to add a network request
303 * includes a NetworkRequestInfo
304 */
305 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
306
307 /**
308 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900309 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700310 * cancel it.
311 * includes a NetworkRequestInfo
312 */
313 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
314
315 /**
316 * used to add a network listener - no request
317 * includes a NetworkRequestInfo
318 */
319 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
320
321 /**
322 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400323 * arg1 = UID of caller
324 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700325 */
326 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
327
Robert Greenwalta67be032014-05-16 15:49:14 -0700328 /**
329 * used internally when registering NetworkFactories
330 * obj = Messenger
331 */
332 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
333
Robert Greenwalt27711812014-06-25 16:45:57 -0700334 /**
335 * used internally to expire a wakelock when transitioning
336 * from one net to another. Expire happens when we fail to find
337 * a new network (typically after 1 minute) -
338 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
339 * a replacement network.
340 */
341 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
342
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700343 /**
344 * Used internally to indicate the system is ready.
345 */
346 private static final int EVENT_SYSTEM_READY = 25;
347
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800348 /**
349 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400350 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800351 */
352 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
353
354 /**
355 * used to remove a pending intent and its associated network request.
356 * arg1 = UID of caller
357 * obj = PendingIntent
358 */
359 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
360
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900361 /**
362 * used to specify whether a network should be used even if unvalidated.
363 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
364 * arg2 = whether to remember this choice in the future (1 or 0)
365 * obj = network
366 */
367 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
368
369 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900370 * used to specify whether a network should not be penalized when it becomes unvalidated.
371 */
372 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
373
374 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900375 * used to ask the user to confirm a connection to an unvalidated network.
376 * obj = network
377 */
378 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700379
Erik Klineda4bfa82015-04-30 12:58:40 +0900380 /**
381 * used internally to (re)configure mobile data always-on settings.
382 */
383 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
384
Paul Jensen694f2b82015-06-17 14:15:39 -0400385 /**
386 * used to add a network listener with a pending intent
387 * obj = NetworkRequestInfo
388 */
389 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
390
Erik Klineacdd6392016-07-07 16:50:58 +0900391 /**
392 * Indicates a caller has requested to have its callback invoked with
393 * the latest LinkProperties or NetworkCapabilities.
394 *
395 * arg1 = UID of caller
396 * obj = NetworkRequest
397 */
398 private static final int EVENT_REQUEST_LINKPROPERTIES = 32;
399 private static final int EVENT_REQUEST_NETCAPABILITIES = 33;
400
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900401 /** Handler thread used for both of the handlers below. */
402 @VisibleForTesting
403 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700404 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700405 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700406 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700407 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700408
Mike Lockwood0f79b542009-08-14 14:18:49 -0400409 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800410 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400411
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700412 private PowerManager.WakeLock mNetTransitionWakeLock;
413 private String mNetTransitionWakeLockCausedBy = "";
414 private int mNetTransitionWakeLockSerialNumber;
415 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800416 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700417
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700418 // used in DBG mode to track inet condition reports
419 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
420 private ArrayList mInetLog;
421
Robert Greenwalt434203a2010-10-11 16:00:27 -0700422 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400423 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700424 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700425 private boolean mDefaultProxyDisabled = false;
426
Robert Greenwalt434203a2010-10-11 16:00:27 -0700427 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400428 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700429
Jason Monk602b2322013-07-03 17:04:33 -0400430 private PacManager mPacManager = null;
431
Erik Klineda4bfa82015-04-30 12:58:40 +0900432 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700433
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400434 private UserManager mUserManager;
435
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700436 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700437 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700438
Robert Greenwalt50393202011-06-21 17:26:14 -0700439 // the set of network types that can only be enabled by system/sig apps
440 List mProtectedNetworks;
441
John Spurlockbf991a82013-06-24 14:20:23 -0400442 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700443
Wink Savilleab9321d2013-06-29 21:10:57 -0700444 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400445
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900446 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900447 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900448 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900449
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700450 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
451 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700452 private final static int MAX_NET_ID = 65535;
453 private int mNextNetId = MIN_NET_ID;
454
Robert Greenwalt34524f02014-05-18 16:22:10 -0700455 // sequence number of NetworkRequests
456 private int mNextNetworkRequestId = 1;
457
Erik Kline7523eb32015-07-09 18:24:03 +0900458 // NetworkRequest activity String log entries.
459 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
460 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
461
Hugo Benichic2ae2872016-07-11 11:05:12 +0900462 // NetworkInfo blocked and unblocked String log entries
463 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
464 private static final int MAX_NETWORK_INFO_LOGS = 100;
465 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
466
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700467 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
468 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400469 private static class ValidationLog {
470 final Network mNetwork;
471 final String mNetworkExtraInfo;
472 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700473
Paul Jensen0808eb82016-06-03 13:51:21 -0400474 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
475 mNetwork = network;
476 mNetworkExtraInfo = networkExtraInfo;
477 mLog = log;
478 }
479 }
480 private final ArrayDeque<ValidationLog> mValidationLogs =
481 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
482
483 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700484 synchronized(mValidationLogs) {
485 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
486 mValidationLogs.removeLast();
487 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400488 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700489 }
490 }
491
Hugo Benichif9fdf872016-07-28 17:53:06 +0900492 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900493
Erik Kline065ab6e2016-10-02 18:02:14 +0900494 @VisibleForTesting
495 final AvoidBadWifiTracker mAvoidBadWifiTracker;
496
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700497 /**
498 * Implements support for the legacy "one network per network type" model.
499 *
500 * We used to have a static array of NetworkStateTrackers, one for each
501 * network type, but that doesn't work any more now that we can have,
502 * for example, more that one wifi network. This class stores all the
503 * NetworkAgentInfo objects that support a given type, but the legacy
504 * API will only see the first one.
505 *
506 * It serves two main purposes:
507 *
508 * 1. Provide information about "the network for a given type" (since this
509 * API only supports one).
510 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
511 * the first network for a given type changes, or if the default network
512 * changes.
513 */
514 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900516 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900517 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900518
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 /**
520 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
521 * Each list holds references to all NetworkAgentInfos that are used to
522 * satisfy requests for that network type.
523 *
524 * This array is built out at startup such that an unsupported network
525 * doesn't get an ArrayList instance, making this a tristate:
526 * unsupported, supported but not active and active.
527 *
528 * The actual lists are populated when we scan the network types that
529 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900530 *
531 * Threading model:
532 * - addSupportedType() is only called in the constructor
533 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
534 * They are therefore not thread-safe with respect to each other.
535 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
536 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
537 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900539 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700540
541 public LegacyTypeTracker() {
542 mTypeLists = (ArrayList<NetworkAgentInfo>[])
543 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
544 }
545
546 public void addSupportedType(int type) {
547 if (mTypeLists[type] != null) {
548 throw new IllegalStateException(
549 "legacy list for type " + type + "already initialized");
550 }
551 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
552 }
553
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700554 public boolean isTypeSupported(int type) {
555 return isNetworkTypeValid(type) && mTypeLists[type] != null;
556 }
557
558 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900559 synchronized (mTypeLists) {
560 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
561 return mTypeLists[type].get(0);
562 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900564 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700565 }
566
Robert Greenwalt8d482522015-06-24 13:23:42 -0700567 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900568 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700570 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900571 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900572 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900573 }
574 }
575
576 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700577 public void add(int type, NetworkAgentInfo nai) {
578 if (!isTypeSupported(type)) {
579 return; // Invalid network type.
580 }
581 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
582
583 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
584 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700585 return;
586 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900587 synchronized (mTypeLists) {
588 list.add(nai);
589 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900590
591 // 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 +0900592 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900593 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700594 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
595 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
598
Lorenzo Colittia793a672014-07-31 23:20:17 +0900599 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900600 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900601 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
602 if (list == null || list.isEmpty()) {
603 return;
604 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900605 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606
Hugo Benichi78caa2582016-06-21 09:48:07 +0900607 synchronized (mTypeLists) {
608 if (!list.remove(nai)) {
609 return;
610 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900611 }
612
Robert Greenwalt8d482522015-06-24 13:23:42 -0700613 final DetailedState state = DetailedState.DISCONNECTED;
614
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900615 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700616 maybeLogBroadcast(nai, state, type, wasDefault);
617 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618 }
619
620 if (!list.isEmpty() && wasFirstNetwork) {
621 if (DBG) log("Other network available for type " + type +
622 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900623 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700624 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
625 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900626 }
627 }
628
629 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
631 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900633 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700634 }
635 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700636
Robert Greenwalt8d482522015-06-24 13:23:42 -0700637 // send out another legacy broadcast - currently only used for suspend/unsuspend
638 // toggle
639 public void update(NetworkAgentInfo nai) {
640 final boolean isDefault = isDefaultNetwork(nai);
641 final DetailedState state = nai.networkInfo.getDetailedState();
642 for (int type = 0; type < mTypeLists.length; type++) {
643 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700644 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900645 final boolean isFirst = contains && (nai == list.get(0));
646 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700647 maybeLogBroadcast(nai, state, type, isDefault);
648 sendLegacyNetworkBroadcast(nai, state, type);
649 }
650 }
651 }
652
Lorenzo Colittia793a672014-07-31 23:20:17 +0900653 private String naiToString(NetworkAgentInfo nai) {
654 String name = (nai != null) ? nai.name() : "null";
655 String state = (nai.networkInfo != null) ?
656 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
657 "???/???";
658 return name + " " + state;
659 }
660
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700661 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900662 pw.println("mLegacyTypeTracker:");
663 pw.increaseIndent();
664 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700665 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900666 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700667 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900668 pw.println();
669 pw.println("Current state:");
670 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900671 synchronized (mTypeLists) {
672 for (int type = 0; type < mTypeLists.length; type++) {
673 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
674 for (NetworkAgentInfo nai : mTypeLists[type]) {
675 pw.println(type + " " + naiToString(nai));
676 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900677 }
678 }
679 pw.decreaseIndent();
680 pw.decreaseIndent();
681 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700682 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700683 }
684 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
685
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900686 @VisibleForTesting
687 protected HandlerThread createHandlerThread() {
688 return new HandlerThread("ConnectivityServiceThread");
689 }
690
Jeff Sharkey899223b2012-08-04 15:24:58 -0700691 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700692 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900693 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
694 }
695
696 @VisibleForTesting
697 protected ConnectivityService(Context context, INetworkManagementService netManager,
698 INetworkStatsService statsService, INetworkPolicyManager policyManager,
699 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800700 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800701
Hugo Benichif9fdf872016-07-28 17:53:06 +0900702 mMetricsLog = logger;
Erik Klineda4bfa82015-04-30 12:58:40 +0900703 mDefaultRequest = createInternetRequestForTransport(-1);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900704 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900705 mNetworkRequests.put(mDefaultRequest, defaultNRI);
706 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900707
708 mDefaultMobileDataRequest = createInternetRequestForTransport(
709 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700710
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900711 mHandlerThread = createHandlerThread();
712 mHandlerThread.start();
713 mHandler = new InternalHandler(mHandlerThread.getLooper());
714 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700715
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800716 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800717 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
718 String id = Settings.Secure.getString(context.getContentResolver(),
719 Settings.Secure.ANDROID_ID);
720 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700721 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800722 SystemProperties.set("net.hostname", name);
723 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800724 }
725
Jeremy Joslin79294842014-12-03 17:15:28 -0800726 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
727 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
728
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900729 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
730
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700731 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700732 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800733 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700734 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700735 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700736 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700737
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700738 try {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600739 mPolicyManager.setConnectivityListener(mPolicyListener);
740 mRestrictBackground = mPolicyManager.getRestrictBackground();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700741 } catch (RemoteException e) {
742 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700743 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700744 }
745
746 final PowerManager powerManager = (PowerManager) context.getSystemService(
747 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700748 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
749 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
750 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800751 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700752
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700753 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700754
Wink Saville51f456f2013-04-23 14:26:51 -0700755 // TODO: What is the "correct" way to do determine if this is a wifi only device?
756 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
757 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700758 String[] naStrings = context.getResources().getStringArray(
759 com.android.internal.R.array.networkAttributes);
760 for (String naString : naStrings) {
761 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700762 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700763 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700764 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800765 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700766 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700767 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700768 }
Wink Saville51f456f2013-04-23 14:26:51 -0700769 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
770 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
771 n.type);
772 continue;
773 }
Wink Saville975c8482011-04-07 14:23:45 -0700774 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800775 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700776 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700777 continue;
778 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700779 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700780
Wink Saville975c8482011-04-07 14:23:45 -0700781 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700782 mNetworksDefined++;
783 } catch(Exception e) {
784 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700785 }
786 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700787
788 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
789 if (mNetConfigs[TYPE_VPN] == null) {
790 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
791 // don't need to add TYPE_VPN to mNetConfigs.
792 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
793 mNetworksDefined++; // used only in the log() statement below.
794 }
795
Wink Saville5e56bc52013-07-29 15:00:57 -0700796 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700797
Robert Greenwalt50393202011-06-21 17:26:14 -0700798 mProtectedNetworks = new ArrayList<Integer>();
799 int[] protectedNetworks = context.getResources().getIntArray(
800 com.android.internal.R.array.config_protectedNetworks);
801 for (int p : protectedNetworks) {
802 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
803 mProtectedNetworks.add(p);
804 } else {
805 if (DBG) loge("Ignoring protectedNetwork " + p);
806 }
807 }
808
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700809 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
810 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700811
Jeremy Kleinfa8712b2016-01-26 11:10:55 -0800812 mTethering = new Tethering(mContext, mNetd, statsService);
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800813
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700814 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
815
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700816 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700817 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100818 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700819 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700820 intentFilter.addAction(Intent.ACTION_USER_ADDED);
821 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000822 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700823 mContext.registerReceiverAsUser(
824 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900825
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700826 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700827 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700828 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700829 } catch (RemoteException e) {
830 loge("Error registering observer :" + e);
831 }
832
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700833 if (DBG) {
834 mInetLog = new ArrayList();
835 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700836
Erik Klineda4bfa82015-04-30 12:58:40 +0900837 mSettingsObserver = new SettingsObserver(mContext, mHandler);
838 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800839
John Spurlockbf991a82013-06-24 14:20:23 -0400840 mDataConnectionStats = new DataConnectionStats(mContext);
841 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400842
Jason Monkdecd2952013-10-10 14:02:51 -0400843 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700844
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400845 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900846
847 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900848 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
849 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900850
851 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
852 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
853 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
854 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
855 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
856 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
857 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900858
Erik Kline065ab6e2016-10-02 18:02:14 +0900859 mAvoidBadWifiTracker = createAvoidBadWifiTracker(
860 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800861 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700862
Erik Klineda4bfa82015-04-30 12:58:40 +0900863 private NetworkRequest createInternetRequestForTransport(int transportType) {
864 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900865 netCap.addCapability(NET_CAPABILITY_INTERNET);
866 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900867 if (transportType > -1) {
868 netCap.addTransportType(transportType);
869 }
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900870 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(),
871 NetworkRequest.Type.REQUEST);
Erik Klineda4bfa82015-04-30 12:58:40 +0900872 }
873
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900874 // Used only for testing.
875 // TODO: Delete this and either:
876 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
877 // changing ContentResolver to make registerContentObserver non-final).
878 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
879 // by subclassing SettingsObserver.
880 @VisibleForTesting
881 void updateMobileDataAlwaysOn() {
882 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
883 }
884
Erik Klineda4bfa82015-04-30 12:58:40 +0900885 private void handleMobileDataAlwaysOn() {
886 final boolean enable = (Settings.Global.getInt(
887 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
888 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
889 if (enable == isEnabled) {
890 return; // Nothing to do.
891 }
892
893 if (enable) {
894 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900895 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900896 } else {
897 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
898 }
899 }
900
901 private void registerSettingsCallbacks() {
902 // Watch for global HTTP proxy changes.
903 mSettingsObserver.observe(
904 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
905 EVENT_APPLY_GLOBAL_HTTP_PROXY);
906
907 // Watch for whether or not to keep mobile data always on.
908 mSettingsObserver.observe(
909 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
910 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
911 }
912
Robert Greenwalt34524f02014-05-18 16:22:10 -0700913 private synchronized int nextNetworkRequestId() {
914 return mNextNetworkRequestId++;
915 }
916
Paul Jensen67b0b072015-06-10 11:22:17 -0400917 @VisibleForTesting
918 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400919 synchronized (mNetworkForNetId) {
920 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
921 int netId = mNextNetId;
922 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
923 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500924 if (!mNetIdInUse.get(netId)) {
925 mNetIdInUse.put(netId, true);
926 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400927 }
928 }
929 }
930 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700931 }
932
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600933 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600935 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
936 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800937 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600938 state = nai.getNetworkState();
939 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800940 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600941 final NetworkInfo info = new NetworkInfo(networkType, 0,
942 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800943 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
944 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600945 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
946 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800947 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600948 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600949 return state;
950 } else {
951 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800952 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400953 }
954
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800955 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
956 if (network == null) {
957 return null;
958 }
959 synchronized (mNetworkForNetId) {
960 return mNetworkForNetId.get(network.netId);
961 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600962 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800963
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900964 private Network[] getVpnUnderlyingNetworks(int uid) {
965 if (!mLockdownEnabled) {
966 int user = UserHandle.getUserId(uid);
967 synchronized (mVpns) {
968 Vpn vpn = mVpns.get(user);
969 if (vpn != null && vpn.appliesToUid(uid)) {
970 return vpn.getUnderlyingNetworks();
971 }
972 }
973 }
974 return null;
975 }
976
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800977 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400978 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800979
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900980 final Network[] networks = getVpnUnderlyingNetworks(uid);
981 if (networks != null) {
982 // getUnderlyingNetworks() returns:
983 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
984 // empty array => the VPN explicitly said "no default network".
985 // non-empty array => the VPN specified one or more default networks; we use the
986 // first one.
987 if (networks.length > 0) {
988 nai = getNetworkAgentInfoForNetwork(networks[0]);
989 } else {
990 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800991 }
992 }
993
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800994 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600995 return nai.getNetworkState();
996 } else {
997 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800998 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400999 }
1000
1001 /**
1002 * Check if UID should be blocked from using the network with the given LinkProperties.
1003 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001004 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1005 boolean ignoreBlocked) {
1006 // Networks aren't blocked when ignoring blocked status
1007 if (ignoreBlocked) return false;
1008 // Networks are never blocked for system services
Felipe Lemeee27cab2016-06-20 16:36:29 -07001009 if (isSystem(uid)) return false;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001010
1011 final boolean networkMetered;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001012 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -07001013
Robin Lee17e61832016-05-09 13:46:28 +01001014 synchronized (mVpns) {
1015 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1016 if (vpn != null && vpn.isBlockingUid(uid)) {
1017 return true;
1018 }
1019 }
1020
Robert Greenwalt12e67352014-05-13 21:41:06 -07001021 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001022 synchronized (mRulesLock) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001023 networkMetered = mMeteredIfaces.contains(iface);
Felipe Leme46c4fc32016-05-04 09:21:43 -07001024 uidRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001025 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001026
Felipe Lemed31a97f2016-05-06 14:53:50 -07001027 boolean allowed = true;
1028 // Check Data Saver Mode first...
1029 if (networkMetered) {
1030 if ((uidRules & RULE_REJECT_METERED) != 0) {
1031 if (LOGD_RULES) Log.d(TAG, "uid " + uid + " is blacklisted");
1032 // Explicitly blacklisted.
1033 allowed = false;
1034 } else {
1035 allowed = !mRestrictBackground
1036 || (uidRules & RULE_ALLOW_METERED) != 0
1037 || (uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0;
1038 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
1039 + " mRestrictBackground=" + mRestrictBackground
1040 + ", whitelisted=" + ((uidRules & RULE_ALLOW_METERED) != 0)
1041 + ", tempWhitelist= + ((uidRules & RULE_TEMPORARY_ALLOW_METERED) != 0)"
1042 + ": " + allowed);
1043 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001044 }
Felipe Leme781ba142016-05-09 16:24:48 -07001045 // ...then power restrictions.
1046 if (allowed) {
1047 allowed = (uidRules & RULE_REJECT_ALL) == 0;
Felipe Lemed31a97f2016-05-06 14:53:50 -07001048 if (LOGD_RULES) Log.d(TAG, "allowed status for uid " + uid + " when"
Felipe Leme781ba142016-05-09 16:24:48 -07001049 + " rule is " + uidRulesToString(uidRules) + ": " + allowed);
Felipe Lemed31a97f2016-05-06 14:53:50 -07001050 }
1051 return !allowed;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 }
1053
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001054 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001055 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1056 return;
1057 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001058 boolean removed = false;
1059 boolean added = false;
1060 synchronized (mBlockedAppUids) {
1061 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1062 added = true;
1063 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1064 removed = true;
1065 }
1066 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001067 if (added) {
1068 log("Returning blocked NetworkInfo to uid=" + uid);
1069 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1070 } else if (removed) {
1071 log("Returning unblocked NetworkInfo to uid=" + uid);
1072 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1073 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001074 }
1075
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001076 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001077 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1078 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1079 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1080 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001081 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001082 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001083 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1084
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001085 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001086 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001087 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001088 if (mLockdownTracker != null) {
1089 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001090 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001091
1092 // TODO: apply metered state closer to NetworkAgentInfo
1093 final long token = Binder.clearCallingIdentity();
1094 try {
1095 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1096 } catch (RemoteException e) {
1097 } finally {
1098 Binder.restoreCallingIdentity(token);
1099 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001100 }
1101
1102 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001103 * Return NetworkInfo for the active (i.e., connected) network interface.
1104 * It is assumed that at most one network is active at a time. If more
1105 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001106 * @return the info for the active network, or {@code null} if none is
1107 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001109 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001110 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 enforceAccessPermission();
1112 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001113 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001114 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001115 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1116 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001117 }
1118
Paul Jensen31a94f42015-02-13 14:18:39 -05001119 @Override
1120 public Network getActiveNetwork() {
1121 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001123 }
1124
1125 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001126 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001127 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001128 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001129 }
1130
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001131 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001132 final int user = UserHandle.getUserId(uid);
1133 int vpnNetId = NETID_UNSET;
1134 synchronized (mVpns) {
1135 final Vpn vpn = mVpns.get(user);
1136 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1137 }
1138 NetworkAgentInfo nai;
1139 if (vpnNetId != NETID_UNSET) {
1140 synchronized (mNetworkForNetId) {
1141 nai = mNetworkForNetId.get(vpnNetId);
1142 }
1143 if (nai != null) return nai.network;
1144 }
1145 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001146 if (nai != null
1147 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1148 nai = null;
1149 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001150 return nai != null ? nai.network : null;
1151 }
1152
Lorenzo Colitti18660282016-07-04 12:55:44 +09001153 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001154 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1155 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001156 final int uid = Binder.getCallingUid();
1157 NetworkState state = getUnfilteredActiveNetworkState(uid);
1158 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001159 }
1160
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001161 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001162 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001164 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001165 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001166 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001167 }
1168
1169 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 public NetworkInfo getNetworkInfo(int networkType) {
1171 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001172 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001173 if (getVpnUnderlyingNetworks(uid) != null) {
1174 // A VPN is active, so we may need to return one of its underlying networks. This
1175 // information is not available in LegacyTypeTracker, so we have to get it from
1176 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001177 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001178 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001179 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001180 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001181 }
1182 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001183 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001184 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
1186
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001188 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001189 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001190 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001191 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001192 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001193 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001194 return state.networkInfo;
1195 } else {
1196 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001197 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001198 }
1199
1200 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 public NetworkInfo[] getAllNetworkInfo() {
1202 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001203 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001204 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1205 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001206 NetworkInfo info = getNetworkInfo(networkType);
1207 if (info != null) {
1208 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001209 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001210 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001211 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001212 }
1213
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001214 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001215 public Network getNetworkForType(int networkType) {
1216 enforceAccessPermission();
1217 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001218 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1219 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001221 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001222 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001223 }
1224
1225 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001226 public Network[] getAllNetworks() {
1227 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001228 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001229 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001230 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001231 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001232 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001233 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001234 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001235 }
1236
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001237 @Override
1238 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1239 // The basic principle is: if an app's traffic could possibly go over a
1240 // network, without the app doing anything multinetwork-specific,
1241 // (hence, by "default"), then include that network's capabilities in
1242 // the array.
1243 //
1244 // In the normal case, app traffic only goes over the system's default
1245 // network connection, so that's the only network returned.
1246 //
1247 // With a VPN in force, some app traffic may go into the VPN, and thus
1248 // over whatever underlying networks the VPN specifies, while other app
1249 // traffic may go over the system default network (e.g.: a split-tunnel
1250 // VPN, or an app disallowed by the VPN), so the set of networks
1251 // returned includes the VPN's underlying networks and the system
1252 // default.
1253 enforceAccessPermission();
1254
1255 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1256
1257 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001258 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001259 if (nc != null) {
1260 result.put(nai.network, nc);
1261 }
1262
1263 if (!mLockdownEnabled) {
1264 synchronized (mVpns) {
1265 Vpn vpn = mVpns.get(userId);
1266 if (vpn != null) {
1267 Network[] networks = vpn.getUnderlyingNetworks();
1268 if (networks != null) {
1269 for (Network network : networks) {
1270 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001271 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001272 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001273 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001274 }
1275 }
1276 }
1277 }
1278 }
1279 }
1280
1281 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1282 out = result.values().toArray(out);
1283 return out;
1284 }
1285
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001286 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001287 public boolean isNetworkSupported(int networkType) {
1288 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001289 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001290 }
1291
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001292 /**
1293 * Return LinkProperties for the active (i.e., connected) default
1294 * network interface. It is assumed that at most one default network
1295 * is active at a time. If more than one is active, it is indeterminate
1296 * which will be returned.
1297 * @return the ip properties for the active network, or {@code null} if
1298 * none is active
1299 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001300 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001301 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001302 enforceAccessPermission();
1303 final int uid = Binder.getCallingUid();
1304 NetworkState state = getUnfilteredActiveNetworkState(uid);
1305 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001306 }
1307
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001308 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001309 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001310 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001311 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1312 if (nai != null) {
1313 synchronized (nai) {
1314 return new LinkProperties(nai.linkProperties);
1315 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001316 }
1317 return null;
1318 }
1319
Robert Greenwalt12e67352014-05-13 21:41:06 -07001320 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001321 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001322 public LinkProperties getLinkProperties(Network network) {
1323 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001324 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001325 if (nai != null) {
1326 synchronized (nai) {
1327 return new LinkProperties(nai.linkProperties);
1328 }
1329 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001330 return null;
1331 }
1332
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001333 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001334 if (nai != null) {
1335 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001336 if (nai.networkCapabilities != null) {
1337 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001338 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001339 }
1340 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001341 return null;
1342 }
1343
1344 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001345 public NetworkCapabilities getNetworkCapabilities(Network network) {
1346 enforceAccessPermission();
1347 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1348 }
1349
1350 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001351 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001352 // Require internal since we're handing out IMSI details
1353 enforceConnectivityInternalPermission();
1354
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001355 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001356 for (Network network : getAllNetworks()) {
1357 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1358 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001359 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001360 }
1361 }
1362 return result.toArray(new NetworkState[result.size()]);
1363 }
1364
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001365 @Override
1366 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1367 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001368 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001369 final long token = Binder.clearCallingIdentity();
1370 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001371 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1372 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001373 try {
1374 return mPolicyManager.getNetworkQuotaInfo(state);
1375 } catch (RemoteException e) {
1376 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001377 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001378 return null;
1379 } finally {
1380 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001381 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001382 }
1383
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001384 @Override
1385 public boolean isActiveNetworkMetered() {
1386 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001387
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001388 final NetworkInfo info = getActiveNetworkInfo();
1389 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001390 }
1391
Jeff Sharkey216c1812012-08-05 14:29:23 -07001392 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1393 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001394 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001395 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001396 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001397 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001398 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001399
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001400 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 * Ensure that a network route exists to deliver traffic to the specified
1402 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001403 * @param networkType the type of the network over which traffic to the
1404 * specified host is to be routed
1405 * @param hostAddress the IP address of the host to which the route is
1406 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001407 * @return {@code true} on success, {@code false} on failure
1408 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001409 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001410 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001412 if (mProtectedNetworks.contains(networkType)) {
1413 enforceConnectivityInternalPermission();
1414 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001415
Chad Brubakerc0234532014-02-14 13:24:29 -08001416 InetAddress addr;
1417 try {
1418 addr = InetAddress.getByAddress(hostAddress);
1419 } catch (UnknownHostException e) {
1420 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1421 return false;
1422 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001425 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001426 return false;
1427 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001428
1429 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1430 if (nai == null) {
1431 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1432 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1433 } else {
1434 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1435 }
1436 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001437 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001438
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001439 DetailedState netState;
1440 synchronized (nai) {
1441 netState = nai.networkInfo.getDetailedState();
1442 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001443
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001444 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001445 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001446 log("requestRouteToHostAddress on down network "
1447 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001448 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001449 }
1450 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001452
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001453 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001454 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001455 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001456 LinkProperties lp;
1457 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001458 synchronized (nai) {
1459 lp = nai.linkProperties;
1460 netId = nai.network.netId;
1461 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001462 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001463 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1464 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001465 } finally {
1466 Binder.restoreCallingIdentity(token);
1467 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001468 }
1469
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001470 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001471 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001472 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001473 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001474 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001475 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001476 if (bestRoute.getGateway().equals(addr)) {
1477 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001478 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001479 } else {
1480 // if we will connect to this through another route, add a direct route
1481 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001482 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001483 }
1484 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001485 if (DBG) log("Adding legacy route " + bestRoute +
1486 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001487 try {
1488 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1489 } catch (Exception e) {
1490 // never crash - catch them all
1491 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001492 return false;
1493 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001494 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001497 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1498 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001499 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001500 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001501 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001502 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001503 }
1504
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001505 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001506 // skip update when we've already applied rules
Felipe Lemed31a97f2016-05-06 14:53:50 -07001507 final int oldRules = mUidRules.get(uid, RULE_NONE);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001508 if (oldRules == uidRules) return;
1509
Felipe Leme781ba142016-05-09 16:24:48 -07001510 if (uidRules == RULE_NONE) {
1511 mUidRules.delete(uid);
1512 } else {
1513 mUidRules.put(uid, uidRules);
1514 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001515 }
1516
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001517 // TODO: notify UID when it has requested targeted updates
1518 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001519
1520 @Override
1521 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001522 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001523 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001524 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001525 }
1526
1527 synchronized (mRulesLock) {
1528 mMeteredIfaces.clear();
1529 for (String iface : meteredIfaces) {
1530 mMeteredIfaces.add(iface);
1531 }
1532 }
1533 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001534
1535 @Override
1536 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1537 // caller is NPMS, since we only register with them
1538 if (LOGD_RULES) {
1539 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1540 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001541
1542 synchronized (mRulesLock) {
1543 mRestrictBackground = restrictBackground;
1544 }
1545
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001546 if (restrictBackground) {
1547 log("onRestrictBackgroundChanged(true): disabling tethering");
1548 mTethering.untetherAll();
1549 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001550 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001551
1552 @Override
1553 public void onRestrictBackgroundWhitelistChanged(int uid, boolean whitelisted) {
1554 if (LOGD_RULES) {
1555 // caller is NPMS, since we only register with them
1556 log("onRestrictBackgroundWhitelistChanged(uid=" + uid + ", whitelisted="
1557 + whitelisted + ")");
1558 }
1559 }
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001560 @Override
1561 public void onRestrictBackgroundBlacklistChanged(int uid, boolean blacklisted) {
1562 if (LOGD_RULES) {
1563 // caller is NPMS, since we only register with them
1564 log("onRestrictBackgroundBlacklistChanged(uid=" + uid + ", blacklisted="
1565 + blacklisted + ")");
1566 }
1567 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001568 };
1569
Robin Lee3b3dd942015-05-12 18:14:58 +01001570 /**
1571 * Require that the caller is either in the same user or has appropriate permission to interact
1572 * across users.
1573 *
1574 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1575 */
1576 private void enforceCrossUserPermission(int userId) {
1577 if (userId == UserHandle.getCallingUserId()) {
1578 // Not a cross-user call.
1579 return;
1580 }
1581 mContext.enforceCallingOrSelfPermission(
1582 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1583 "ConnectivityService");
1584 }
1585
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001586 private void enforceInternetPermission() {
1587 mContext.enforceCallingOrSelfPermission(
1588 android.Manifest.permission.INTERNET,
1589 "ConnectivityService");
1590 }
1591
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001592 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001593 mContext.enforceCallingOrSelfPermission(
1594 android.Manifest.permission.ACCESS_NETWORK_STATE,
1595 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 }
1597
1598 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001599 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001600 }
1601
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001602 private void enforceTetherAccessPermission() {
1603 mContext.enforceCallingOrSelfPermission(
1604 android.Manifest.permission.ACCESS_NETWORK_STATE,
1605 "ConnectivityService");
1606 }
1607
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001608 private void enforceConnectivityInternalPermission() {
1609 mContext.enforceCallingOrSelfPermission(
1610 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1611 "ConnectivityService");
1612 }
1613
Hugo Benichi514da602016-07-19 15:59:27 +09001614 private void enforceConnectivityRestrictedNetworksPermission() {
1615 try {
1616 mContext.enforceCallingOrSelfPermission(
1617 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1618 "ConnectivityService");
1619 return;
1620 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1621 enforceConnectivityInternalPermission();
1622 }
1623
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001624 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001625 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001626 }
1627
Lorenzo Colitti18660282016-07-04 12:55:44 +09001628 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001629 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001630 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001631 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001632 }
1633
1634 private void sendInetConditionBroadcast(NetworkInfo info) {
1635 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1636 }
1637
Wink Saville628b0852011-08-04 15:01:58 -07001638 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001639 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001640 info = new NetworkInfo(info);
1641 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001642 }
1643
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001644 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001645 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001646 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001647 if (info.isFailover()) {
1648 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1649 info.setFailover(false);
1650 }
1651 if (info.getReason() != null) {
1652 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1653 }
1654 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001655 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1656 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001657 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001658 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001659 return intent;
1660 }
1661
1662 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1663 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1664 }
1665
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001666 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001667 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1668 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1669 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001670 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001671 final long ident = Binder.clearCallingIdentity();
1672 try {
1673 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1674 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1675 } finally {
1676 Binder.restoreCallingIdentity(ident);
1677 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001678 }
1679
Mike Lockwood0f79b542009-08-14 14:18:49 -04001680 private void sendStickyBroadcast(Intent intent) {
1681 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001682 if (!mSystemReady) {
1683 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001684 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001685 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001686 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001687 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001688 }
1689
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001690 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001691 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001692 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001693 final NetworkInfo ni = intent.getParcelableExtra(
1694 ConnectivityManager.EXTRA_NETWORK_INFO);
1695 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1696 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1697 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001698 } else {
1699 BroadcastOptions opts = BroadcastOptions.makeBasic();
1700 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1701 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001702 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001703 final IBatteryStats bs = BatteryStatsService.getService();
1704 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001705 bs.noteConnectivityChanged(intent.getIntExtra(
1706 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1707 ni != null ? ni.getState().toString() : "?");
1708 } catch (RemoteException e) {
1709 }
1710 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001711 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001712 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001713 } finally {
1714 Binder.restoreCallingIdentity(ident);
1715 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001716 }
1717 }
1718
1719 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001720 loadGlobalProxy();
1721
Mike Lockwood0f79b542009-08-14 14:18:49 -04001722 synchronized(this) {
1723 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001724 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001725 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001726 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001727 }
1728 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001729 // load the global proxy at startup
1730 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001731
Robin Lee244ce8e2016-01-05 18:03:46 +00001732 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1733 // for user to unlock device too.
1734 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001735
Erik Klineda4bfa82015-04-30 12:58:40 +09001736 // Configure whether mobile data is always on.
1737 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1738
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001739 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001740
1741 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 }
1743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001745 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001746 *
1747 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001748 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001749 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1751 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001752
1753 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001754 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001755
Robert Greenwalt7b816022014-04-18 15:25:25 -07001756 if (networkAgent.networkCapabilities.hasTransport(
1757 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001758 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1759 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001760 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001761 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001762 } else if (networkAgent.networkCapabilities.hasTransport(
1763 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001764 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1765 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001766 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001767 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001768 } else {
1769 // do not track any other networks
1770 timeout = 0;
1771 }
1772
Robert Greenwalt7b816022014-04-18 15:25:25 -07001773 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001774 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001775 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001776 } catch (Exception e) {
1777 // You shall not crash!
1778 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001779 }
1780 }
1781 }
1782
1783 /**
1784 * Remove data activity tracking when network disconnects.
1785 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001786 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1787 final String iface = networkAgent.linkProperties.getInterfaceName();
1788 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001789
Robert Greenwalt7b816022014-04-18 15:25:25 -07001790 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1791 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001792 try {
1793 // the call fails silently if no idletimer setup for this interface
1794 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001795 } catch (Exception e) {
1796 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001797 }
1798 }
1799 }
1800
1801 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001802 * Reads the network specific MTU size from reources.
1803 * and set it on it's iface.
1804 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001805 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1806 final String iface = newLp.getInterfaceName();
1807 final int mtu = newLp.getMtu();
1808 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1809 if (VDBG) log("identical MTU - not setting");
1810 return;
1811 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001812
Robert Greenwalt43074032014-08-15 17:53:05 -07001813 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001814 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001815 return;
1816 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001817
w1997615afd812014-08-05 15:18:11 -07001818 // Cannot set MTU without interface name
1819 if (TextUtils.isEmpty(iface)) {
1820 loge("Setting MTU size with null iface.");
1821 return;
1822 }
1823
Robert Greenwalt7b816022014-04-18 15:25:25 -07001824 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001825 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001826 mNetd.setMtu(iface, mtu);
1827 } catch (Exception e) {
1828 Slog.e(TAG, "exception in setMtu()" + e);
1829 }
1830 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001831
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001832 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001833 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1834
1835 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001836 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001837 protected int getDefaultTcpRwnd() {
1838 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1839 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001840
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001841 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1842 if (isDefaultNetwork(nai) == false) {
1843 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001844 }
1845
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001846 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1847 String[] values = null;
1848 if (tcpBufferSizes != null) {
1849 values = tcpBufferSizes.split(",");
1850 }
1851
1852 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001853 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001854 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1855 values = tcpBufferSizes.split(",");
1856 }
1857
1858 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1859
1860 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001861 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001862
1863 final String prefix = "/sys/kernel/ipv4/tcp_";
1864 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1865 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1866 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1867 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1868 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1869 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1870 mCurrentTcpBufferSizes = tcpBufferSizes;
1871 } catch (IOException e) {
1872 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001873 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001874
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001875 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001876 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001877 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1878 if (rwndValue != 0) {
1879 SystemProperties.set(sysctlKey, rwndValue.toString());
1880 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001881 }
1882
Mattias Falk8b47b362011-08-23 14:15:13 +02001883 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001884 /*
1885 * Tell the VMs to toss their DNS caches
1886 */
1887 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1888 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001889 /*
1890 * Connectivity events can happen before boot has completed ...
1891 */
1892 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001893 final long ident = Binder.clearCallingIdentity();
1894 try {
1895 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1896 } finally {
1897 Binder.restoreCallingIdentity(ident);
1898 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001899 }
1900
Robert Greenwalt562cc542014-05-15 18:07:26 -07001901 @Override
1902 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001903 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1904 NETWORK_RESTORE_DELAY_PROP_NAME);
1905 if(restoreDefaultNetworkDelayStr != null &&
1906 restoreDefaultNetworkDelayStr.length() != 0) {
1907 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001908 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001909 } catch (NumberFormatException e) {
1910 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001911 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001912 // if the system property isn't set, use the value for the apn type
1913 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1914
1915 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1916 (mNetConfigs[networkType] != null)) {
1917 ret = mNetConfigs[networkType].restoreTime;
1918 }
1919 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001920 }
1921
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001922 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001923 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001924 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001925 }
1926 return false;
1927 }
1928
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001929 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1930 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1931 final long DIAG_TIME_MS = 5000;
1932 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1933 // Start gathering diagnostic information.
1934 netDiags.add(new NetworkDiagnostics(
1935 nai.network,
1936 new LinkProperties(nai.linkProperties), // Must be a copy.
1937 DIAG_TIME_MS));
1938 }
1939
1940 for (NetworkDiagnostics netDiag : netDiags) {
1941 pw.println();
1942 netDiag.waitForMeasurements();
1943 netDiag.dump(pw);
1944 }
1945 }
1946
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001947 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001948 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1949 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001950 if (mContext.checkCallingOrSelfPermission(
1951 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001952 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001953 pw.println("Permission Denial: can't dump ConnectivityService " +
1954 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1955 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001956 return;
1957 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001958
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001959 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001960 dumpNetworkDiagnostics(pw);
1961 return;
1962 }
Erik Kline379747a2015-06-05 17:47:34 +09001963
Lorenzo Colittie3805462015-06-03 11:18:24 +09001964 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001965 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001966 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001967 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001968 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001969 pw.println();
1970
Paul Jensen85cf78e2015-06-25 13:25:07 -04001971 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001972 pw.print("Active default network: ");
1973 if (defaultNai == null) {
1974 pw.println("none");
1975 } else {
1976 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001977 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001978 pw.println();
1979
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001980 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001981 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001982 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1983 pw.println(nai.toString());
1984 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001985 pw.println(String.format("Requests: %d request/%d total",
1986 nai.numRequestNetworkRequests(), nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001987 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001988 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1989 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001990 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001991 pw.decreaseIndent();
1992 pw.println("Lingered:");
1993 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001994 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001995 pw.decreaseIndent();
1996 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001997 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001998 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001999 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08002000
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002001 pw.println("Metered Interfaces:");
2002 pw.increaseIndent();
2003 for (String value : mMeteredIfaces) {
2004 pw.println(value);
2005 }
2006 pw.decreaseIndent();
2007 pw.println();
2008
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06002009 pw.print("Restrict background: ");
2010 pw.println(mRestrictBackground);
2011 pw.println();
2012
Felipe Leme46c4fc32016-05-04 09:21:43 -07002013 pw.println("Status for known UIDs:");
2014 pw.increaseIndent();
2015 final int size = mUidRules.size();
2016 for (int i = 0; i < size; i++) {
2017 final int uid = mUidRules.keyAt(i);
2018 pw.print("UID=");
2019 pw.print(uid);
2020 final int uidRules = mUidRules.get(uid, RULE_NONE);
2021 pw.print(" rules=");
2022 pw.print(uidRulesToString(uidRules));
2023 pw.println();
2024 }
2025 pw.println();
2026 pw.decreaseIndent();
2027
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002028 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002029 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07002030 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2031 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08002032 }
2033 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002034 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002035
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002036 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07002037
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002038 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09002039 pw.print("mNetTransitionWakeLock: currently " +
2040 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
2041 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
2042 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
2043 } else {
2044 pw.println(", last requested never");
2045 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002046 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002047
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002048 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002049 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002050
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002051 pw.println();
2052 mKeepaliveTracker.dump(pw);
2053
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002054 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002055 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09002056
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002057 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09002058 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002059 pw.println();
2060 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002061 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002062 for(int i = 0; i < mInetLog.size(); i++) {
2063 pw.println(mInetLog.get(i));
2064 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07002065 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07002066 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002067
2068 if (argsContain(args, "--short") == false) {
2069 pw.println();
2070 synchronized (mValidationLogs) {
2071 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04002072 for (ValidationLog p : mValidationLogs) {
2073 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002074 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04002075 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002076 pw.decreaseIndent();
2077 }
2078 }
Erik Kline7523eb32015-07-09 18:24:03 +09002079
2080 pw.println();
2081 pw.println("mNetworkRequestInfoLogs (most recent first):");
2082 pw.increaseIndent();
2083 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2084 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002085
2086 pw.println();
2087 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2088 pw.increaseIndent();
2089 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2090 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002091 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002092 }
2093
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002094 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002095 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002096 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002097 if (officialNai != null && officialNai.equals(nai)) return true;
2098 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002099 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002100 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002101 " - " + nai);
2102 }
2103 return false;
2104 }
2105
Robert Greenwalt42acef32009-08-12 16:08:25 -07002106 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002107 private class NetworkStateTrackerHandler extends Handler {
2108 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002109 super(looper);
2110 }
2111
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002112 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002113 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002114 default:
2115 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002116 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002117 handleAsyncChannelHalfConnect(msg);
2118 break;
2119 }
2120 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2121 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2122 if (nai != null) nai.asyncChannel.disconnect();
2123 break;
2124 }
2125 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2126 handleAsyncChannelDisconnected(msg);
2127 break;
2128 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002129 }
2130 return true;
2131 }
2132
2133 private void maybeHandleNetworkAgentMessage(Message msg) {
2134 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2135 if (nai == null) {
2136 if (VDBG) {
2137 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2138 log(String.format("%s from unknown NetworkAgent", what));
2139 }
2140 return;
2141 }
2142
2143 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002145 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2146 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
2147 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
2148 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002149 }
Robin Lee585e2482016-05-01 23:00:00 +01002150 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002151 networkCapabilities)) {
2152 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
2153 + nai.networkCapabilities + " -> " + networkCapabilities);
2154 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002155 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002156 break;
2157 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002158 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002159 if (VDBG) {
2160 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002161 "; created=" + nai.created +
2162 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002163 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002164 LinkProperties oldLp = nai.linkProperties;
2165 synchronized (nai) {
2166 nai.linkProperties = (LinkProperties)msg.obj;
2167 }
Robin Lee585e2482016-05-01 23:00:00 +01002168 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002169 break;
2170 }
2171 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002172 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 updateNetworkInfo(nai, info);
2174 break;
2175 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002176 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002177 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002178 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002179 break;
2180 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002181 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002182 try {
2183 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002184 } catch (Exception e) {
2185 // Never crash!
2186 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002187 }
2188 break;
2189 }
2190 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002191 try {
2192 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002193 } catch (Exception e) {
2194 // Never crash!
2195 loge("Exception in removeVpnUidRanges: " + e);
2196 }
2197 break;
2198 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002199 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002200 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2201 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002202 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002203 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002204 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002205 break;
2206 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002207 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002208 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2209 break;
2210 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002211 }
2212 }
2213
2214 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2215 switch (msg.what) {
2216 default:
2217 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002218 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002219 final NetworkAgentInfo nai;
2220 synchronized (mNetworkForNetId) {
2221 nai = mNetworkForNetId.get(msg.arg2);
2222 }
2223 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002224 final boolean valid =
2225 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002226 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002227 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2228 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002229 if (valid != nai.lastValidated) {
2230 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002231 nai.lastValidated = valid;
2232 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002233 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002234 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2235 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002236 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002237 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002238 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002239 Bundle redirectUrlBundle = new Bundle();
2240 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002241 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002242 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002243 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002244 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002245 if (wasValidated && !nai.lastValidated) {
2246 handleNetworkUnvalidated(nai);
2247 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002248 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002249 break;
2250 }
Paul Jensen869868be2014-05-15 10:33:05 -04002251 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002252 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002253 final boolean visible = (msg.arg1 != 0);
2254 final NetworkAgentInfo nai;
2255 synchronized (mNetworkForNetId) {
2256 nai = mNetworkForNetId.get(netId);
2257 }
2258 // If captive portal status has changed, update capabilities.
2259 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002260 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002261 nai.lastCaptivePortalDetected = visible;
2262 nai.everCaptivePortalDetected |= visible;
Hugo Benichif15b2822016-09-15 18:18:48 +09002263 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002264 }
2265 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002266 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002267 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002268 if (nai == null) {
2269 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2270 break;
2271 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002272 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002273 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002274 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002275 }
Paul Jensen869868be2014-05-15 10:33:05 -04002276 }
Paul Jensen869868be2014-05-15 10:33:05 -04002277 break;
2278 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002279 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002280 return true;
2281 }
2282
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002283 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2284 switch (msg.what) {
2285 default:
2286 return false;
2287 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2288 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2289 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2290 handleLingerComplete(nai);
2291 }
2292 break;
2293 }
2294 }
2295 return true;
2296 }
2297
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002298 @Override
2299 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002300 if (!maybeHandleAsyncChannelMessage(msg) &&
2301 !maybeHandleNetworkMonitorMessage(msg) &&
2302 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002303 maybeHandleNetworkAgentMessage(msg);
2304 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002305 }
2306 }
2307
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002308 private void updateLingerState(NetworkAgentInfo nai, long now) {
2309 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2310 // 2. If the network was lingering and there are now requests, unlinger it.
2311 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2312 // one lingered request, start lingering.
2313 nai.updateLingerTimer();
2314 if (nai.isLingering() && nai.numRequestNetworkRequests() > 0) {
2315 if (DBG) log("Unlingering " + nai.name());
2316 nai.unlinger();
2317 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
2318 } else if (unneeded(nai) && nai.getLingerExpiry() > 0) { // unneeded() calls isLingering()
2319 int lingerTime = (int) (nai.getLingerExpiry() - now);
2320 if (DBG) {
2321 Log.d(TAG, "Lingering " + nai.name() + " for " + lingerTime + "ms");
2322 }
2323 nai.linger();
2324 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2325 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2326 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002327 }
2328
Robert Greenwalt7b816022014-04-18 15:25:25 -07002329 private void handleAsyncChannelHalfConnect(Message msg) {
2330 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002331 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002332 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2333 if (VDBG) log("NetworkFactory connected");
2334 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002335 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002336 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002337 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002338 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002339 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002340 }
2341 } else {
2342 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002343 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002344 }
2345 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2346 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2347 if (VDBG) log("NetworkAgent connected");
2348 // A network agent has requested a connection. Establish the connection.
2349 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2350 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2351 } else {
2352 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002353 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002354 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002355 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002356 synchronized (mNetworkForNetId) {
2357 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002358 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002359 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002360 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002361 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002362 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002363 }
2364 }
2365 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002366
Robert Greenwalt7b816022014-04-18 15:25:25 -07002367 private void handleAsyncChannelDisconnected(Message msg) {
2368 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2369 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002370 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002371 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002372 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002373 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002374 // TODO - if we move the logic to the network agent (have them disconnect
2375 // because they lost all their requests or because their score isn't good)
2376 // then they would disconnect organically, report their new state and then
2377 // disconnect the channel.
2378 if (nai.networkInfo.isConnected()) {
2379 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2380 null, null);
2381 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002382 final boolean wasDefault = isDefaultNetwork(nai);
2383 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002384 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002385 // Log default network disconnection before required book-keeping.
2386 // Let rematchAllNetworksAndRequests() below record a new default network event
2387 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2388 // whose timestamps tell how long it takes to recover a default network.
2389 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002390 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002391 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002392 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2393 // by other networks that are already connected. Perhaps that can be done by
2394 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2395 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002396 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002397 mKeepaliveTracker.handleStopAllKeepalives(nai,
2398 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002399 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002400 mNetworkAgentInfos.remove(msg.replyTo);
2401 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002402 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002403 // Remove the NetworkAgent, but don't mark the netId as
2404 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002405 mNetworkForNetId.remove(nai.network.netId);
2406 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002407 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002408 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2409 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002410 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2411 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2412 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002413 sendUpdatedScoreToFactories(request, 0);
2414 }
2415 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002416 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002417 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002418 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002419 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002420 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002421 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002422 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002423 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002424 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002425 if (nai.created) {
2426 // Tell netd to clean up the configuration for this network
2427 // (routing rules, DNS, etc).
2428 // This may be slow as it requires a lot of netd shelling out to ip and
2429 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2430 // after we've rematched networks with requests which should make a potential
2431 // fallback network the default or requested a new network from the
2432 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2433 // long time.
2434 try {
2435 mNetd.removeNetwork(nai.network.netId);
2436 } catch (Exception e) {
2437 loge("Exception removing network: " + e);
2438 }
2439 }
2440 synchronized (mNetworkForNetId) {
2441 mNetIdInUse.delete(nai.network.netId);
2442 }
2443 } else {
2444 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2445 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002446 }
2447 }
2448
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002449 // If this method proves to be too slow then we can maintain a separate
2450 // pendingIntent => NetworkRequestInfo map.
2451 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2452 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2453 Intent intent = pendingIntent.getIntent();
2454 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2455 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2456 if (existingPendingIntent != null &&
2457 existingPendingIntent.getIntent().filterEquals(intent)) {
2458 return entry.getValue();
2459 }
2460 }
2461 return null;
2462 }
2463
2464 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2465 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2466
2467 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2468 if (existingRequest != null) { // remove the existing request.
2469 if (DBG) log("Replacing " + existingRequest.request + " with "
2470 + nri.request + " because their intents matched.");
2471 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2472 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002473 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002474 }
2475
Erik Klineda4bfa82015-04-30 12:58:40 +09002476 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002477 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002478 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002479 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002480 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002481 if (nri.request.networkCapabilities.hasSignalStrength() &&
2482 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2483 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002484 }
2485 }
2486 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002487 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002488 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002489 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002490 }
2491 }
2492
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002493 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2494 int callingUid) {
2495 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2496 if (nri != null) {
2497 handleReleaseNetworkRequest(nri.request, callingUid);
2498 }
2499 }
2500
Paul Jensen99364842014-12-09 11:43:45 -05002501 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002502 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2503 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002504 private boolean unneeded(NetworkAgentInfo nai) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002505 if (!nai.everConnected || nai.isVPN() ||
2506 nai.isLingering() || nai.numRequestNetworkRequests() > 0) {
2507 return false;
2508 }
Paul Jensene0988542015-06-25 15:30:08 -04002509 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2510 // If this Network is already the highest scoring Network for a request, or if
2511 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002512 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002513 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002514 // Note that this catches two important cases:
2515 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2516 // is currently satisfying the request. This is desirable when
2517 // cellular ends up validating but WiFi does not.
2518 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002519 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002520 // WiFi ends up validating and out scoring cellular.
2521 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2522 nai.getCurrentScoreAsValidated())) {
2523 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002524 }
2525 }
Paul Jensene0988542015-06-25 15:30:08 -04002526 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002527 }
2528
Erik Klineacdd6392016-07-07 16:50:58 +09002529 private NetworkRequestInfo getNriForAppRequest(
2530 NetworkRequest request, int callingUid, String requestedOperation) {
2531 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2532
Robert Greenwalt9258c642014-03-26 16:47:06 -07002533 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002534 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002535 log(String.format("UID %d attempted to %s for unowned request %s",
2536 callingUid, requestedOperation, nri));
2537 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002538 }
Erik Klineacdd6392016-07-07 16:50:58 +09002539 }
2540
2541 return nri;
2542 }
2543
2544 private void handleRequestCallbackUpdate(NetworkRequest request, int callingUid,
2545 String description, int callbackType) {
2546 final NetworkRequestInfo nri = getNriForAppRequest(request, callingUid, description);
2547 if (nri == null) return;
2548
2549 final NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2550 // The network that is satisfying this request may have changed since
2551 // the application requested the update.
2552 //
2553 // - If the request is no longer satisfied, don't send any updates.
2554 // - If the request is satisfied by a different network, it is the
2555 // caller's responsibility to check that the Network object in the
2556 // callback matches the network that was returned in the last
2557 // onAvailable() callback for this request.
2558 if (nai == null) return;
2559 callCallbackForRequest(nri, nai, callbackType, 0);
2560 }
2561
2562 private void handleRequestLinkProperties(NetworkRequest request, int callingUid) {
2563 handleRequestCallbackUpdate(request, callingUid,
2564 "request LinkProperties", ConnectivityManager.CALLBACK_IP_CHANGED);
2565 }
2566
2567 private void handleRequestNetworkCapabilities(NetworkRequest request, int callingUid) {
2568 handleRequestCallbackUpdate(request, callingUid,
2569 "request NetworkCapabilities", ConnectivityManager.CALLBACK_CAP_CHANGED);
2570 }
2571
2572 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2573 final NetworkRequestInfo nri = getNriForAppRequest(
2574 request, callingUid, "release NetworkRequest");
2575 if (nri == null) return;
2576
2577 if (VDBG || (DBG && nri.request.isRequest())) log("releasing " + request);
2578 nri.unlinkDeathRecipient();
2579 mNetworkRequests.remove(request);
2580 synchronized (mUidToNetworkRequestCount) {
2581 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2582 if (requests < 1) {
2583 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2584 nri.mUid);
2585 } else if (requests == 1) {
2586 mUidToNetworkRequestCount.removeAt(
2587 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2588 } else {
2589 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2590 }
2591 }
2592 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2593 if (nri.request.isRequest()) {
2594 boolean wasKept = false;
2595 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2596 if (nai != null) {
2597 nai.removeRequest(nri.request.requestId);
2598 if (VDBG) {
2599 log(" Removing from current network " + nai.name() +
2600 ", leaving " + nai.numNetworkRequests() + " requests.");
2601 }
2602 // If there are still lingered requests on this network, don't tear it down,
2603 // but resume lingering instead.
2604 updateLingerState(nai, SystemClock.elapsedRealtime());
2605 if (unneeded(nai)) {
2606 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2607 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002608 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002609 wasKept = true;
2610 }
2611 mNetworkForRequestId.remove(nri.request.requestId);
2612 }
2613
2614 // TODO: remove this code once we know that the Slog.wtf is never hit.
2615 //
2616 // Find all networks that are satisfying this request and remove the request
2617 // from their request lists.
2618 // TODO - it's my understanding that for a request there is only a single
2619 // network satisfying it, so this loop is wasteful
2620 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2621 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2622 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2623 otherNai.name() + ", but mNetworkAgentInfos says " +
2624 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002625 }
2626 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002627
Erik Klineacdd6392016-07-07 16:50:58 +09002628 // Maintain the illusion. When this request arrived, we might have pretended
2629 // that a network connected to serve it, even though the network was already
2630 // connected. Now that this request has gone away, we might have to pretend
2631 // that the network disconnected. LegacyTypeTracker will generate that
2632 // phantom disconnect for this type.
2633 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2634 boolean doRemove = true;
2635 if (wasKept) {
2636 // check if any of the remaining requests for this network are for the
2637 // same legacy type - if so, don't remove the nai
2638 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2639 NetworkRequest otherRequest = nai.requestAt(i);
2640 if (otherRequest.legacyType == nri.request.legacyType &&
2641 otherRequest.isRequest()) {
2642 if (DBG) log(" still have other legacy request - leaving");
2643 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002644 }
2645 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002646 }
2647
Erik Klineacdd6392016-07-07 16:50:58 +09002648 if (doRemove) {
2649 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002650 }
2651 }
Erik Klineacdd6392016-07-07 16:50:58 +09002652
2653 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2654 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2655 nri.request);
2656 }
2657 } else {
2658 // listens don't have a singular affectedNetwork. Check all networks to see
2659 // if this listen request applies and remove it.
2660 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2661 nai.removeRequest(nri.request.requestId);
2662 if (nri.request.networkCapabilities.hasSignalStrength() &&
2663 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2664 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2665 }
2666 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002667 }
Erik Klineacdd6392016-07-07 16:50:58 +09002668 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002669 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002670
Lorenzo Colitti18660282016-07-04 12:55:44 +09002671 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002672 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2673 enforceConnectivityInternalPermission();
2674 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2675 accept ? 1 : 0, always ? 1: 0, network));
2676 }
2677
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002678 @Override
2679 public void setAvoidUnvalidated(Network network) {
2680 enforceConnectivityInternalPermission();
2681 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2682 }
2683
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002684 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2685 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2686 " accept=" + accept + " always=" + always);
2687
2688 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2689 if (nai == null) {
2690 // Nothing to do.
2691 return;
2692 }
2693
2694 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002695 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002696 return;
2697 }
2698
2699 if (!nai.networkMisc.explicitlySelected) {
2700 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2701 }
2702
2703 if (accept != nai.networkMisc.acceptUnvalidated) {
2704 int oldScore = nai.getCurrentScore();
2705 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002706 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002707 sendUpdatedScoreToFactories(nai);
2708 }
2709
2710 if (always) {
2711 nai.asyncChannel.sendMessage(
2712 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2713 }
2714
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002715 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002716 // Tell the NetworkAgent to not automatically reconnect to the network.
2717 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2718 // Teardown the nework.
2719 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002720 }
2721
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002722 }
2723
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002724 private void handleSetAvoidUnvalidated(Network network) {
2725 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2726 if (nai == null || nai.lastValidated) {
2727 // Nothing to do. The network either disconnected or revalidated.
2728 return;
2729 }
2730 if (!nai.avoidUnvalidated) {
2731 int oldScore = nai.getCurrentScore();
2732 nai.avoidUnvalidated = true;
2733 rematchAllNetworksAndRequests(nai, oldScore);
2734 sendUpdatedScoreToFactories(nai);
2735 }
2736 }
2737
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002738 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002739 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002740 mHandler.sendMessageDelayed(
2741 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2742 PROMPT_UNVALIDATED_DELAY_MS);
2743 }
2744
Hugo Benichic8e9e122016-09-14 23:23:08 +00002745 public boolean avoidBadWifi() {
Erik Kline065ab6e2016-10-02 18:02:14 +09002746 return mAvoidBadWifiTracker.currentValue();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002747 }
2748
Erik Kline065ab6e2016-10-02 18:02:14 +09002749 private void rematchForAvoidBadWifiUpdate() {
2750 rematchAllNetworksAndRequests(null, 0);
2751 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2752 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2753 sendUpdatedScoreToFactories(nai);
2754 }
2755 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002756 }
2757
Erik Kline065ab6e2016-10-02 18:02:14 +09002758 // TODO: Evaluate whether this is of interest to other consumers of
2759 // AvoidBadWifiTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002760 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Erik Kline065ab6e2016-10-02 18:02:14 +09002761 final boolean configRestrict = mAvoidBadWifiTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002762 if (!configRestrict) {
2763 pw.println("Bad Wi-Fi avoidance: unrestricted");
2764 return;
2765 }
2766
2767 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2768 pw.increaseIndent();
2769 pw.println("Config restrict: " + configRestrict);
2770
Erik Kline065ab6e2016-10-02 18:02:14 +09002771 final String value = mAvoidBadWifiTracker.getSettingsValue();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002772 String description;
2773 // Can't use a switch statement because strings are legal case labels, but null is not.
2774 if ("0".equals(value)) {
2775 description = "get stuck";
2776 } else if (value == null) {
2777 description = "prompt";
2778 } else if ("1".equals(value)) {
2779 description = "avoid";
2780 } else {
2781 description = value + " (?)";
2782 }
2783 pw.println("User setting: " + description);
2784 pw.println("Network overrides:");
2785 pw.increaseIndent();
2786 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2787 if (nai.avoidUnvalidated) {
2788 pw.println(nai.name());
2789 }
2790 }
2791 pw.decreaseIndent();
2792 pw.decreaseIndent();
2793 }
2794
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002795 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2796 final String action;
2797 switch (type) {
2798 case NO_INTERNET:
2799 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2800 break;
2801 case LOST_INTERNET:
2802 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2803 break;
2804 default:
2805 Slog.wtf(TAG, "Unknown notification type " + type);
2806 return;
2807 }
2808
2809 Intent intent = new Intent(action);
2810 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2811 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2812 intent.setClassName("com.android.settings",
2813 "com.android.settings.wifi.WifiNoInternetDialog");
2814
2815 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2816 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2817 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2818 }
2819
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002820 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002821 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002822 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2823
2824 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2825 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002826 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002827 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002828 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2829 return;
2830 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002831 showValidationNotification(nai, NotificationType.NO_INTERNET);
2832 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002833
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002834 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2835 NetworkCapabilities nc = nai.networkCapabilities;
2836 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002837
Erik Kline065ab6e2016-10-02 18:02:14 +09002838 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
2839 mAvoidBadWifiTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002840 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2841 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002842 }
2843
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002844 private class InternalHandler extends Handler {
2845 public InternalHandler(Looper looper) {
2846 super(looper);
2847 }
2848
2849 @Override
2850 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002851 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002852 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002853 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002854 String causedBy = null;
2855 synchronized (ConnectivityService.this) {
2856 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2857 mNetTransitionWakeLock.isHeld()) {
2858 mNetTransitionWakeLock.release();
2859 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002860 } else {
2861 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002862 }
2863 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002864 if (VDBG) {
2865 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2866 log("Failed to find a new network - expiring NetTransition Wakelock");
2867 } else {
2868 log("NetTransition Wakelock (" +
2869 (causedBy == null ? "unknown" : causedBy) +
2870 " cleared because we found a replacement network");
2871 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002872 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002873 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002874 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002875 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002876 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002877 break;
2878 }
Jason Monkdecd2952013-10-10 14:02:51 -04002879 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002880 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002881 break;
2882 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002883 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002884 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2885 break;
2886 }
2887 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2888 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002889 break;
2890 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002891 case EVENT_REGISTER_NETWORK_AGENT: {
2892 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2893 break;
2894 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002895 case EVENT_REGISTER_NETWORK_REQUEST:
2896 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002897 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002898 break;
2899 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002900 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2901 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002902 handleRegisterNetworkRequestWithIntent(msg);
2903 break;
2904 }
2905 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2906 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2907 break;
2908 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002909 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002910 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002911 break;
2912 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002913 case EVENT_SET_ACCEPT_UNVALIDATED: {
2914 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2915 break;
2916 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002917 case EVENT_SET_AVOID_UNVALIDATED: {
2918 handleSetAvoidUnvalidated((Network) msg.obj);
2919 break;
2920 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002921 case EVENT_PROMPT_UNVALIDATED: {
2922 handlePromptUnvalidated((Network) msg.obj);
2923 break;
2924 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002925 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2926 handleMobileDataAlwaysOn();
2927 break;
2928 }
Erik Klineacdd6392016-07-07 16:50:58 +09002929 case EVENT_REQUEST_LINKPROPERTIES:
2930 handleRequestLinkProperties((NetworkRequest) msg.obj, msg.arg1);
2931 break;
2932 case EVENT_REQUEST_NETCAPABILITIES:
2933 handleRequestNetworkCapabilities((NetworkRequest) msg.obj, msg.arg1);
2934 break;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002935 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2936 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2937 mKeepaliveTracker.handleStartKeepalive(msg);
2938 break;
2939 }
2940 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2941 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2942 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2943 int slot = msg.arg1;
2944 int reason = msg.arg2;
2945 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2946 break;
2947 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002948 case EVENT_SYSTEM_READY: {
2949 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2950 nai.networkMonitor.systemReady = true;
2951 }
2952 break;
2953 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002954 }
2955 }
2956 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002957
2958 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002959 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002960 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002961 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002962 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002963 final int status = mTethering.tether(iface);
2964 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2965 try {
2966 mPolicyManager.onTetheringChanged(iface, true);
2967 } catch (RemoteException e) {
2968 }
2969 }
2970 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002971 } else {
2972 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2973 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002974 }
2975
2976 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002977 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002978 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002979 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002980
2981 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002982 final int status = mTethering.untether(iface);
2983 if (status == ConnectivityManager.TETHER_ERROR_NO_ERROR) {
2984 try {
2985 mPolicyManager.onTetheringChanged(iface, false);
2986 } catch (RemoteException e) {
2987 }
2988 }
2989 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002990 } else {
2991 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2992 }
2993 }
2994
2995 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002996 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002997 public int getLastTetherError(String iface) {
2998 enforceTetherAccessPermission();
2999
3000 if (isTetheringSupported()) {
3001 return mTethering.getLastTetherError(iface);
3002 } else {
3003 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3004 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003005 }
3006
3007 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003008 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003009 public String[] getTetherableUsbRegexs() {
3010 enforceTetherAccessPermission();
3011 if (isTetheringSupported()) {
3012 return mTethering.getTetherableUsbRegexs();
3013 } else {
3014 return new String[0];
3015 }
3016 }
3017
Lorenzo Colitti18660282016-07-04 12:55:44 +09003018 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003019 public String[] getTetherableWifiRegexs() {
3020 enforceTetherAccessPermission();
3021 if (isTetheringSupported()) {
3022 return mTethering.getTetherableWifiRegexs();
3023 } else {
3024 return new String[0];
3025 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003026 }
3027
Lorenzo Colitti18660282016-07-04 12:55:44 +09003028 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003029 public String[] getTetherableBluetoothRegexs() {
3030 enforceTetherAccessPermission();
3031 if (isTetheringSupported()) {
3032 return mTethering.getTetherableBluetoothRegexs();
3033 } else {
3034 return new String[0];
3035 }
3036 }
3037
Lorenzo Colitti18660282016-07-04 12:55:44 +09003038 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003039 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07003040 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003041 if (isTetheringSupported()) {
3042 return mTethering.setUsbTethering(enable);
3043 } else {
3044 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3045 }
3046 }
3047
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003048 // TODO - move iface listing, queries, etc to new module
3049 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003050 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003051 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003052 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003053 return mTethering.getTetherableIfaces();
3054 }
3055
Lorenzo Colitti18660282016-07-04 12:55:44 +09003056 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003057 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003058 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003059 return mTethering.getTetheredIfaces();
3060 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003061
Lorenzo Colitti18660282016-07-04 12:55:44 +09003062 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003063 public String[] getTetheringErroredIfaces() {
3064 enforceTetherAccessPermission();
3065 return mTethering.getErroredIfaces();
3066 }
3067
Lorenzo Colitti18660282016-07-04 12:55:44 +09003068 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003069 public String[] getTetheredDhcpRanges() {
3070 enforceConnectivityInternalPermission();
3071 return mTethering.getTetheredDhcpRanges();
3072 }
3073
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003074 // if ro.tether.denied = true we default to no tethering
3075 // gservices could set the secure setting to 1 though to enable it on a build where it
3076 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003077 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003078 public boolean isTetheringSupported() {
3079 enforceTetherAccessPermission();
3080 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07003081 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003082 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
3083 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003084 return tetherEnabledInSettings && mUserManager.isAdminUser() &&
3085 ((mTethering.getTetherableUsbRegexs().length != 0 ||
Robert Greenwaltc13368b2013-07-18 14:24:42 -07003086 mTethering.getTetherableWifiRegexs().length != 0 ||
3087 mTethering.getTetherableBluetoothRegexs().length != 0) &&
3088 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003089 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003090
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003091 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003092 public void startTethering(int type, ResultReceiver receiver,
3093 boolean showProvisioningUi) {
3094 ConnectivityManager.enforceTetherChangePermission(mContext);
3095 if (!isTetheringSupported()) {
3096 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3097 return;
3098 }
3099 mTethering.startTethering(type, receiver, showProvisioningUi);
3100 }
3101
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003102 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003103 public void stopTethering(int type) {
3104 ConnectivityManager.enforceTetherChangePermission(mContext);
3105 mTethering.stopTethering(type);
3106 }
3107
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003108 // Called when we lose the default network and have no replacement yet.
3109 // This will automatically be cleared after X seconds or a new default network
3110 // becomes CONNECTED, whichever happens first. The timer is started by the
3111 // first caller and not restarted by subsequent callers.
3112 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003113 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003114 synchronized (this) {
3115 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003116 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003117 mNetTransitionWakeLock.acquire();
3118 mNetTransitionWakeLockCausedBy = forWhom;
3119 }
3120 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003121 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003122 mNetTransitionWakeLockTimeout);
3123 return;
3124 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003125
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003126 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003127 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003128 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003129 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003130 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003131 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003132 }
3133
Lorenzo Colitti18660282016-07-04 12:55:44 +09003134 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003135 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003136 enforceAccessPermission();
3137 enforceInternetPermission();
3138
Paul Jensenbfd17b72015-04-07 12:43:13 -04003139 NetworkAgentInfo nai;
3140 if (network == null) {
3141 nai = getDefaultNetwork();
3142 } else {
3143 nai = getNetworkAgentInfoForNetwork(network);
3144 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003145 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3146 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3147 return;
3148 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003149 // Revalidate if the app report does not match our current validated state.
3150 if (hasConnectivity == nai.lastValidated) return;
3151 final int uid = Binder.getCallingUid();
3152 if (DBG) {
3153 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3154 ") by " + uid);
3155 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003156 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003157 // Validating a network that has not yet connected could result in a call to
3158 // rematchNetworkAndRequests() which is not meant to work on such networks.
3159 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003160
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003161 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003162
3163 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3164 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003165 }
3166
Paul Jensencee9b512015-05-06 07:32:40 -04003167 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003168 // this information is already available as a world read/writable jvm property
3169 // so this API change wouldn't have a benifit. It also breaks the passing
3170 // of proxy info to all the JVMs.
3171 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003172 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003173 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003174 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3175 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003176 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003177 }
3178
Lorenzo Colitti18660282016-07-04 12:55:44 +09003179 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003180 public ProxyInfo getProxyForNetwork(Network network) {
3181 if (network == null) return getDefaultProxy();
3182 final ProxyInfo globalProxy = getGlobalProxy();
3183 if (globalProxy != null) return globalProxy;
3184 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3185 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3186 // caller may not have.
3187 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3188 if (nai == null) return null;
3189 synchronized (nai) {
3190 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3191 if (proxyInfo == null) return null;
3192 return new ProxyInfo(proxyInfo);
3193 }
3194 }
3195
Paul Jensene0bef712014-12-10 15:12:18 -05003196 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3197 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3198 // proxy is null then there is no proxy in place).
3199 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3200 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3201 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3202 proxy = null;
3203 }
3204 return proxy;
3205 }
3206
3207 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3208 // better for determining if a new proxy broadcast is necessary:
3209 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3210 // avoid unnecessary broadcasts.
3211 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3212 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3213 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3214 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3215 // all set.
3216 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3217 a = canonicalizeProxyInfo(a);
3218 b = canonicalizeProxyInfo(b);
3219 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3220 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3221 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3222 }
3223
Jason Monk207900c2014-04-25 15:00:09 -04003224 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003225 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003226
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003227 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003228 if (proxyProperties == mGlobalProxy) return;
3229 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3230 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3231
3232 String host = "";
3233 int port = 0;
3234 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003235 String pacFileUrl = "";
3236 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003237 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003238 if (!proxyProperties.isValid()) {
3239 if (DBG)
3240 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3241 return;
3242 }
Jason Monk207900c2014-04-25 15:00:09 -04003243 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003244 host = mGlobalProxy.getHost();
3245 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003246 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003247 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003248 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003249 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003250 } else {
3251 mGlobalProxy = null;
3252 }
3253 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003254 final long token = Binder.clearCallingIdentity();
3255 try {
3256 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3257 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3258 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3259 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003260 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003261 } finally {
3262 Binder.restoreCallingIdentity(token);
3263 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003264
Jason Monkcf0f97a2014-10-02 15:39:38 -04003265 if (mGlobalProxy == null) {
3266 proxyProperties = mDefaultProxy;
3267 }
3268 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003269 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003270 }
3271
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003272 private void loadGlobalProxy() {
3273 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003274 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3275 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3276 String exclList = Settings.Global.getString(res,
3277 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003278 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3279 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003280 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003281 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003282 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003283 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003284 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003285 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003286 if (!proxyProperties.isValid()) {
3287 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3288 return;
3289 }
3290
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003291 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003292 mGlobalProxy = proxyProperties;
3293 }
3294 }
3295 }
3296
Jason Monk207900c2014-04-25 15:00:09 -04003297 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003298 // this information is already available as a world read/writable jvm property
3299 // so this API change wouldn't have a benifit. It also breaks the passing
3300 // of proxy info to all the JVMs.
3301 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003302 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003303 return mGlobalProxy;
3304 }
3305 }
3306
Jason Monk207900c2014-04-25 15:00:09 -04003307 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003308 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003309 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003310 proxy = null;
3311 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003312 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003313 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003314 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003315 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003316 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3317 return;
3318 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003319
3320 // This call could be coming from the PacManager, containing the port of the local
3321 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3322 // global (to get the correct local port), and send a broadcast.
3323 // TODO: Switch PacManager to have its own message to send back rather than
3324 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003325 if ((mGlobalProxy != null) && (proxy != null)
3326 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003327 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3328 mGlobalProxy = proxy;
3329 sendProxyBroadcast(mGlobalProxy);
3330 return;
3331 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003332 mDefaultProxy = proxy;
3333
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003334 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003335 if (!mDefaultProxyDisabled) {
3336 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003337 }
3338 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003339 }
3340
Paul Jensene0bef712014-12-10 15:12:18 -05003341 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3342 // This method gets called when any network changes proxy, but the broadcast only ever contains
3343 // the default proxy (even if it hasn't changed).
3344 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3345 // world where an app might be bound to a non-default network.
3346 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3347 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3348 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3349
3350 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3351 sendProxyBroadcast(getDefaultProxy());
3352 }
3353 }
3354
Robert Greenwalt434203a2010-10-11 16:00:27 -07003355 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003356 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3357 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003358 if (!TextUtils.isEmpty(proxy)) {
3359 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003360 if (data.length == 0) {
3361 return;
3362 }
3363
Robert Greenwalt434203a2010-10-11 16:00:27 -07003364 String proxyHost = data[0];
3365 int proxyPort = 8080;
3366 if (data.length > 1) {
3367 try {
3368 proxyPort = Integer.parseInt(data[1]);
3369 } catch (NumberFormatException e) {
3370 return;
3371 }
3372 }
Jason Monk207900c2014-04-25 15:00:09 -04003373 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003374 setGlobalProxy(p);
3375 }
3376 }
3377
Jason Monk207900c2014-04-25 15:00:09 -04003378 private void sendProxyBroadcast(ProxyInfo proxy) {
3379 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003380 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003381 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003382 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003383 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3384 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003385 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003386 final long ident = Binder.clearCallingIdentity();
3387 try {
3388 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3389 } finally {
3390 Binder.restoreCallingIdentity(ident);
3391 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003392 }
3393
3394 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003395 final private HashMap<Uri, Integer> mUriEventMap;
3396 final private Context mContext;
3397 final private Handler mHandler;
3398
3399 SettingsObserver(Context context, Handler handler) {
3400 super(null);
3401 mUriEventMap = new HashMap<Uri, Integer>();
3402 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003403 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003404 }
3405
Erik Klineda4bfa82015-04-30 12:58:40 +09003406 void observe(Uri uri, int what) {
3407 mUriEventMap.put(uri, what);
3408 final ContentResolver resolver = mContext.getContentResolver();
3409 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003410 }
3411
3412 @Override
3413 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003414 Slog.wtf(TAG, "Should never be reached.");
3415 }
3416
3417 @Override
3418 public void onChange(boolean selfChange, Uri uri) {
3419 final Integer what = mUriEventMap.get(uri);
3420 if (what != null) {
3421 mHandler.obtainMessage(what.intValue()).sendToTarget();
3422 } else {
3423 loge("No matching event to send for URI=" + uri);
3424 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003425 }
3426 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003427
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003428 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003429 Slog.d(TAG, s);
3430 }
3431
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003432 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003433 Slog.e(TAG, s);
3434 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003435
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003436 private static <T> T checkNotNull(T value, String message) {
3437 if (value == null) {
3438 throw new NullPointerException(message);
3439 }
3440 return value;
3441 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003442
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003443 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003444 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003445 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3446 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3447 *
3448 * @param oldPackage Package name of the application which currently controls VPN, which will
3449 * be replaced. If there is no such application, this should should either be
3450 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3451 * @param newPackage Package name of the application which should gain control of VPN, or
3452 * {@code null} to disable.
3453 * @param userId User for whom to prepare the new VPN.
3454 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003455 * @hide
3456 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003457 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003458 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3459 int userId) {
3460 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003461 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003462
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003463 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003464 Vpn vpn = mVpns.get(userId);
3465 if (vpn != null) {
3466 return vpn.prepare(oldPackage, newPackage);
3467 } else {
3468 return false;
3469 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003470 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003471 }
3472
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003473 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003474 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3475 * This method is used by system-privileged apps.
3476 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3477 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3478 *
3479 * @param packageName The package for which authorization state should change.
3480 * @param userId User for whom {@code packageName} is installed.
3481 * @param authorized {@code true} if this app should be able to start a VPN connection without
3482 * explicit user approval, {@code false} if not.
3483 *
Jeff Davidson05542602014-08-11 14:07:27 -07003484 * @hide
3485 */
3486 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003487 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3488 enforceCrossUserPermission(userId);
3489
Jeff Davidson05542602014-08-11 14:07:27 -07003490 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003491 Vpn vpn = mVpns.get(userId);
3492 if (vpn != null) {
3493 vpn.setPackageAuthorization(packageName, authorized);
3494 }
Jeff Davidson05542602014-08-11 14:07:27 -07003495 }
3496 }
3497
3498 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003499 * Configure a TUN interface and return its file descriptor. Parameters
3500 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003501 * and not available in ConnectivityManager. Permissions are checked in
3502 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003503 * @hide
3504 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003505 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003506 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003507 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003508 int user = UserHandle.getUserId(Binder.getCallingUid());
3509 synchronized(mVpns) {
3510 return mVpns.get(user).establish(config);
3511 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003512 }
3513
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003514 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003515 * Start legacy VPN, controlling native daemons as needed. Creates a
3516 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003517 */
3518 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003519 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003520 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003521 final LinkProperties egress = getActiveLinkProperties();
3522 if (egress == null) {
3523 throw new IllegalStateException("Missing active network connection");
3524 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003525 int user = UserHandle.getUserId(Binder.getCallingUid());
3526 synchronized(mVpns) {
3527 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3528 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003529 }
3530
3531 /**
3532 * Return the information of the ongoing legacy VPN. This method is used
3533 * by VpnSettings and not available in ConnectivityManager. Permissions
3534 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003535 */
3536 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003537 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3538 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003539
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003540 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003541 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003542 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003543 }
3544
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003545 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003546 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3547 * and not available in ConnectivityManager.
3548 */
3549 @Override
3550 public VpnInfo[] getAllVpnInfo() {
3551 enforceConnectivityInternalPermission();
3552 if (mLockdownEnabled) {
3553 return new VpnInfo[0];
3554 }
3555
3556 synchronized(mVpns) {
3557 List<VpnInfo> infoList = new ArrayList<>();
3558 for (int i = 0; i < mVpns.size(); i++) {
3559 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3560 if (info != null) {
3561 infoList.add(info);
3562 }
3563 }
3564 return infoList.toArray(new VpnInfo[infoList.size()]);
3565 }
3566 }
3567
3568 /**
3569 * @return VPN information for accounting, or null if we can't retrieve all required
3570 * information, e.g primary underlying iface.
3571 */
3572 @Nullable
3573 private VpnInfo createVpnInfo(Vpn vpn) {
3574 VpnInfo info = vpn.getVpnInfo();
3575 if (info == null) {
3576 return null;
3577 }
3578 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3579 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3580 // the underlyingNetworks list.
3581 if (underlyingNetworks == null) {
3582 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3583 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3584 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3585 }
3586 } else if (underlyingNetworks.length > 0) {
3587 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3588 if (linkProperties != null) {
3589 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3590 }
3591 }
3592 return info.primaryUnderlyingIface == null ? null : info;
3593 }
3594
3595 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003596 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3597 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003598 * Permissions are checked in Vpn class.
3599 * @hide
3600 */
3601 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003602 public VpnConfig getVpnConfig(int userId) {
3603 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003604 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003605 Vpn vpn = mVpns.get(userId);
3606 if (vpn != null) {
3607 return vpn.getVpnConfig();
3608 } else {
3609 return null;
3610 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003611 }
3612 }
3613
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003614 @Override
3615 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003616 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3617 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3618 return false;
3619 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003620
3621 // Tear down existing lockdown if profile was removed
3622 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3623 if (mLockdownEnabled) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003624 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3625 final VpnProfile profile = VpnProfile.decode(
3626 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003627 if (profile == null) {
3628 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3629 setLockdownTracker(null);
3630 return true;
3631 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003632 int user = UserHandle.getUserId(Binder.getCallingUid());
3633 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003634 Vpn vpn = mVpns.get(user);
3635 if (vpn == null) {
3636 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3637 return false;
3638 }
3639 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003640 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003641 } else {
3642 setLockdownTracker(null);
3643 }
3644
3645 return true;
3646 }
3647
3648 /**
3649 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3650 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3651 */
3652 private void setLockdownTracker(LockdownVpnTracker tracker) {
3653 // Shutdown any existing tracker
3654 final LockdownVpnTracker existing = mLockdownTracker;
3655 mLockdownTracker = null;
3656 if (existing != null) {
3657 existing.shutdown();
3658 }
3659
3660 try {
3661 if (tracker != null) {
3662 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003663 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003664 mLockdownTracker = tracker;
3665 mLockdownTracker.init();
3666 } else {
3667 mNetd.setFirewallEnabled(false);
3668 }
3669 } catch (RemoteException e) {
3670 // ignored; NMS lives inside system_server
3671 }
3672 }
3673
3674 private void throwIfLockdownEnabled() {
3675 if (mLockdownEnabled) {
3676 throw new IllegalStateException("Unavailable in lockdown mode");
3677 }
3678 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003679
Robin Lee244ce8e2016-01-05 18:03:46 +00003680 /**
Robin Lee17e61832016-05-09 13:46:28 +01003681 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3682 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003683 *
Robin Lee17e61832016-05-09 13:46:28 +01003684 * @return {@code true} if the service was started, the service was already connected, or there
3685 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003686 */
Robin Lee17e61832016-05-09 13:46:28 +01003687 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003688 synchronized (mVpns) {
3689 Vpn vpn = mVpns.get(userId);
3690 if (vpn == null) {
3691 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3692 // exists already.
3693 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3694 return false;
3695 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003696
Robin Lee812800c2016-05-13 15:38:08 +01003697 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003698 }
3699 }
3700
3701 @Override
Robin Leedc679712016-05-03 13:23:03 +01003702 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003703 enforceConnectivityInternalPermission();
3704 enforceCrossUserPermission(userId);
3705
3706 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3707 if (LockdownVpnTracker.isEnabled()) {
3708 return false;
3709 }
3710
Robin Lee244ce8e2016-01-05 18:03:46 +00003711 synchronized (mVpns) {
3712 Vpn vpn = mVpns.get(userId);
3713 if (vpn == null) {
3714 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3715 return false;
3716 }
Robin Lee17e61832016-05-09 13:46:28 +01003717 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003718 return false;
3719 }
Robin Lee17e61832016-05-09 13:46:28 +01003720 if (!startAlwaysOnVpn(userId)) {
3721 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003722 return false;
3723 }
Robin Lee17e61832016-05-09 13:46:28 +01003724
Robin Lee812800c2016-05-13 15:38:08 +01003725 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003726 }
3727 return true;
3728 }
3729
3730 @Override
3731 public String getAlwaysOnVpnPackage(int userId) {
3732 enforceConnectivityInternalPermission();
3733 enforceCrossUserPermission(userId);
3734
3735 synchronized (mVpns) {
3736 Vpn vpn = mVpns.get(userId);
3737 if (vpn == null) {
3738 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3739 return null;
3740 }
3741 return vpn.getAlwaysOnPackage();
3742 }
3743 }
3744
Wink Savilleab9321d2013-06-29 21:10:57 -07003745 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003746 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003747 // TODO: Remove? Any reason to trigger a provisioning check?
3748 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003749 }
3750
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003751 /** Location to an updatable file listing carrier provisioning urls.
3752 * An example:
3753 *
3754 * <?xml version="1.0" encoding="utf-8"?>
3755 * <provisioningUrls>
3756 * <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 -07003757 * </provisioningUrls>
3758 */
3759 private static final String PROVISIONING_URL_PATH =
3760 "/data/misc/radio/provisioning_urls.xml";
3761 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003762
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003763 /** XML tag for root element. */
3764 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3765 /** XML tag for individual url */
3766 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003767 /** XML attribute for mcc */
3768 private static final String ATTR_MCC = "mcc";
3769 /** XML attribute for mnc */
3770 private static final String ATTR_MNC = "mnc";
3771
Paul Jensen434dde82015-06-11 09:43:30 -04003772 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003773 FileReader fileReader = null;
3774 XmlPullParser parser = null;
3775 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003776
3777 try {
3778 fileReader = new FileReader(mProvisioningUrlFile);
3779 parser = Xml.newPullParser();
3780 parser.setInput(fileReader);
3781 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3782
3783 while (true) {
3784 XmlUtils.nextElement(parser);
3785
3786 String element = parser.getName();
3787 if (element == null) break;
3788
Paul Jensen434dde82015-06-11 09:43:30 -04003789 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003790 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3791 try {
3792 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3793 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3794 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3795 parser.next();
3796 if (parser.getEventType() == XmlPullParser.TEXT) {
3797 return parser.getText();
3798 }
3799 }
3800 }
3801 } catch (NumberFormatException e) {
3802 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3803 }
3804 }
3805 }
3806 return null;
3807 } catch (FileNotFoundException e) {
3808 loge("Carrier Provisioning Urls file not found");
3809 } catch (XmlPullParserException e) {
3810 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3811 } catch (IOException e) {
3812 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3813 } finally {
3814 if (fileReader != null) {
3815 try {
3816 fileReader.close();
3817 } catch (IOException e) {}
3818 }
3819 }
3820 return null;
3821 }
3822
Wink Saville42d4f082013-07-20 20:31:59 -07003823 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003824 public String getMobileProvisioningUrl() {
3825 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003826 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003827 if (TextUtils.isEmpty(url)) {
3828 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003829 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003830 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003831 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003832 }
Wink Saville8cf35602013-07-10 23:00:07 -07003833 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003834 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003835 String phoneNumber = mTelephonyManager.getLine1Number();
3836 if (TextUtils.isEmpty(phoneNumber)) {
3837 phoneNumber = "0000000000";
3838 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003839 url = String.format(url,
3840 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3841 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003842 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003843 }
3844
Wink Savilleab9321d2013-06-29 21:10:57 -07003845 return url;
3846 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003847
Wink Saville948282b2013-08-29 08:55:16 -07003848 @Override
3849 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003850 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003851 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003852 final long ident = Binder.clearCallingIdentity();
3853 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003854 // Concatenate the range of types onto the range of NetIDs.
3855 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3856 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003857 } finally {
3858 Binder.restoreCallingIdentity(ident);
3859 }
Wink Saville948282b2013-08-29 08:55:16 -07003860 }
Wink Saville7788c612013-08-29 14:57:08 -07003861
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003862 @Override
3863 public void setAirplaneMode(boolean enable) {
3864 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003865 final long ident = Binder.clearCallingIdentity();
3866 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003867 final ContentResolver cr = mContext.getContentResolver();
3868 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3869 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3870 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003871 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003872 } finally {
3873 Binder.restoreCallingIdentity(ident);
3874 }
3875 }
3876
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003877 private void onUserStart(int userId) {
3878 synchronized(mVpns) {
3879 Vpn userVpn = mVpns.get(userId);
3880 if (userVpn != null) {
3881 loge("Starting user already has a VPN");
3882 return;
3883 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003884 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003885 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003886
3887 final ContentResolver cr = mContext.getContentResolver();
3888 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3889 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3890 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3891 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3892 if (alwaysOnPackage != null) {
3893 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3894 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003895 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003896 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3897 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003898 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003899 }
3900
3901 private void onUserStop(int userId) {
3902 synchronized(mVpns) {
3903 Vpn userVpn = mVpns.get(userId);
3904 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003905 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003906 return;
3907 }
Robin Lee17e61832016-05-09 13:46:28 +01003908 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003909 mVpns.delete(userId);
3910 }
3911 }
3912
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003913 private void onUserAdded(int userId) {
3914 synchronized(mVpns) {
3915 final int vpnsSize = mVpns.size();
3916 for (int i = 0; i < vpnsSize; i++) {
3917 Vpn vpn = mVpns.valueAt(i);
3918 vpn.onUserAdded(userId);
3919 }
3920 }
3921 }
3922
3923 private void onUserRemoved(int userId) {
3924 synchronized(mVpns) {
3925 final int vpnsSize = mVpns.size();
3926 for (int i = 0; i < vpnsSize; i++) {
3927 Vpn vpn = mVpns.valueAt(i);
3928 vpn.onUserRemoved(userId);
3929 }
3930 }
3931 }
3932
Robin Lee89e7a692016-02-29 14:38:17 +00003933 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003934 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3935 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3936 updateLockdownVpn();
3937 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003938 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003939 }
3940 }
3941
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003942 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3943 @Override
3944 public void onReceive(Context context, Intent intent) {
3945 final String action = intent.getAction();
3946 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3947 if (userId == UserHandle.USER_NULL) return;
3948
Robin Lee323f29d2016-05-04 16:38:06 +01003949 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003950 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003951 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003952 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003953 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3954 onUserAdded(userId);
3955 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3956 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003957 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3958 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003959 }
3960 }
3961 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003962
Robert Greenwalta67be032014-05-16 15:49:14 -07003963 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3964 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003965 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3966 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003967
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003968 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3969 // Map from UID to number of NetworkRequests that UID has filed.
3970 @GuardedBy("mUidToNetworkRequestCount")
3971 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3972
Robert Greenwalta67be032014-05-16 15:49:14 -07003973 private static class NetworkFactoryInfo {
3974 public final String name;
3975 public final Messenger messenger;
3976 public final AsyncChannel asyncChannel;
3977
3978 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3979 this.name = name;
3980 this.messenger = messenger;
3981 this.asyncChannel = asyncChannel;
3982 }
3983 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003984
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003985 private void ensureNetworkRequestHasType(NetworkRequest request) {
3986 if (request.type == NetworkRequest.Type.NONE) {
3987 throw new IllegalArgumentException(
3988 "All NetworkRequests in ConnectivityService must have a type");
3989 }
3990 }
3991
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003992 /**
3993 * Tracks info about the requester.
3994 * Also used to notice when the calling process dies so we can self-expire
3995 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003996 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003997 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003998 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003999 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004000 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004001 final int mPid;
4002 final int mUid;
4003 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004004
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004005 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004006 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004007 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004008 mPendingIntent = pi;
4009 messenger = null;
4010 mBinder = null;
4011 mPid = getCallingPid();
4012 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004013 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004014 }
4015
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004016 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004017 super();
4018 messenger = m;
4019 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004020 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004021 mBinder = binder;
4022 mPid = getCallingPid();
4023 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004024 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004025 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004026
4027 try {
4028 mBinder.linkToDeath(this, 0);
4029 } catch (RemoteException e) {
4030 binderDied();
4031 }
4032 }
4033
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004034 private void enforceRequestCountLimit() {
4035 synchronized (mUidToNetworkRequestCount) {
4036 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4037 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
4038 throw new IllegalArgumentException("Too many NetworkRequests filed");
4039 }
4040 mUidToNetworkRequestCount.put(mUid, networkRequests);
4041 }
4042 }
4043
Robert Greenwalt9258c642014-03-26 16:47:06 -07004044 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004045 if (mBinder != null) {
4046 mBinder.unlinkToDeath(this, 0);
4047 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004048 }
4049
4050 public void binderDied() {
4051 log("ConnectivityService NetworkRequestInfo binderDied(" +
4052 request + ", " + mBinder + ")");
4053 releaseNetworkRequest(request);
4054 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004055
4056 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004057 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004058 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004059 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 }
4061
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004062 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4063 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4064 if (badCapability != null) {
4065 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004066 }
4067 }
4068
Erik Kline9d598e12015-07-13 16:37:51 +09004069 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004070 final SortedSet<Integer> thresholds = new TreeSet();
4071 synchronized (nai) {
4072 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4073 if (nri.request.networkCapabilities.hasSignalStrength() &&
4074 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4075 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4076 }
4077 }
4078 }
Erik Kline9d598e12015-07-13 16:37:51 +09004079 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004080 }
4081
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004082 private void updateSignalStrengthThresholds(
4083 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4084 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004085 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004086 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4087
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004088 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004089 String detail;
4090 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4091 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4092 } else {
4093 detail = reason;
4094 }
4095 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4096 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4097 }
4098
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004099 nai.asyncChannel.sendMessage(
4100 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004101 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004102 }
4103
Robert Greenwalt9258c642014-03-26 16:47:06 -07004104 @Override
4105 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004106 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004107 final NetworkRequest.Type type = (networkCapabilities == null)
4108 ? NetworkRequest.Type.TRACK_DEFAULT
4109 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004110 // If the requested networkCapabilities is null, take them instead from
4111 // the default network request. This allows callers to keep track of
4112 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004113 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004114 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4115 enforceAccessPermission();
4116 } else {
4117 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4118 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004119 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4120 // of the app when the request is filed, but we never change the request if the app
4121 // changes network state. http://b/29964605
4122 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004123 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004124 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004125
Robert Greenwalt6078b502014-06-11 16:05:07 -07004126 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004127 throw new IllegalArgumentException("Bad timeout specified");
4128 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004129
Etan Cohenddb9ef02015-11-18 10:56:15 -08004130 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4131 .equals(networkCapabilities.getNetworkSpecifier())) {
4132 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4133 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4134 }
4135
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004136 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004137 nextNetworkRequestId(), type);
4138 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004139 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004140
4141 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004142 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004143 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004144 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004145 }
4146 return networkRequest;
4147 }
4148
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004149 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004150 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004151 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004152 } else {
4153 enforceChangePermission();
4154 }
4155 }
4156
fenglub15e72b2015-03-20 11:29:56 -07004157 @Override
fengludb571472015-04-21 17:12:05 -07004158 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004159 enforceAccessPermission();
4160 NetworkAgentInfo nai = null;
4161 if (network == null) {
4162 return false;
4163 }
4164 synchronized (mNetworkForNetId) {
4165 nai = mNetworkForNetId.get(network.netId);
4166 }
4167 if (nai != null) {
4168 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4169 return true;
4170 }
4171 return false;
4172 }
4173
Felipe Lemeee27cab2016-06-20 16:36:29 -07004174 private boolean isSystem(int uid) {
4175 return uid < Process.FIRST_APPLICATION_UID;
4176 }
fenglub15e72b2015-03-20 11:29:56 -07004177
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004178 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004179 final int uid = Binder.getCallingUid();
4180 if (isSystem(uid)) {
4181 return;
4182 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004183 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004184 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004185 final int uidRules;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004186 synchronized(mRulesLock) {
4187 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
4188 }
Felipe Lemea4aba6e2016-05-20 18:04:14 -07004189 if (mRestrictBackground && (uidRules & RULE_ALLOW_METERED) == 0
4190 && (uidRules & RULE_TEMPORARY_ALLOW_METERED) == 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004191 // we could silently fail or we can filter the available nets to only give
Felipe Lemed31a97f2016-05-06 14:53:50 -07004192 // them those they have access to. Chose the more useful option.
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09004193 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004194 }
4195 }
4196 }
4197
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198 @Override
4199 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4200 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004201 checkNotNull(operation, "PendingIntent cannot be null.");
4202 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4203 enforceNetworkRequestPermissions(networkCapabilities);
4204 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004205 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004206
4207 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004208 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4209 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004210 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004211 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4212 nri));
4213 return networkRequest;
4214 }
4215
Jeremy Joslin79294842014-12-03 17:15:28 -08004216 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4217 mHandler.sendMessageDelayed(
4218 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4219 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4220 }
4221
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004222 @Override
4223 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004224 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004225 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4226 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004227 }
4228
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004229 // In order to implement the compatibility measure for pre-M apps that call
4230 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4231 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4232 // This ensures it has permission to do so.
4233 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4234 if (nc == null) {
4235 return false;
4236 }
4237 int[] transportTypes = nc.getTransportTypes();
4238 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4239 return false;
4240 }
4241 try {
4242 mContext.enforceCallingOrSelfPermission(
4243 android.Manifest.permission.ACCESS_WIFI_STATE,
4244 "ConnectivityService");
4245 } catch (SecurityException e) {
4246 return false;
4247 }
4248 return true;
4249 }
4250
Robert Greenwalt9258c642014-03-26 16:47:06 -07004251 @Override
4252 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4253 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004254 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4255 enforceAccessPermission();
4256 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004257
Erik Kline7523eb32015-07-09 18:24:03 +09004258 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004259 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4260 NetworkRequest.Type.LISTEN);
4261 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004262 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004263
4264 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4265 return networkRequest;
4266 }
4267
4268 @Override
4269 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4270 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004271 checkNotNull(operation, "PendingIntent cannot be null.");
4272 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4273 enforceAccessPermission();
4274 }
4275
Erik Kline7523eb32015-07-09 18:24:03 +09004276 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004277 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4278 NetworkRequest.Type.LISTEN);
4279 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004280 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004281
4282 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004283 }
4284
4285 @Override
Erik Klineacdd6392016-07-07 16:50:58 +09004286 public void requestLinkProperties(NetworkRequest networkRequest) {
4287 ensureNetworkRequestHasType(networkRequest);
4288 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4289 mHandler.sendMessage(mHandler.obtainMessage(
4290 EVENT_REQUEST_LINKPROPERTIES, getCallingUid(), 0, networkRequest));
4291 }
4292
4293 @Override
4294 public void requestNetworkCapabilities(NetworkRequest networkRequest) {
4295 ensureNetworkRequestHasType(networkRequest);
4296 if (networkRequest.type == NetworkRequest.Type.LISTEN) return;
4297 mHandler.sendMessage(mHandler.obtainMessage(
4298 EVENT_REQUEST_NETCAPABILITIES, getCallingUid(), 0, networkRequest));
4299 }
4300
4301 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004302 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004303 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004304 mHandler.sendMessage(mHandler.obtainMessage(
4305 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004306 }
4307
4308 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004309 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004310 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004311 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4312 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004313 }
4314
Robert Greenwalta67be032014-05-16 15:49:14 -07004315 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004316 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004317 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4318 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4319 }
4320
4321 @Override
4322 public void unregisterNetworkFactory(Messenger messenger) {
4323 enforceConnectivityInternalPermission();
4324 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4325 }
4326
4327 private void handleUnregisterNetworkFactory(Messenger messenger) {
4328 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4329 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004330 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004331 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004332 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004333 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004334 }
4335
Robert Greenwalt7b816022014-04-18 15:25:25 -07004336 /**
4337 * NetworkAgentInfo supporting a request by requestId.
4338 * These have already been vetted (their Capabilities satisfy the request)
4339 * and the are the highest scored network available.
4340 * the are keyed off the Requests requestId.
4341 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004342 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004343 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4344 new SparseArray<NetworkAgentInfo>();
4345
Paul Jensen31a94f42015-02-13 14:18:39 -05004346 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4347 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004348 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4349 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004350 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4351 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4352 // there may not be a strict 1:1 correlation between the two.
4353 @GuardedBy("mNetworkForNetId")
4354 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004355
Robert Greenwalt7b816022014-04-18 15:25:25 -07004356 // NetworkAgentInfo keyed off its connecting messenger
4357 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004358 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004359 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4360 new HashMap<Messenger, NetworkAgentInfo>();
4361
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004362 @GuardedBy("mBlockedAppUids")
4363 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4364
Paul Jensen2c311d62014-11-17 12:34:51 -05004365 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004366 private final NetworkRequest mDefaultRequest;
4367
Erik Klineda4bfa82015-04-30 12:58:40 +09004368 // Request used to optionally keep mobile data active even when higher
4369 // priority networks like Wi-Fi are active.
4370 private final NetworkRequest mDefaultMobileDataRequest;
4371
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004372 private NetworkAgentInfo getDefaultNetwork() {
4373 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4374 }
4375
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004376 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004377 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004378 }
4379
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004380 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4381 return nri.request.requestId == mDefaultRequest.requestId;
4382 }
4383
Paul Jensen31a94f42015-02-13 14:18:39 -05004384 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004385 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004386 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004387 enforceConnectivityInternalPermission();
4388
Paul Jensen2c311d62014-11-17 12:34:51 -05004389 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4390 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004391 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004392 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4393 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004394 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004395 synchronized (this) {
4396 nai.networkMonitor.systemReady = mSystemReady;
4397 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004398 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4399 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004400 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004401 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004402 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004403 }
4404
4405 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4406 if (VDBG) log("Got NetworkAgent Messenger");
4407 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004408 synchronized (mNetworkForNetId) {
4409 mNetworkForNetId.put(na.network.netId, na);
4410 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004411 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4412 NetworkInfo networkInfo = na.networkInfo;
4413 na.networkInfo = null;
4414 updateNetworkInfo(na, networkInfo);
4415 }
4416
4417 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4418 LinkProperties newLp = networkAgent.linkProperties;
4419 int netId = networkAgent.network.netId;
4420
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004421 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4422 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004423 if (networkAgent.clatd != null) {
4424 networkAgent.clatd.fixupLinkProperties(oldLp);
4425 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004426
Paul Jensen992f2522014-04-28 10:33:11 -04004427 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004428 updateMtu(newLp, oldLp);
4429 // TODO - figure out what to do for clat
4430// for (LinkProperties lp : newLp.getStackedLinks()) {
4431// updateMtu(lp, null);
4432// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004433 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004434
Erik Kline94887872016-04-05 13:30:49 +09004435 updateRoutes(newLp, oldLp, netId);
4436 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004437
Paul Jensen3b759822014-05-13 11:44:01 -04004438 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004439 if (isDefaultNetwork(networkAgent)) {
4440 handleApplyDefaultProxy(newLp.getHttpProxy());
4441 } else {
4442 updateProxy(newLp, oldLp, networkAgent);
4443 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004444 // TODO - move this check to cover the whole function
4445 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004446 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004447 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4448 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004449
4450 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004451 }
4452
Lorenzo Colitti95439462014-10-09 13:44:48 +09004453 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4454 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4455 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004456
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004457 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004458 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4459 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004460 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004461 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004462 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004463 }
Paul Jensen992f2522014-04-28 10:33:11 -04004464
4465 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4466 CompareResult<String> interfaceDiff = new CompareResult<String>();
4467 if (oldLp != null) {
4468 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4469 } else if (newLp != null) {
4470 interfaceDiff.added = newLp.getAllInterfaceNames();
4471 }
4472 for (String iface : interfaceDiff.added) {
4473 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004474 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004475 mNetd.addInterfaceToNetwork(iface, netId);
4476 } catch (Exception e) {
4477 loge("Exception adding interface: " + e);
4478 }
4479 }
4480 for (String iface : interfaceDiff.removed) {
4481 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004482 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004483 mNetd.removeInterfaceFromNetwork(iface, netId);
4484 } catch (Exception e) {
4485 loge("Exception removing interface: " + e);
4486 }
4487 }
4488 }
4489
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004490 /**
4491 * Have netd update routes from oldLp to newLp.
4492 * @return true if routes changed between oldLp and newLp
4493 */
4494 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004495 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4496 if (oldLp != null) {
4497 routeDiff = oldLp.compareAllRoutes(newLp);
4498 } else if (newLp != null) {
4499 routeDiff.added = newLp.getAllRoutes();
4500 }
4501
4502 // add routes before removing old in case it helps with continuous connectivity
4503
4504 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4505 for (RouteInfo route : routeDiff.added) {
4506 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004507 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004508 try {
4509 mNetd.addRoute(netId, route);
4510 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004511 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4512 loge("Exception in addRoute for non-gateway: " + e);
4513 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004514 }
4515 }
4516 for (RouteInfo route : routeDiff.added) {
4517 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004518 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004519 try {
4520 mNetd.addRoute(netId, route);
4521 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004522 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4523 loge("Exception in addRoute for gateway: " + e);
4524 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525 }
4526 }
4527
4528 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004529 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004530 try {
4531 mNetd.removeRoute(netId, route);
4532 } catch (Exception e) {
4533 loge("Exception in removeRoute: " + e);
4534 }
4535 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004536 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004537 }
Erik Kline41368502015-06-17 13:19:54 +09004538
Erik Kline94887872016-04-05 13:30:49 +09004539 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4540 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4541 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 }
Erik Kline94887872016-04-05 13:30:49 +09004543
4544 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004545 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004546 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004547 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004548 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4549 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004550 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004551 }
4552 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4553 if (defaultNai != null && defaultNai.network.netId == netId) {
4554 setDefaultDnsSystemProperties(dnses);
4555 }
4556 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004557 }
4558
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004559 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4560 int last = 0;
4561 for (InetAddress dns : dnses) {
4562 ++last;
4563 String key = "net.dns" + last;
4564 String value = dns.getHostAddress();
4565 SystemProperties.set(key, value);
4566 }
4567 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4568 String key = "net.dns" + i;
4569 SystemProperties.set(key, "");
4570 }
4571 mNumDnsEntries = last;
4572 }
4573
Paul Jensen3d194ea2015-06-16 14:27:36 -04004574 /**
4575 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4576 * augmented with any stateful capabilities implied from {@code networkAgent}
4577 * (e.g., validated status and captive portal status).
4578 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004579 * @param oldScore score of the network before any of the changes that prompted us
4580 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004581 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004582 * @param networkCapabilities the new network capabilities.
4583 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004584 private void updateCapabilities(
4585 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004586 // Don't modify caller's NetworkCapabilities.
4587 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004588 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004589 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4590 } else {
4591 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4592 }
Paul Jensene0988542015-06-25 15:30:08 -04004593 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004594 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4595 } else {
4596 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4597 }
Paul Jensene0988542015-06-25 15:30:08 -04004598 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
Paul Jensen487ffe72015-07-24 15:57:11 -04004599 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4600 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4601 try {
4602 mNetd.setNetworkPermission(nai.network.netId,
4603 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4604 null : NetworkManagementService.PERMISSION_SYSTEM);
4605 } catch (RemoteException e) {
4606 loge("Exception in setNetworkPermission: " + e);
4607 }
4608 }
Paul Jensene0988542015-06-25 15:30:08 -04004609 synchronized (nai) {
4610 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004611 }
Paul Jensene0988542015-06-25 15:30:08 -04004612 rematchAllNetworksAndRequests(nai, oldScore);
4613 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004614 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004615 }
4616
Paul Jensenc8b9a742014-09-30 15:37:41 -04004617 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004618 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4619 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004620 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004621 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004622 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4623 }
4624 }
4625
Robert Greenwalt7b816022014-04-18 15:25:25 -07004626 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4627 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004628 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004629 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4630 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004631 }
4632 }
4633
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004634 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4635 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004636 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004637 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004638 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4639 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004640 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004641 sendIntent(nri.mPendingIntent, intent);
4642 }
4643 // else not handled
4644 }
4645
4646 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4647 mPendingIntentWakeLock.acquire();
4648 try {
4649 if (DBG) log("Sending " + pendingIntent);
4650 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4651 } catch (PendingIntent.CanceledException e) {
4652 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4653 mPendingIntentWakeLock.release();
4654 releasePendingNetworkRequest(pendingIntent);
4655 }
4656 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4657 }
4658
4659 @Override
4660 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4661 String resultData, Bundle resultExtras) {
4662 if (DBG) log("Finished sending " + pendingIntent);
4663 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004664 // Release with a delay so the receiving client has an opportunity to put in its
4665 // own request.
4666 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004667 }
4668
Robert Greenwalt9258c642014-03-26 16:47:06 -07004669 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004670 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004671 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004672 Bundle bundle = new Bundle();
4673 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4674 new NetworkRequest(nri.request));
4675 Message msg = Message.obtain();
4676 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4677 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4678 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4679 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004680 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004681 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004682 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004683 break;
4684 }
4685 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4686 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4687 new NetworkCapabilities(networkAgent.networkCapabilities));
4688 break;
4689 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004690 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004691 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4692 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004693 break;
4694 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004695 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004696 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004697 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004698 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004699 if (VDBG) {
4700 log("sending notification " + notifyTypeToName(notificationType) +
4701 " for " + nri.request);
4702 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004703 nri.messenger.send(msg);
4704 } catch (RemoteException e) {
4705 // may occur naturally in the race of binder death.
4706 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4707 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004708 }
4709
Paul Jensenc8b9a742014-09-30 15:37:41 -04004710 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004711 if (nai.numRequestNetworkRequests() != 0) {
4712 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4713 NetworkRequest nr = nai.requestAt(i);
4714 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004715 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004716 loge("Dead network still had at least " + nr);
4717 break;
4718 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004719 }
4720 nai.asyncChannel.disconnect();
4721 }
4722
Robert Greenwalt7b816022014-04-18 15:25:25 -07004723 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4724 if (oldNetwork == null) {
4725 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4726 return;
4727 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004728 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004729
4730 // If we get here it means that the last linger timeout for this network expired. So there
4731 // must be no other active linger timers, and we must stop lingering.
4732 oldNetwork.clearLingerState();
4733
4734 if (unneeded(oldNetwork)) {
4735 teardownUnneededNetwork(oldNetwork);
4736 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004737 }
4738
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004739 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004740 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004741 setupDataActivityTracking(newNetwork);
4742 try {
4743 mNetd.setDefaultNetId(newNetwork.network.netId);
4744 } catch (Exception e) {
4745 loge("Exception setting default network :" + e);
4746 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004747 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004748 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004749 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004750 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004751 }
4752
Paul Jensen2161a8e2014-09-11 11:00:39 -04004753 // Handles a network appearing or improving its score.
4754 //
4755 // - Evaluates all current NetworkRequests that can be
4756 // satisfied by newNetwork, and reassigns to newNetwork
4757 // any such requests for which newNetwork is the best.
4758 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004759 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004760 // needed. A network is needed if it is the best network for
4761 // one or more NetworkRequests, or if it is a VPN.
4762 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004763 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004764 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004765 //
4766 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4767 // networks that have no chance (i.e. even if validated)
4768 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004769 //
4770 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4771 // it does not remove NetworkRequests that other Networks could better satisfy.
4772 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4773 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4774 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004775 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004776 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004777 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4778 // performed to tear down unvalidated networks that have no chance (i.e. even if
4779 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004780 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004781 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004782 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004783 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004784 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004785 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004786 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004787 // Find and migrate to this Network any NetworkRequests for
4788 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004789 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004790 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004791 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004792 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004793 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4794 final boolean satisfies = newNetwork.satisfies(nri.request);
4795 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004796 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004797 log("Network " + newNetwork.name() + " was already satisfying" +
4798 " request " + nri.request.requestId + ". No change.");
4799 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004800 keep = true;
4801 continue;
4802 }
4803
4804 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004805 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004806 if (satisfies) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004807 if (nri.request.isListen()) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004808 // This is not a request, it's a callback listener.
4809 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004810 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004811 continue;
4812 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004813
Robert Greenwalt7b816022014-04-18 15:25:25 -07004814 // next check if it's better than any current network we're using for
4815 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004816 if (VDBG) {
4817 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004818 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4819 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004820 }
4821 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004822 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004823 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004824 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004825 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004826 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004827 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004828 affectedNetworks.add(currentNetwork);
4829 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004830 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004831 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004832 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004833 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004834 if (!newNetwork.addRequest(nri.request)) {
4835 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4836 }
4837 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004838 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004839 // Tell NetworkFactories about the new score, so they can stop
4840 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004841 // TODO - this could get expensive if we have alot of requests for this
4842 // network. Think about if there is a way to reduce this. Push
4843 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004844 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004845 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004846 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004847 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004848 if (currentNetwork != null) {
4849 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4850 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004851 }
4852 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004853 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004854 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4855 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004856 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004857 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4858 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4859 // This means this code doesn't have to handle the case where "currentNetwork" no
4860 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4861 if (DBG) {
4862 log("Network " + newNetwork.name() + " stopped satisfying" +
4863 " request " + nri.request.requestId);
4864 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004865 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004866 if (currentNetwork == newNetwork) {
4867 mNetworkForRequestId.remove(nri.request.requestId);
4868 sendUpdatedScoreToFactories(nri.request, 0);
4869 } else {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004870 if (nri.request.isRequest()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004871 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4872 newNetwork.name() +
4873 " without updating mNetworkForRequestId or factories!");
4874 }
4875 }
4876 // TODO: technically, sending CALLBACK_LOST here is
4877 // incorrect if nri is a request (not a listen) and there
4878 // is a replacement network currently connected that can
4879 // satisfy it. However, the only capability that can both
4880 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4881 // so this code is only incorrect for a network that loses
4882 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004883 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004884 }
4885 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004886 if (isNewDefault) {
4887 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004888 makeDefault(newNetwork);
4889 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4890 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004891 synchronized (ConnectivityService.this) {
4892 // have a new default network, release the transition wakelock in
4893 // a second if it's held. The second pause is to allow apps
4894 // to reconnect over the new network
4895 if (mNetTransitionWakeLock.isHeld()) {
4896 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4897 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4898 mNetTransitionWakeLockSerialNumber, 0),
4899 1000);
4900 }
4901 }
4902 }
4903
4904 // do this after the default net is switched, but
4905 // before LegacyTypeTracker sends legacy broadcasts
4906 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4907
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004908 // Linger any networks that are no longer needed. This should be done after sending the
4909 // available callback for newNetwork.
4910 for (NetworkAgentInfo nai : affectedNetworks) {
4911 updateLingerState(nai, now);
4912 }
4913 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4914 // does not need to be done in any particular order.
4915 updateLingerState(newNetwork, now);
4916
Paul Jensencf4c2c62015-07-01 14:16:32 -04004917 if (isNewDefault) {
4918 // Maintain the illusion: since the legacy API only
4919 // understands one network at a time, we must pretend
4920 // that the current default network disconnected before
4921 // the new one connected.
4922 if (oldDefaultNetwork != null) {
4923 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4924 oldDefaultNetwork, true);
4925 }
4926 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4927 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4928 notifyLockdownVpn(newNetwork);
4929 }
4930
Robert Greenwalt7b816022014-04-18 15:25:25 -07004931 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004932 // Notify battery stats service about this network, both the normal
4933 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004934 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004935 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004936 final IBatteryStats bs = BatteryStatsService.getService();
4937 final int type = newNetwork.networkInfo.getType();
4938
4939 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4940 bs.noteNetworkInterfaceType(baseIface, type);
4941 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4942 final String stackedIface = stacked.getInterfaceName();
4943 bs.noteNetworkInterfaceType(stackedIface, type);
4944 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4945 }
4946 } catch (RemoteException ignored) {
4947 }
4948
Robert Greenwalt152ed372014-12-17 17:19:53 -08004949 // This has to happen after the notifyNetworkCallbacks as that tickles each
4950 // ConnectivityManager instance so that legacy requests correctly bind dns
4951 // requests to this network. The legacy users are listening for this bcast
4952 // and will generally do a dns request so they can ensureRouteToHost and if
4953 // they do that before the callbacks happen they'll use the default network.
4954 //
4955 // TODO: Is there still a race here? We send the broadcast
4956 // after sending the callback, but if the app can receive the
4957 // broadcast before the callback, it might still break.
4958 //
4959 // This *does* introduce a race where if the user uses the new api
4960 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4961 // they may get old info. Reverse this after the old startUsing api is removed.
4962 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004963 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4964 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004965 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004966 // legacy type tracker filters out repeat adds
4967 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4968 }
4969 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004970
4971 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4972 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4973 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4974 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4975 if (newNetwork.isVPN()) {
4976 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4977 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004978 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004979 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4980 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004981 if (unneeded(nai)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004982 if (nai.getLingerExpiry() > 0) {
4983 // This network has active linger timers and no requests, but is not
4984 // lingering. Linger it.
4985 //
4986 // One way (the only way?) this can happen if this network is unvalidated
4987 // and became unneeded due to another network improving its score to the
4988 // point where this network will no longer be able to satisfy any requests
4989 // even if it validates.
4990 updateLingerState(nai, now);
4991 } else {
4992 if (DBG) log("Reaping " + nai.name());
4993 teardownUnneededNetwork(nai);
4994 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004995 }
4996 }
4997 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004998 }
4999
Paul Jensen1c7ba022015-06-16 14:27:36 -04005000 /**
5001 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5002 * being disconnected.
5003 * @param changed If only one Network's score or capabilities have been modified since the last
5004 * time this function was called, pass this Network in this argument, otherwise pass
5005 * null.
5006 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5007 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5008 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5009 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5010 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005011 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005012 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005013 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5014 // to avoid the slowness. It is not simply enough to process just "changed", for
5015 // example in the case where "changed"'s score decreases and another network should begin
5016 // satifying a NetworkRequest that "changed" currently satisfies.
5017
5018 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5019 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5020 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005021 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005022 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005023 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005024 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005025 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5026 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5027 // Rematch higher scoring networks first to prevent requests first matching a lower
5028 // scoring network and then a higher scoring network, which could produce multiple
5029 // callbacks and inadvertently unlinger networks.
5030 Arrays.sort(nais);
5031 for (NetworkAgentInfo nai : nais) {
5032 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005033 // Only reap the last time through the loop. Reaping before all rematching
5034 // is complete could incorrectly teardown a network that hasn't yet been
5035 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005036 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005037 : ReapUnvalidatedNetworks.REAP,
5038 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005039 }
5040 }
5041 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005042
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005043 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005044 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005045 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005046 // For now only update icons for default connection.
5047 // TODO: Update WiFi and cellular icons separately. b/17237507
5048 if (!isDefaultNetwork(nai)) return;
5049
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005050 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005051 // Don't repeat publish.
5052 if (newInetCondition == mDefaultInetConditionPublished) return;
5053
5054 mDefaultInetConditionPublished = newInetCondition;
5055 sendInetConditionBroadcast(nai.networkInfo);
5056 }
5057
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005058 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5059 if (mLockdownTracker != null) {
5060 if (nai != null && nai.isVPN()) {
5061 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5062 } else {
5063 mLockdownTracker.onNetworkInfoChanged();
5064 }
5065 }
5066 }
5067
Robert Greenwalt7b816022014-04-18 15:25:25 -07005068 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
5069 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005070 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005071 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005072 synchronized (networkAgent) {
5073 oldInfo = networkAgent.networkInfo;
5074 networkAgent.networkInfo = newInfo;
5075 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005076 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005077
5078 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005079 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5080 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5081 notifyIfacesChangedForNetworkStats();
5082 } else if (VDBG) log("ignoring duplicate network state non-change");
5083 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005084 return;
5085 }
5086 if (DBG) {
5087 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5088 (oldInfo == null ? "null" : oldInfo.getState()) +
5089 " to " + state);
5090 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005091
Robin Lee585e2482016-05-01 23:00:00 +01005092 if (!networkAgent.created
5093 && (state == NetworkInfo.State.CONNECTED
5094 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005095 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005096 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005097 if (networkAgent.isVPN()) {
5098 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005099 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5100 (networkAgent.networkMisc == null ||
5101 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005102 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005103 mNetd.createPhysicalNetwork(networkAgent.network.netId,
5104 networkAgent.networkCapabilities.hasCapability(
5105 NET_CAPABILITY_NOT_RESTRICTED) ?
5106 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005107 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005108 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005109 loge("Error creating network " + networkAgent.network.netId + ": "
5110 + e.getMessage());
5111 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005112 }
Paul Jenseneec75412014-08-04 12:21:19 -04005113 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005114 }
5115
5116 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5117 networkAgent.everConnected = true;
5118
Robert Greenwalt7b816022014-04-18 15:25:25 -07005119 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005120 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005121
Paul Jensenca8f16a2014-05-09 12:47:55 -04005122 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005123 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005124
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005125 if (networkAgent.isVPN()) {
5126 // Temporarily disable the default proxy (not global).
5127 synchronized (mProxyLock) {
5128 if (!mDefaultProxyDisabled) {
5129 mDefaultProxyDisabled = true;
5130 if (mGlobalProxy == null && mDefaultProxy != null) {
5131 sendProxyBroadcast(null);
5132 }
5133 }
5134 }
5135 // TODO: support proxy per network.
5136 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005137
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005138 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5139 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5140 // capabilities, so it only needs to be done once on initial connect, not every time the
5141 // network's capabilities change. Note that we do this before rematching the network,
5142 // so we could decide to tear it down immediately afterwards. That's fine though - on
5143 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5144 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005145 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005146
Paul Jensen2161a8e2014-09-11 11:00:39 -04005147 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005148 final long now = SystemClock.elapsedRealtime();
5149 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005150
5151 // This has to happen after matching the requests, because callbacks are just requests.
5152 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005153 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005154 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005155 if (networkAgent.isVPN()) {
5156 synchronized (mProxyLock) {
5157 if (mDefaultProxyDisabled) {
5158 mDefaultProxyDisabled = false;
5159 if (mGlobalProxy == null && mDefaultProxy != null) {
5160 sendProxyBroadcast(mDefaultProxy);
5161 }
5162 }
5163 }
5164 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005165 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5166 state == NetworkInfo.State.SUSPENDED) {
5167 // going into or coming out of SUSPEND: rescore and notify
5168 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005169 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005170 }
5171 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5172 ConnectivityManager.CALLBACK_SUSPENDED :
5173 ConnectivityManager.CALLBACK_RESUMED));
5174 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005175 }
5176 }
5177
Robert Greenwaltac96c522014-06-03 16:43:57 -07005178 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005179 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005180 if (score < 0) {
5181 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5182 "). Bumping score to min of 0");
5183 score = 0;
5184 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005185
Paul Jensen2161a8e2014-09-11 11:00:39 -04005186 final int oldScore = nai.getCurrentScore();
5187 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005188
Paul Jensen85cf78e2015-06-25 13:25:07 -04005189 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005190
Paul Jensenc8b9a742014-09-30 15:37:41 -04005191 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005192 }
5193
Robert Greenwalt9258c642014-03-26 16:47:06 -07005194 // notify only this one new request of the current state
5195 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
5196 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005197 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005198 callCallbackForRequest(nri, nai, notifyType, 0);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005199 } else {
5200 sendPendingIntentForRequest(nri, nai, notifyType);
5201 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07005202 }
5203
Robert Greenwalt8d482522015-06-24 13:23:42 -07005204 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005205 // The NetworkInfo we actually send out has no bearing on the real
5206 // state of affairs. For example, if the default connection is mobile,
5207 // and a request for HIPRI has just gone away, we need to pretend that
5208 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5209 // the state to DISCONNECTED, even though the network is of type MOBILE
5210 // and is still connected.
5211 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5212 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005213 if (state != DetailedState.DISCONNECTED) {
5214 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005215 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005216 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005217 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005218 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5219 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5220 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5221 if (info.isFailover()) {
5222 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5223 nai.networkInfo.setFailover(false);
5224 }
5225 if (info.getReason() != null) {
5226 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5227 }
5228 if (info.getExtraInfo() != null) {
5229 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5230 }
5231 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005232 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005233 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005234 if (newDefaultAgent != null) {
5235 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5236 newDefaultAgent.networkInfo);
5237 } else {
5238 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5239 }
5240 }
5241 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5242 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005243 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005244 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005245 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005246 }
5247 }
5248 }
5249
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005250 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005251 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005252 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5253 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005254 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5255 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005256 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005257 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005258 } else {
5259 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5260 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005261 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005262 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005263
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005264 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5265 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5266 }
5267
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005268 private String notifyTypeToName(int notifyType) {
5269 switch (notifyType) {
5270 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5271 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5272 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5273 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5274 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5275 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5276 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5277 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5278 }
5279 return "UNKNOWN";
5280 }
5281
Jeff Sharkey69736342014-12-08 14:50:12 -08005282 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005283 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5284 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005285 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005286 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005287 try {
5288 mStatsService.forceUpdateIfaces();
5289 } catch (Exception ignored) {
5290 }
5291 }
5292
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005293 @Override
5294 public boolean addVpnAddress(String address, int prefixLength) {
5295 throwIfLockdownEnabled();
5296 int user = UserHandle.getUserId(Binder.getCallingUid());
5297 synchronized (mVpns) {
5298 return mVpns.get(user).addAddress(address, prefixLength);
5299 }
5300 }
5301
5302 @Override
5303 public boolean removeVpnAddress(String address, int prefixLength) {
5304 throwIfLockdownEnabled();
5305 int user = UserHandle.getUserId(Binder.getCallingUid());
5306 synchronized (mVpns) {
5307 return mVpns.get(user).removeAddress(address, prefixLength);
5308 }
5309 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005310
5311 @Override
5312 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5313 throwIfLockdownEnabled();
5314 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005315 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005316 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005317 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005318 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005319 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005320 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005321 }
5322 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005323 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005324
5325 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005326 public String getCaptivePortalServerUrl() {
5327 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
5328 }
5329
5330 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005331 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5332 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5333 enforceKeepalivePermission();
5334 mKeepaliveTracker.startNattKeepalive(
5335 getNetworkAgentInfoForNetwork(network),
5336 intervalSeconds, messenger, binder,
5337 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5338 }
5339
5340 @Override
5341 public void stopKeepalive(Network network, int slot) {
5342 mHandler.sendMessage(mHandler.obtainMessage(
5343 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5344 }
5345
5346 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005347 public void factoryReset() {
5348 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005349
5350 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5351 return;
5352 }
5353
Robin Lee3b3dd942015-05-12 18:14:58 +01005354 final int userId = UserHandle.getCallingUserId();
5355
Stuart Scottf1fb3972015-04-02 18:00:02 -07005356 // Turn airplane mode off
5357 setAirplaneMode(false);
5358
Stuart Scotte3e314d2015-04-20 14:07:45 -07005359 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5360 // Untether
5361 for (String tether : getTetheredIfaces()) {
5362 untether(tether);
5363 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005364 }
5365
Stuart Scotte3e314d2015-04-20 14:07:45 -07005366 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005367 // Remove always-on package
5368 synchronized (mVpns) {
5369 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5370 if (alwaysOnPackage != null) {
5371 setAlwaysOnVpnPackage(userId, null, false);
5372 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5373 }
5374 }
5375
Stuart Scotte3e314d2015-04-20 14:07:45 -07005376 // Turn VPN off
5377 VpnConfig vpnConfig = getVpnConfig(userId);
5378 if (vpnConfig != null) {
5379 if (vpnConfig.legacy) {
5380 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5381 } else {
5382 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5383 // in the future without user intervention.
5384 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005385
Victor Changb04a5ea2016-05-30 20:36:30 +01005386 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005387 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005388 }
5389 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005390
5391 Settings.Global.putString(mContext.getContentResolver(),
5392 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005393 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005394
5395 @VisibleForTesting
5396 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5397 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5398 return new NetworkMonitor(context, handler, nai, defaultRequest);
5399 }
Erik Kline48f12f22016-04-14 17:30:59 +09005400
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005401 @VisibleForTesting
Erik Kline065ab6e2016-10-02 18:02:14 +09005402 AvoidBadWifiTracker createAvoidBadWifiTracker(Context c, Handler h, Runnable r) {
5403 return new AvoidBadWifiTracker(c, h, r);
5404 }
5405
5406 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005407 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5408 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5409 }
5410
Hugo Benichicfddd682016-05-31 16:28:06 +09005411 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005412 int newNetid = NETID_UNSET;
5413 int prevNetid = NETID_UNSET;
5414 int[] transports = new int[0];
5415 boolean hadIPv4 = false;
5416 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005417
Hugo Benichi5f16f762016-04-20 12:09:33 +09005418 if (newNai != null) {
5419 newNetid = newNai.network.netId;
5420 transports = newNai.networkCapabilities.getTransportTypes();
5421 }
5422 if (prevNai != null) {
5423 prevNetid = prevNai.network.netId;
5424 final LinkProperties lp = prevNai.linkProperties;
5425 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5426 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5427 }
5428
Hugo Benichicfddd682016-05-31 16:28:06 +09005429 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5430 }
5431
5432 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5433 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005434 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005435}