blob: 6dbf53850ec77ecbb7643979b16382427663e45e [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;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090022import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070023import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070024import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070025import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070026import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040027import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060032import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeandda156a2018-01-10 21:19:32 +090033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060035import static android.net.NetworkCapabilities.TRANSPORT_VPN;
36
Hugo Benichia0385682017-03-22 17:07:57 +090037import static com.android.internal.util.Preconditions.checkNotNull;
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;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070048import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070049import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090051import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070053import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070054import android.net.INetworkPolicyListener;
55import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070056import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080057import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070058import android.net.LinkProperties.CompareResult;
Hugo Benichib577d652017-06-27 15:13:20 +090059import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070060import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070061import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070062import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070063import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070065import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070066import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090067import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070068import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070069import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070070import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070073import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040074import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070075import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040076import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040077import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060078import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090079import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090080import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090081import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080083import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070084import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040085import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070087import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070088import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070089import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.os.Looper;
91import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070092import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070093import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090094import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070095import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070096import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070097import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080098import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090099import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900100import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900101import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700102import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400103import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800104import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700105import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700106import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700107import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700108import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900109import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700110import android.util.LocalLog;
111import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600112import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800113import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700114import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500115import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700116import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700117import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800118
Wink Savilleab9321d2013-06-29 21:10:57 -0700119import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400120import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400121import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700122import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700123import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700124import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700125import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800126import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700127import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700128import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600129import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700130import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900131import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900132import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700133import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700134import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400135import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900136import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900137import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
Hugo Benichi64901e52017-10-19 14:42:40 +0900138import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900139import com.android.server.connectivity.KeepaliveTracker;
Charles Hea0a87e82017-05-15 17:07:18 +0100140import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700141import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700142import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600143import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400144import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900145import com.android.server.connectivity.NetworkNotificationManager;
146import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400147import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700148import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800149import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700150import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900151import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700152import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700153import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900154import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600155
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700156import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700157
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700158import org.xmlpull.v1.XmlPullParser;
159import org.xmlpull.v1.XmlPullParserException;
160
161import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700163import java.io.FileNotFoundException;
164import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700165import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800166import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700167import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700168import java.net.InetAddress;
169import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700170import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700171import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700172import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700173import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700174import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700175import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700176import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700177import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700178import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900179import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600180import java.util.SortedSet;
181import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800182
183/**
184 * @hide
185 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800186public class ConnectivityService extends IConnectivityManager.Stub
187 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900188 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800189
Erik Kline7747fd42017-05-12 16:52:48 +0900190 public static final String DIAG_ARG = "--diag";
191 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900192 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900193
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900194 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700195 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Jake Hamby786e71a2014-02-06 14:43:50 -0800197 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900198 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700199
Jeff Sharkey899223b2012-08-04 15:24:58 -0700200 // TODO: create better separation between radio types and network types
201
Robert Greenwalt42acef32009-08-12 16:08:25 -0700202 // how long to wait before switching back to a radio's default network
203 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
204 // system property that can override the above value
205 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
206 "android.telephony.apn-restore";
207
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900208 // How long to wait before putting up a "This network doesn't have an Internet connection,
209 // connect anyway?" dialog after the user selects a network that doesn't validate.
210 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
211
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900212 // Default to 30s linger time-out. Modifiable only for testing.
213 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
214 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
215 @VisibleForTesting
216 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
217
Jeremy Joslin79294842014-12-03 17:15:28 -0800218 // How long to delay to removal of a pending intent based request.
219 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
220 private final int mReleasePendingIntentDelayMs;
221
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900222 private MockableSystemProperties mSystemProperties;
223
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800224 private Tethering mTethering;
225
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700226 private final PermissionMonitor mPermissionMonitor;
227
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700228 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700229
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700230 @GuardedBy("mVpns")
231 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700232
Hugo Benichi69744342017-11-27 10:57:16 +0900233 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
234 // a direct call to LockdownVpnTracker.isEnabled().
235 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700236 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900237 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700238 private LockdownVpnTracker mLockdownTracker;
239
Erik Klineda4bfa82015-04-30 12:58:40 +0900240 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800241 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700242 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700243 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700246 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700248 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800249 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700250 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900251 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700252
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700253 private String mCurrentTcpBufferSizes;
254
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700255 private static final int ENABLED = 1;
256 private static final int DISABLED = 0;
257
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900258 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900259 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
260 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900261
Paul Jensenb10e37f2014-11-25 12:33:08 -0500262 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400263 // Tear down networks that have no chance (e.g. even if validated) of becoming
264 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500265 // all networks have been rematched against all NetworkRequests.
266 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400267 // Don't reap networks. This should be passed when some networks have not yet been
268 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500269 DONT_REAP
270 };
271
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900272 private enum UnneededFor {
273 LINGER, // Determine whether this network is unneeded and should be lingered.
274 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
275 }
276
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700277 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700278 * used internally to change our mobile data enabled flag
279 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700280 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700281
282 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700283 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700284 * from one net to another. Clear happens when we get a new
285 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
286 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700287 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700288 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700289
Robert Greenwalt434203a2010-10-11 16:00:27 -0700290 /**
291 * used internally to reload global proxy settings
292 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700293 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700294
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700295 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400296 * PAC manager has received new port.
297 */
298 private static final int EVENT_PROXY_HAS_CHANGED = 16;
299
Robert Greenwalte049c232014-04-11 15:53:27 -0700300 /**
301 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700302 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700303 */
304 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
305
Robert Greenwalt7b816022014-04-18 15:25:25 -0700306 /**
307 * used internally when registering NetworkAgents
308 * obj = Messenger
309 */
310 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
311
Robert Greenwalt9258c642014-03-26 16:47:06 -0700312 /**
313 * used to add a network request
314 * includes a NetworkRequestInfo
315 */
316 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
317
318 /**
319 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900320 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700321 * cancel it.
322 * includes a NetworkRequestInfo
323 */
324 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
325
326 /**
327 * used to add a network listener - no request
328 * includes a NetworkRequestInfo
329 */
330 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
331
332 /**
333 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400334 * arg1 = UID of caller
335 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700336 */
337 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
338
Robert Greenwalta67be032014-05-16 15:49:14 -0700339 /**
340 * used internally when registering NetworkFactories
341 * obj = Messenger
342 */
343 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
344
Robert Greenwalt27711812014-06-25 16:45:57 -0700345 /**
346 * used internally to expire a wakelock when transitioning
347 * from one net to another. Expire happens when we fail to find
348 * a new network (typically after 1 minute) -
349 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
350 * a replacement network.
351 */
352 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
353
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700354 /**
355 * Used internally to indicate the system is ready.
356 */
357 private static final int EVENT_SYSTEM_READY = 25;
358
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800359 /**
360 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400361 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800362 */
363 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
364
365 /**
366 * used to remove a pending intent and its associated network request.
367 * arg1 = UID of caller
368 * obj = PendingIntent
369 */
370 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
371
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900372 /**
373 * used to specify whether a network should be used even if unvalidated.
374 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
375 * arg2 = whether to remember this choice in the future (1 or 0)
376 * obj = network
377 */
378 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
379
380 /**
381 * used to ask the user to confirm a connection to an unvalidated network.
382 * obj = network
383 */
384 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700385
Erik Klineda4bfa82015-04-30 12:58:40 +0900386 /**
387 * used internally to (re)configure mobile data always-on settings.
388 */
389 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
390
Paul Jensen694f2b82015-06-17 14:15:39 -0400391 /**
392 * used to add a network listener with a pending intent
393 * obj = NetworkRequestInfo
394 */
395 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
396
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900397 /**
398 * used to specify whether a network should not be penalized when it becomes unvalidated.
399 */
400 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
401
402 /**
403 * used to trigger revalidation of a network.
404 */
405 private static final int EVENT_REVALIDATE_NETWORK = 36;
406
Erik Klinea24d4592018-01-11 21:07:29 +0900407 // Handle changes in Private DNS settings.
408 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
409
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900410 private static String eventName(int what) {
411 return sMagicDecoderRing.get(what, Integer.toString(what));
412 }
413
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900414 /** Handler thread used for both of the handlers below. */
415 @VisibleForTesting
416 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700417 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700418 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700419 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700420 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900421 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700422
Mike Lockwood0f79b542009-08-14 14:18:49 -0400423 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800424 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400425
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700426 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700427 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800428 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700429
Robert Greenwalt434203a2010-10-11 16:00:27 -0700430 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400431 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700432 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700433 private boolean mDefaultProxyDisabled = false;
434
Robert Greenwalt434203a2010-10-11 16:00:27 -0700435 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400436 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700437
Jason Monk602b2322013-07-03 17:04:33 -0400438 private PacManager mPacManager = null;
439
Erik Klineda4bfa82015-04-30 12:58:40 +0900440 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700441
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400442 private UserManager mUserManager;
443
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700444 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700445 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700446
Robert Greenwalt50393202011-06-21 17:26:14 -0700447 // the set of network types that can only be enabled by system/sig apps
448 List mProtectedNetworks;
449
John Spurlockbf991a82013-06-24 14:20:23 -0400450 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700451
Wink Savilleab9321d2013-06-29 21:10:57 -0700452 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400453
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900454 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900455 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900456 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900457
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700458 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
459 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700460 private final static int MAX_NET_ID = 65535;
461 private int mNextNetId = MIN_NET_ID;
462
Robert Greenwalt34524f02014-05-18 16:22:10 -0700463 // sequence number of NetworkRequests
464 private int mNextNetworkRequestId = 1;
465
Erik Kline7523eb32015-07-09 18:24:03 +0900466 // NetworkRequest activity String log entries.
467 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
468 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
469
Hugo Benichic2ae2872016-07-11 11:05:12 +0900470 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900471 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900472 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
473
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900474 private static final int MAX_WAKELOCK_LOGS = 20;
475 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900476 private int mTotalWakelockAcquisitions = 0;
477 private int mTotalWakelockReleases = 0;
478 private long mTotalWakelockDurationMs = 0;
479 private long mMaxWakelockDurationMs = 0;
480 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900481
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700482 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
483 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400484 private static class ValidationLog {
485 final Network mNetwork;
486 final String mNetworkExtraInfo;
487 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700488
Paul Jensen0808eb82016-06-03 13:51:21 -0400489 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
490 mNetwork = network;
491 mNetworkExtraInfo = networkExtraInfo;
492 mLog = log;
493 }
494 }
495 private final ArrayDeque<ValidationLog> mValidationLogs =
496 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
497
498 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900499 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700500 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
501 mValidationLogs.removeLast();
502 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400503 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700504 }
505 }
506
Hugo Benichif9fdf872016-07-28 17:53:06 +0900507 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900508
Erik Kline065ab6e2016-10-02 18:02:14 +0900509 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900510 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900511
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700512 /**
513 * Implements support for the legacy "one network per network type" model.
514 *
515 * We used to have a static array of NetworkStateTrackers, one for each
516 * network type, but that doesn't work any more now that we can have,
517 * for example, more that one wifi network. This class stores all the
518 * NetworkAgentInfo objects that support a given type, but the legacy
519 * API will only see the first one.
520 *
521 * It serves two main purposes:
522 *
523 * 1. Provide information about "the network for a given type" (since this
524 * API only supports one).
525 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
526 * the first network for a given type changes, or if the default network
527 * changes.
528 */
529 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900531 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900532 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900533
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700534 /**
535 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
536 * Each list holds references to all NetworkAgentInfos that are used to
537 * satisfy requests for that network type.
538 *
539 * This array is built out at startup such that an unsupported network
540 * doesn't get an ArrayList instance, making this a tristate:
541 * unsupported, supported but not active and active.
542 *
543 * The actual lists are populated when we scan the network types that
544 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900545 *
546 * Threading model:
547 * - addSupportedType() is only called in the constructor
548 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
549 * They are therefore not thread-safe with respect to each other.
550 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
551 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
552 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700553 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900554 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700555
556 public LegacyTypeTracker() {
557 mTypeLists = (ArrayList<NetworkAgentInfo>[])
558 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
559 }
560
561 public void addSupportedType(int type) {
562 if (mTypeLists[type] != null) {
563 throw new IllegalStateException(
564 "legacy list for type " + type + "already initialized");
565 }
566 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
567 }
568
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700569 public boolean isTypeSupported(int type) {
570 return isNetworkTypeValid(type) && mTypeLists[type] != null;
571 }
572
573 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900574 synchronized (mTypeLists) {
575 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
576 return mTypeLists[type].get(0);
577 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700578 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900579 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700580 }
581
Robert Greenwalt8d482522015-06-24 13:23:42 -0700582 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900583 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900584 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700585 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900586 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900587 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900588 }
589 }
590
591 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700592 public void add(int type, NetworkAgentInfo nai) {
593 if (!isTypeSupported(type)) {
594 return; // Invalid network type.
595 }
596 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
597
598 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
599 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700600 return;
601 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900602 synchronized (mTypeLists) {
603 list.add(nai);
604 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900605
606 // 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 +0900607 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900608 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700609 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
610 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700611 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700612 }
613
Lorenzo Colittia793a672014-07-31 23:20:17 +0900614 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900615 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900616 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
617 if (list == null || list.isEmpty()) {
618 return;
619 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900620 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900621
Hugo Benichi78caa2582016-06-21 09:48:07 +0900622 synchronized (mTypeLists) {
623 if (!list.remove(nai)) {
624 return;
625 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900626 }
627
Robert Greenwalt8d482522015-06-24 13:23:42 -0700628 final DetailedState state = DetailedState.DISCONNECTED;
629
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700631 maybeLogBroadcast(nai, state, type, wasDefault);
632 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900633 }
634
635 if (!list.isEmpty() && wasFirstNetwork) {
636 if (DBG) log("Other network available for type " + type +
637 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900638 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700639 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
640 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900641 }
642 }
643
644 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900645 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
646 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700647 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900648 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700649 }
650 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700651
Robert Greenwalt8d482522015-06-24 13:23:42 -0700652 // send out another legacy broadcast - currently only used for suspend/unsuspend
653 // toggle
654 public void update(NetworkAgentInfo nai) {
655 final boolean isDefault = isDefaultNetwork(nai);
656 final DetailedState state = nai.networkInfo.getDetailedState();
657 for (int type = 0; type < mTypeLists.length; type++) {
658 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700659 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900660 final boolean isFirst = contains && (nai == list.get(0));
661 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700662 maybeLogBroadcast(nai, state, type, isDefault);
663 sendLegacyNetworkBroadcast(nai, state, type);
664 }
665 }
666 }
667
Lorenzo Colittia793a672014-07-31 23:20:17 +0900668 private String naiToString(NetworkAgentInfo nai) {
669 String name = (nai != null) ? nai.name() : "null";
670 String state = (nai.networkInfo != null) ?
671 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
672 "???/???";
673 return name + " " + state;
674 }
675
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700676 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900677 pw.println("mLegacyTypeTracker:");
678 pw.increaseIndent();
679 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700680 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900681 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700682 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900683 pw.println();
684 pw.println("Current state:");
685 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900686 synchronized (mTypeLists) {
687 for (int type = 0; type < mTypeLists.length; type++) {
688 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
689 for (NetworkAgentInfo nai : mTypeLists[type]) {
690 pw.println(type + " " + naiToString(nai));
691 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900692 }
693 }
694 pw.decreaseIndent();
695 pw.decreaseIndent();
696 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700697 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700698 }
699 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
700
Jeff Sharkey899223b2012-08-04 15:24:58 -0700701 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700702 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900703 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
704 }
705
706 @VisibleForTesting
707 protected ConnectivityService(Context context, INetworkManagementService netManager,
708 INetworkStatsService statsService, INetworkPolicyManager policyManager,
709 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800710 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800711
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900712 mSystemProperties = getSystemProperties();
713
Hugo Benichif9fdf872016-07-28 17:53:06 +0900714 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900715 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900716 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900717 mNetworkRequests.put(mDefaultRequest, defaultNRI);
718 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900719
Chalard Jeandda156a2018-01-10 21:19:32 +0900720 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900721 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700722
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900723 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900724 mHandlerThread.start();
725 mHandler = new InternalHandler(mHandlerThread.getLooper());
726 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700727
Jeremy Joslin79294842014-12-03 17:15:28 -0800728 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
729 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
730
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900731 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900732
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700733 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700734 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800735 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700736 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900737 mPolicyManagerInternal = checkNotNull(
738 LocalServices.getService(NetworkPolicyManagerInternal.class),
739 "missing NetworkPolicyManagerInternal");
740
Jeff Sharkey82f85212012-08-24 11:17:25 -0700741 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700742 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700743
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700744 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900745 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700746 } catch (RemoteException e) {
747 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700748 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700749 }
750
751 final PowerManager powerManager = (PowerManager) context.getSystemService(
752 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700753 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
754 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
755 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800756 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700757
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700758 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700759
Wink Saville51f456f2013-04-23 14:26:51 -0700760 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900761 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700762 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700763 String[] naStrings = context.getResources().getStringArray(
764 com.android.internal.R.array.networkAttributes);
765 for (String naString : naStrings) {
766 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700767 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700768 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700769 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800770 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700771 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700772 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700773 }
Wink Saville51f456f2013-04-23 14:26:51 -0700774 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
775 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
776 n.type);
777 continue;
778 }
Wink Saville975c8482011-04-07 14:23:45 -0700779 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800780 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700781 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700782 continue;
783 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700784 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700785
Wink Saville975c8482011-04-07 14:23:45 -0700786 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700787 mNetworksDefined++;
788 } catch(Exception e) {
789 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700790 }
791 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700792
793 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
794 if (mNetConfigs[TYPE_VPN] == null) {
795 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
796 // don't need to add TYPE_VPN to mNetConfigs.
797 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
798 mNetworksDefined++; // used only in the log() statement below.
799 }
800
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900801 // Do the same for Ethernet, since it's often not specified in the configs, although many
802 // devices can use it via USB host adapters.
803 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
804 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
805 mNetworksDefined++;
806 }
807
Wink Saville5e56bc52013-07-29 15:00:57 -0700808 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700809
Robert Greenwalt50393202011-06-21 17:26:14 -0700810 mProtectedNetworks = new ArrayList<Integer>();
811 int[] protectedNetworks = context.getResources().getIntArray(
812 com.android.internal.R.array.config_protectedNetworks);
813 for (int p : protectedNetworks) {
814 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
815 mProtectedNetworks.add(p);
816 } else {
817 if (DBG) loge("Ignoring protectedNetwork " + p);
818 }
819 }
820
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900821 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
822 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700823
Erik Kline47222fc2017-04-30 19:36:15 +0900824 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800825
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700826 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
827
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700828 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700829 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100830 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700831 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700832 intentFilter.addAction(Intent.ACTION_USER_ADDED);
833 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000834 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700835 mContext.registerReceiverAsUser(
836 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000837 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
838 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900839
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700840 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700841 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700842 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700843 } catch (RemoteException e) {
844 loge("Error registering observer :" + e);
845 }
846
Erik Klineda4bfa82015-04-30 12:58:40 +0900847 mSettingsObserver = new SettingsObserver(mContext, mHandler);
848 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800849
John Spurlockbf991a82013-06-24 14:20:23 -0400850 mDataConnectionStats = new DataConnectionStats(mContext);
851 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400852
Jason Monkdecd2952013-10-10 14:02:51 -0400853 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700854
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400855 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900856
857 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900858 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
859 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900860
861 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
862 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
863 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
864 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
865 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
866 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
867 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900868
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900869 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900870 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900871 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900872
873 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900874 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700876
Erik Kline47222fc2017-04-30 19:36:15 +0900877 private Tethering makeTethering() {
878 // TODO: Move other elements into @Overridden getters.
879 final TetheringDependencies deps = new TetheringDependencies();
880 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
881 IoThread.get().getLooper(), new MockableSystemProperties(),
882 deps);
883 }
884
Chalard Jeandda156a2018-01-10 21:19:32 +0900885 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900886 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900887 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900888 netCap.addCapability(NET_CAPABILITY_INTERNET);
889 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900890 if (transportType > -1) {
891 netCap.addTransportType(transportType);
892 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900893 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900894 }
895
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900896 // Used only for testing.
897 // TODO: Delete this and either:
898 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
899 // changing ContentResolver to make registerContentObserver non-final).
900 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
901 // by subclassing SettingsObserver.
902 @VisibleForTesting
903 void updateMobileDataAlwaysOn() {
904 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
905 }
906
Erik Klineda4bfa82015-04-30 12:58:40 +0900907 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900908 final boolean enable = toBool(Settings.Global.getInt(
909 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900910 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
911 if (enable == isEnabled) {
912 return; // Nothing to do.
913 }
914
915 if (enable) {
916 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900917 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900918 } else {
919 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
920 }
921 }
922
923 private void registerSettingsCallbacks() {
924 // Watch for global HTTP proxy changes.
925 mSettingsObserver.observe(
926 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
927 EVENT_APPLY_GLOBAL_HTTP_PROXY);
928
929 // Watch for whether or not to keep mobile data always on.
930 mSettingsObserver.observe(
931 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
932 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
933 }
934
Erik Klinea24d4592018-01-11 21:07:29 +0900935 private void registerPrivateDnsSettingsCallbacks() {
936 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
937 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
938 }
939 }
940
Robert Greenwalt34524f02014-05-18 16:22:10 -0700941 private synchronized int nextNetworkRequestId() {
942 return mNextNetworkRequestId++;
943 }
944
Paul Jensen67b0b072015-06-10 11:22:17 -0400945 @VisibleForTesting
946 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400947 synchronized (mNetworkForNetId) {
948 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
949 int netId = mNextNetId;
950 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
951 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500952 if (!mNetIdInUse.get(netId)) {
953 mNetIdInUse.put(netId, true);
954 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400955 }
956 }
957 }
958 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700959 }
960
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600961 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800962 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600963 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
964 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600966 state = nai.getNetworkState();
967 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800968 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600969 final NetworkInfo info = new NetworkInfo(networkType, 0,
970 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800971 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
972 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700973 final NetworkCapabilities capabilities = new NetworkCapabilities();
974 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
975 !info.isRoaming());
976 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600977 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800978 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600979 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600980 return state;
981 } else {
982 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800983 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400984 }
985
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800986 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
987 if (network == null) {
988 return null;
989 }
990 synchronized (mNetworkForNetId) {
991 return mNetworkForNetId.get(network.netId);
992 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600993 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800994
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900995 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +0900996 synchronized (mVpns) {
997 if (!mLockdownEnabled) {
998 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900999 Vpn vpn = mVpns.get(user);
1000 if (vpn != null && vpn.appliesToUid(uid)) {
1001 return vpn.getUnderlyingNetworks();
1002 }
1003 }
1004 }
1005 return null;
1006 }
1007
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001008 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001009 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001010
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001011 final Network[] networks = getVpnUnderlyingNetworks(uid);
1012 if (networks != null) {
1013 // getUnderlyingNetworks() returns:
1014 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1015 // empty array => the VPN explicitly said "no default network".
1016 // non-empty array => the VPN specified one or more default networks; we use the
1017 // first one.
1018 if (networks.length > 0) {
1019 nai = getNetworkAgentInfoForNetwork(networks[0]);
1020 } else {
1021 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001022 }
1023 }
1024
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001026 return nai.getNetworkState();
1027 } else {
1028 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001030 }
1031
1032 /**
1033 * Check if UID should be blocked from using the network with the given LinkProperties.
1034 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001035 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1036 boolean ignoreBlocked) {
1037 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001038 if (ignoreBlocked) {
1039 return false;
1040 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001041 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001042 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1043 if (isSystem(uid)) {
1044 return false;
1045 }
Robin Lee17e61832016-05-09 13:46:28 +01001046 synchronized (mVpns) {
1047 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1048 if (vpn != null && vpn.isBlockingUid(uid)) {
1049 return true;
1050 }
1051 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001052 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001053 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 }
1055
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001056 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001057 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1058 return;
1059 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001060 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001061 synchronized (mBlockedAppUids) {
1062 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001063 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001064 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001065 blocked = false;
1066 } else {
1067 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001068 }
1069 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001070 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1071 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1072 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001073 }
1074
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001075 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001076 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1077 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001078 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001079 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001080 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001081 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1082
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001083 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001084 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001085 }
Hugo Benichi69744342017-11-27 10:57:16 +09001086 synchronized (mVpns) {
1087 if (mLockdownTracker != null) {
1088 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1089 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001090 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001091 }
1092
1093 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001094 * Return NetworkInfo for the active (i.e., connected) network interface.
1095 * It is assumed that at most one network is active at a time. If more
1096 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001097 * @return the info for the active network, or {@code null} if none is
1098 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001099 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001100 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001101 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001102 enforceAccessPermission();
1103 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001104 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001105 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001106 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1107 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001108 }
1109
Paul Jensen31a94f42015-02-13 14:18:39 -05001110 @Override
1111 public Network getActiveNetwork() {
1112 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001113 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001114 }
1115
1116 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001117 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001118 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001119 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001120 }
1121
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001123 final int user = UserHandle.getUserId(uid);
1124 int vpnNetId = NETID_UNSET;
1125 synchronized (mVpns) {
1126 final Vpn vpn = mVpns.get(user);
1127 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1128 }
1129 NetworkAgentInfo nai;
1130 if (vpnNetId != NETID_UNSET) {
1131 synchronized (mNetworkForNetId) {
1132 nai = mNetworkForNetId.get(vpnNetId);
1133 }
1134 if (nai != null) return nai.network;
1135 }
1136 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001137 if (nai != null
1138 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1139 nai = null;
1140 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001141 return nai != null ? nai.network : null;
1142 }
1143
Lorenzo Colitti18660282016-07-04 12:55:44 +09001144 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001145 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1146 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001147 final int uid = Binder.getCallingUid();
1148 NetworkState state = getUnfilteredActiveNetworkState(uid);
1149 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001150 }
1151
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001152 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001153 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001154 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001155 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001156 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001157 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001158 }
1159
1160 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 public NetworkInfo getNetworkInfo(int networkType) {
1162 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001164 if (getVpnUnderlyingNetworks(uid) != null) {
1165 // A VPN is active, so we may need to return one of its underlying networks. This
1166 // information is not available in LegacyTypeTracker, so we have to get it from
1167 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001168 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001169 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001170 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001171 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001172 }
1173 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001174 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
1177
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001178 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001179 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001180 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001181 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001182 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001183 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001184 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001185 return state.networkInfo;
1186 } else {
1187 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001188 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001189 }
1190
1191 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001192 public NetworkInfo[] getAllNetworkInfo() {
1193 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001194 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001195 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1196 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001197 NetworkInfo info = getNetworkInfo(networkType);
1198 if (info != null) {
1199 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001200 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001201 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001202 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001203 }
1204
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001205 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001206 public Network getNetworkForType(int networkType) {
1207 enforceAccessPermission();
1208 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001209 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1210 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001211 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001212 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001213 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001214 }
1215
1216 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001217 public Network[] getAllNetworks() {
1218 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001219 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001220 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001221 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001222 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001223 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001224 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001225 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001226 }
1227
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001228 @Override
1229 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1230 // The basic principle is: if an app's traffic could possibly go over a
1231 // network, without the app doing anything multinetwork-specific,
1232 // (hence, by "default"), then include that network's capabilities in
1233 // the array.
1234 //
1235 // In the normal case, app traffic only goes over the system's default
1236 // network connection, so that's the only network returned.
1237 //
1238 // With a VPN in force, some app traffic may go into the VPN, and thus
1239 // over whatever underlying networks the VPN specifies, while other app
1240 // traffic may go over the system default network (e.g.: a split-tunnel
1241 // VPN, or an app disallowed by the VPN), so the set of networks
1242 // returned includes the VPN's underlying networks and the system
1243 // default.
1244 enforceAccessPermission();
1245
1246 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1247
1248 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001249 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001250 if (nc != null) {
1251 result.put(nai.network, nc);
1252 }
1253
Hugo Benichi69744342017-11-27 10:57:16 +09001254 synchronized (mVpns) {
1255 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001256 Vpn vpn = mVpns.get(userId);
1257 if (vpn != null) {
1258 Network[] networks = vpn.getUnderlyingNetworks();
1259 if (networks != null) {
1260 for (Network network : networks) {
1261 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001262 nc = getNetworkCapabilitiesInternal(nai);
Chalard Jeandda156a2018-01-10 21:19:32 +09001263 // nc is a copy of the capabilities in nai, so it's fine to mutate it
1264 // TODO : don't remove the UIDs when communicating with processes
1265 // that have the NETWORK_SETTINGS permission.
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001266 if (nc != null) {
Chalard Jeandda156a2018-01-10 21:19:32 +09001267 nc.setSingleUid(userId);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001268 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001269 }
1270 }
1271 }
1272 }
1273 }
1274 }
1275
1276 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1277 out = result.values().toArray(out);
1278 return out;
1279 }
1280
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001281 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001282 public boolean isNetworkSupported(int networkType) {
1283 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001284 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001285 }
1286
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001287 /**
1288 * Return LinkProperties for the active (i.e., connected) default
1289 * network interface. It is assumed that at most one default network
1290 * is active at a time. If more than one is active, it is indeterminate
1291 * which will be returned.
1292 * @return the ip properties for the active network, or {@code null} if
1293 * none is active
1294 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001295 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001296 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001297 enforceAccessPermission();
1298 final int uid = Binder.getCallingUid();
1299 NetworkState state = getUnfilteredActiveNetworkState(uid);
1300 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001301 }
1302
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001303 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001304 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001305 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001306 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1307 if (nai != null) {
1308 synchronized (nai) {
1309 return new LinkProperties(nai.linkProperties);
1310 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001311 }
1312 return null;
1313 }
1314
Robert Greenwalt12e67352014-05-13 21:41:06 -07001315 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001316 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001317 public LinkProperties getLinkProperties(Network network) {
1318 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001319 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1320 }
1321
1322 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1323 if (nai == null) {
1324 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001325 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001326 synchronized (nai) {
1327 return new LinkProperties(nai.linkProperties);
1328 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001329 }
1330
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001331 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001332 if (nai != null) {
1333 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001334 if (nai.networkCapabilities != null) {
1335 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001336 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001337 }
1338 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001339 return null;
1340 }
1341
1342 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001343 public NetworkCapabilities getNetworkCapabilities(Network network) {
1344 enforceAccessPermission();
1345 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1346 }
1347
1348 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001349 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001350 // Require internal since we're handing out IMSI details
1351 enforceConnectivityInternalPermission();
1352
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001353 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001354 for (Network network : getAllNetworks()) {
1355 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1356 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001357 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001358 }
1359 }
1360 return result.toArray(new NetworkState[result.size()]);
1361 }
1362
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001363 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001364 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001365 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001366 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1367 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1368 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001369 }
1370
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001371 @Override
1372 public boolean isActiveNetworkMetered() {
1373 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001374
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001375 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1376 if (caps != null) {
1377 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1378 } else {
1379 // Always return the most conservative value
1380 return true;
1381 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001382 }
1383
Jeff Sharkey216c1812012-08-05 14:29:23 -07001384 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1385 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001386 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001387 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001388 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001389 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001390 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001391
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001392 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 * Ensure that a network route exists to deliver traffic to the specified
1394 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001395 * @param networkType the type of the network over which traffic to the
1396 * specified host is to be routed
1397 * @param hostAddress the IP address of the host to which the route is
1398 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 * @return {@code true} on success, {@code false} on failure
1400 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001401 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001402 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001404 if (mProtectedNetworks.contains(networkType)) {
1405 enforceConnectivityInternalPermission();
1406 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001407
Chad Brubakerc0234532014-02-14 13:24:29 -08001408 InetAddress addr;
1409 try {
1410 addr = InetAddress.getByAddress(hostAddress);
1411 } catch (UnknownHostException e) {
1412 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1413 return false;
1414 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001415
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001416 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001417 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 return false;
1419 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001420
1421 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1422 if (nai == null) {
1423 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1424 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1425 } else {
1426 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1427 }
1428 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001429 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001430
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001431 DetailedState netState;
1432 synchronized (nai) {
1433 netState = nai.networkInfo.getDetailedState();
1434 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001435
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001436 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001437 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001438 log("requestRouteToHostAddress on down network "
1439 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001440 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001441 }
1442 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001444
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001445 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001446 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001447 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001448 LinkProperties lp;
1449 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001450 synchronized (nai) {
1451 lp = nai.linkProperties;
1452 netId = nai.network.netId;
1453 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001454 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001455 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1456 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001457 } finally {
1458 Binder.restoreCallingIdentity(token);
1459 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001460 }
1461
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001462 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001463 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001464 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001465 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001466 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001467 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001468 if (bestRoute.getGateway().equals(addr)) {
1469 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001470 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001471 } else {
1472 // if we will connect to this through another route, add a direct route
1473 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001474 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001475 }
1476 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001477 if (DBG) log("Adding legacy route " + bestRoute +
1478 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001479 try {
1480 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1481 } catch (Exception e) {
1482 // never crash - catch them all
1483 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001484 return false;
1485 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001486 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488
Jeff Sharkey75d31892018-01-18 22:01:59 +09001489 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001490 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001491 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001492 // TODO: notify UID when it has requested targeted updates
1493 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001494 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001495 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001496 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001497 if (restrictBackground) {
1498 log("onRestrictBackgroundChanged(true): disabling tethering");
1499 mTethering.untetherAll();
1500 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001501 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001502 };
1503
Robin Lee3b3dd942015-05-12 18:14:58 +01001504 /**
1505 * Require that the caller is either in the same user or has appropriate permission to interact
1506 * across users.
1507 *
1508 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1509 */
1510 private void enforceCrossUserPermission(int userId) {
1511 if (userId == UserHandle.getCallingUserId()) {
1512 // Not a cross-user call.
1513 return;
1514 }
1515 mContext.enforceCallingOrSelfPermission(
1516 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1517 "ConnectivityService");
1518 }
1519
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001520 private void enforceInternetPermission() {
1521 mContext.enforceCallingOrSelfPermission(
1522 android.Manifest.permission.INTERNET,
1523 "ConnectivityService");
1524 }
1525
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001526 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.ACCESS_NETWORK_STATE,
1529 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001530 }
1531
1532 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001533 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 }
1535
Charles Hea0a87e82017-05-15 17:07:18 +01001536 private void enforceSettingsPermission() {
1537 mContext.enforceCallingOrSelfPermission(
1538 android.Manifest.permission.NETWORK_SETTINGS,
1539 "ConnectivityService");
1540 }
1541
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001542 private void enforceTetherAccessPermission() {
1543 mContext.enforceCallingOrSelfPermission(
1544 android.Manifest.permission.ACCESS_NETWORK_STATE,
1545 "ConnectivityService");
1546 }
1547
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001548 private void enforceConnectivityInternalPermission() {
1549 mContext.enforceCallingOrSelfPermission(
1550 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1551 "ConnectivityService");
1552 }
1553
Hugo Benichi514da602016-07-19 15:59:27 +09001554 private void enforceConnectivityRestrictedNetworksPermission() {
1555 try {
1556 mContext.enforceCallingOrSelfPermission(
1557 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1558 "ConnectivityService");
1559 return;
1560 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1561 enforceConnectivityInternalPermission();
1562 }
1563
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001564 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001565 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001566 }
1567
Lorenzo Colitti18660282016-07-04 12:55:44 +09001568 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001569 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001570 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001571 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001572 }
1573
1574 private void sendInetConditionBroadcast(NetworkInfo info) {
1575 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1576 }
1577
Wink Saville628b0852011-08-04 15:01:58 -07001578 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001579 synchronized (mVpns) {
1580 if (mLockdownTracker != null) {
1581 info = new NetworkInfo(info);
1582 mLockdownTracker.augmentNetworkInfo(info);
1583 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001584 }
1585
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001586 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001587 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001588 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001589 if (info.isFailover()) {
1590 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1591 info.setFailover(false);
1592 }
1593 if (info.getReason() != null) {
1594 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1595 }
1596 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001597 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1598 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001599 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001600 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001601 return intent;
1602 }
1603
1604 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1605 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1606 }
1607
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001608 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001609 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1610 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1611 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001612 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001613 final long ident = Binder.clearCallingIdentity();
1614 try {
1615 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1616 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1617 } finally {
1618 Binder.restoreCallingIdentity(ident);
1619 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001620 }
1621
Mike Lockwood0f79b542009-08-14 14:18:49 -04001622 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001623 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001624 if (!mSystemReady) {
1625 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001626 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001627 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001628 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001629 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001630 }
1631
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001632 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001633 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001634 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001635 final NetworkInfo ni = intent.getParcelableExtra(
1636 ConnectivityManager.EXTRA_NETWORK_INFO);
1637 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1638 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1639 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001640 } else {
1641 BroadcastOptions opts = BroadcastOptions.makeBasic();
1642 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1643 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001644 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001645 final IBatteryStats bs = BatteryStatsService.getService();
1646 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001647 bs.noteConnectivityChanged(intent.getIntExtra(
1648 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1649 ni != null ? ni.getState().toString() : "?");
1650 } catch (RemoteException e) {
1651 }
1652 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001653 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001654 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001655 } finally {
1656 Binder.restoreCallingIdentity(ident);
1657 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001658 }
1659 }
1660
1661 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001662 loadGlobalProxy();
1663
Hugo Benichi20035e02017-04-26 14:53:28 +09001664 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001665 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001666 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001667 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001668 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001669 }
1670 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001671 // load the global proxy at startup
1672 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001673
Robin Lee244ce8e2016-01-05 18:03:46 +00001674 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1675 // for user to unlock device too.
1676 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001677
Erik Klineda4bfa82015-04-30 12:58:40 +09001678 // Configure whether mobile data is always on.
1679 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1680
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001681 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001682
1683 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001684 }
1685
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001686 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001687 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001688 *
1689 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001690 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001691 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001692 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1693 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001694
1695 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001696 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001697
Robert Greenwalt7b816022014-04-18 15:25:25 -07001698 if (networkAgent.networkCapabilities.hasTransport(
1699 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001700 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1701 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001702 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001703 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001704 } else if (networkAgent.networkCapabilities.hasTransport(
1705 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001706 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1707 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001708 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001709 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001710 } else {
1711 // do not track any other networks
1712 timeout = 0;
1713 }
1714
Robert Greenwalt7b816022014-04-18 15:25:25 -07001715 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001716 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001717 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001718 } catch (Exception e) {
1719 // You shall not crash!
1720 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001721 }
1722 }
1723 }
1724
1725 /**
1726 * Remove data activity tracking when network disconnects.
1727 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001728 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1729 final String iface = networkAgent.linkProperties.getInterfaceName();
1730 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001731
Robert Greenwalt7b816022014-04-18 15:25:25 -07001732 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1733 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001734 try {
1735 // the call fails silently if no idletimer setup for this interface
1736 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001737 } catch (Exception e) {
1738 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001739 }
1740 }
1741 }
1742
1743 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001744 * Reads the network specific MTU size from reources.
1745 * and set it on it's iface.
1746 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001747 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1748 final String iface = newLp.getInterfaceName();
1749 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001750 if (oldLp == null && mtu == 0) {
1751 // Silently ignore unset MTU value.
1752 return;
1753 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001754 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1755 if (VDBG) log("identical MTU - not setting");
1756 return;
1757 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001758 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001759 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001760 return;
1761 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001762
w1997615afd812014-08-05 15:18:11 -07001763 // Cannot set MTU without interface name
1764 if (TextUtils.isEmpty(iface)) {
1765 loge("Setting MTU size with null iface.");
1766 return;
1767 }
1768
Robert Greenwalt7b816022014-04-18 15:25:25 -07001769 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001770 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001771 mNetd.setMtu(iface, mtu);
1772 } catch (Exception e) {
1773 Slog.e(TAG, "exception in setMtu()" + e);
1774 }
1775 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001776
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001777 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001778 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1779
1780 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001781 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001782 protected MockableSystemProperties getSystemProperties() {
1783 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001784 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001785
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001786 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1787 if (isDefaultNetwork(nai) == false) {
1788 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001789 }
1790
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001791 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1792 String[] values = null;
1793 if (tcpBufferSizes != null) {
1794 values = tcpBufferSizes.split(",");
1795 }
1796
1797 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001798 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001799 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1800 values = tcpBufferSizes.split(",");
1801 }
1802
1803 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1804
1805 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001806 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001807
1808 final String prefix = "/sys/kernel/ipv4/tcp_";
1809 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1810 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1811 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1812 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1813 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1814 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1815 mCurrentTcpBufferSizes = tcpBufferSizes;
1816 } catch (IOException e) {
1817 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001818 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001819
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001820 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001821 Settings.Global.TCP_DEFAULT_INIT_RWND,
1822 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001823 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1824 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001825 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001826 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001827 }
1828
Robert Greenwalt562cc542014-05-15 18:07:26 -07001829 @Override
1830 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001831 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001832 NETWORK_RESTORE_DELAY_PROP_NAME);
1833 if(restoreDefaultNetworkDelayStr != null &&
1834 restoreDefaultNetworkDelayStr.length() != 0) {
1835 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001836 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001837 } catch (NumberFormatException e) {
1838 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001839 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001840 // if the system property isn't set, use the value for the apn type
1841 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1842
1843 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1844 (mNetConfigs[networkType] != null)) {
1845 ret = mNetConfigs[networkType].restoreTime;
1846 }
1847 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001848 }
1849
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001850 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001851 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001852 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001853 }
1854 return false;
1855 }
1856
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001857 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1858 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1859 final long DIAG_TIME_MS = 5000;
1860 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1861 // Start gathering diagnostic information.
1862 netDiags.add(new NetworkDiagnostics(
1863 nai.network,
1864 new LinkProperties(nai.linkProperties), // Must be a copy.
1865 DIAG_TIME_MS));
1866 }
1867
1868 for (NetworkDiagnostics netDiag : netDiags) {
1869 pw.println();
1870 netDiag.waitForMeasurements();
1871 netDiag.dump(pw);
1872 }
1873 }
1874
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001875 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001876 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1877 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001878 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001879
Erik Kline7747fd42017-05-12 16:52:48 +09001880 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001881 dumpNetworkDiagnostics(pw);
1882 return;
Erik Klineee363c42017-05-29 09:11:03 +09001883 } else if (argsContain(args, TETHERING_ARG)) {
1884 mTethering.dump(fd, pw, args);
1885 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001886 }
Erik Kline379747a2015-06-05 17:47:34 +09001887
Lorenzo Colittie3805462015-06-03 11:18:24 +09001888 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001889 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001890 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001891 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001892 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001893 pw.println();
1894
Paul Jensen85cf78e2015-06-25 13:25:07 -04001895 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001896 pw.print("Active default network: ");
1897 if (defaultNai == null) {
1898 pw.println("none");
1899 } else {
1900 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001901 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001902 pw.println();
1903
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001904 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001905 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001906 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1907 pw.println(nai.toString());
1908 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001909 pw.println(String.format(
1910 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1911 nai.numForegroundNetworkRequests(),
1912 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1913 nai.numBackgroundNetworkRequests(),
1914 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001915 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001916 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1917 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001918 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001919 pw.decreaseIndent();
1920 pw.println("Lingered:");
1921 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001922 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001923 pw.decreaseIndent();
1924 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001925 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001926 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001927 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001928
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001929 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001930 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001931 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1932 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001933 }
1934 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001935 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001936
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001937 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001938
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001939 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001940 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001941
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001942 pw.println();
1943 mKeepaliveTracker.dump(pw);
1944
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001945 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001946 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001947
Erik Kline7747fd42017-05-12 16:52:48 +09001948 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001949 pw.println();
1950 synchronized (mValidationLogs) {
1951 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001952 for (ValidationLog p : mValidationLogs) {
1953 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001954 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001955 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001956 pw.decreaseIndent();
1957 }
1958 }
Erik Kline7523eb32015-07-09 18:24:03 +09001959
1960 pw.println();
1961 pw.println("mNetworkRequestInfoLogs (most recent first):");
1962 pw.increaseIndent();
1963 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1964 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001965
1966 pw.println();
1967 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1968 pw.increaseIndent();
1969 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1970 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001971
1972 pw.println();
1973 pw.println("NetTransition WakeLock activity (most recent first):");
1974 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09001975 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1976 pw.println("total releases: " + mTotalWakelockReleases);
1977 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1978 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1979 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1980 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1981 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1982 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001983 mWakelockLogs.reverseDump(fd, pw, args);
1984 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001985 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001986 }
1987
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001988 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001989 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001990 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001991 if (officialNai != null && officialNai.equals(nai)) return true;
1992 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001993 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001994 " - " + nai);
1995 }
1996 return false;
1997 }
1998
Robert Greenwalt42acef32009-08-12 16:08:25 -07001999 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002000 private class NetworkStateTrackerHandler extends Handler {
2001 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002002 super(looper);
2003 }
2004
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002005 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002006 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002007 default:
2008 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002009 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002010 handleAsyncChannelHalfConnect(msg);
2011 break;
2012 }
2013 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2014 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2015 if (nai != null) nai.asyncChannel.disconnect();
2016 break;
2017 }
2018 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2019 handleAsyncChannelDisconnected(msg);
2020 break;
2021 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002022 }
2023 return true;
2024 }
2025
2026 private void maybeHandleNetworkAgentMessage(Message msg) {
2027 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2028 if (nai == null) {
2029 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002030 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002031 }
2032 return;
2033 }
2034
2035 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002036 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002037 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2038 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002039 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2040 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002041 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002042 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002043 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002044 break;
2045 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002047 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002048 break;
2049 }
2050 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002051 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002052 updateNetworkInfo(nai, info);
2053 break;
2054 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002055 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002056 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002057 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002058 break;
2059 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002060 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002061 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2062 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002063 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002064 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002065 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002066 break;
2067 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002068 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002069 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2070 break;
2071 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002072 }
2073 }
2074
2075 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2076 switch (msg.what) {
2077 default:
2078 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002079 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002080 final NetworkAgentInfo nai;
2081 synchronized (mNetworkForNetId) {
2082 nai = mNetworkForNetId.get(msg.arg2);
2083 }
Erik Klinea24d4592018-01-11 21:07:29 +09002084 if (nai == null) break;
2085
2086 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2087 final boolean wasValidated = nai.lastValidated;
2088 final boolean wasDefault = isDefaultNetwork(nai);
2089
2090 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2091 ? (PrivateDnsConfig) msg.obj : null;
2092 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2093
2094 final boolean reevaluationRequired;
2095 final String logMsg;
2096 if (valid) {
2097 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2098 logMsg = (DBG && (privateDnsCfg != null))
2099 ? " with " + privateDnsCfg.toString() : "";
2100 } else {
2101 reevaluationRequired = false;
2102 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2103 ? " with redirect to " + redirectUrl : "";
2104 }
2105 if (DBG) {
2106 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2107 }
2108 // If there is a change in Private DNS configuration,
2109 // trigger reevaluation of the network to test it.
2110 if (reevaluationRequired) {
2111 nai.networkMonitor.sendMessage(
2112 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2113 break;
2114 }
2115 if (valid != nai.lastValidated) {
2116 if (wasDefault) {
2117 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2118 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002119 }
Erik Klinea24d4592018-01-11 21:07:29 +09002120 final int oldScore = nai.getCurrentScore();
2121 nai.lastValidated = valid;
2122 nai.everValidated |= valid;
2123 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2124 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2125 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2126 }
2127 updateInetCondition(nai);
2128 // Let the NetworkAgent know the state of its network
2129 Bundle redirectUrlBundle = new Bundle();
2130 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2131 nai.asyncChannel.sendMessage(
2132 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2133 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2134 0, redirectUrlBundle);
2135 if (wasValidated && !nai.lastValidated) {
2136 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002137 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002138 break;
2139 }
Paul Jensen869868be2014-05-15 10:33:05 -04002140 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002141 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002142 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002143 final NetworkAgentInfo nai;
2144 synchronized (mNetworkForNetId) {
2145 nai = mNetworkForNetId.get(netId);
2146 }
Calvin Onbe96da12016-10-11 15:10:46 -07002147 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002148 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002149 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002150 nai.lastCaptivePortalDetected = visible;
2151 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002152 if (nai.lastCaptivePortalDetected &&
2153 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2154 if (DBG) log("Avoiding captive portal network: " + nai.name());
2155 nai.asyncChannel.sendMessage(
2156 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2157 teardownUnneededNetwork(nai);
2158 break;
2159 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002160 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002161 }
2162 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002163 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002164 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002165 if (nai == null) {
2166 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2167 break;
2168 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002169 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002170 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002171 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002172 }
Paul Jensen869868be2014-05-15 10:33:05 -04002173 }
Paul Jensen869868be2014-05-15 10:33:05 -04002174 break;
2175 }
Erik Klinea24d4592018-01-11 21:07:29 +09002176 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2177 final NetworkAgentInfo nai;
2178 synchronized (mNetworkForNetId) {
2179 nai = mNetworkForNetId.get(msg.arg2);
2180 }
2181 if (nai == null) break;
2182
2183 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2184 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2185 if (nai.lastValidated && reevaluationRequired) {
2186 nai.networkMonitor.sendMessage(
2187 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2188 }
2189 break;
2190 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002191 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002192 return true;
2193 }
2194
Calvin Onbe96da12016-10-11 15:10:46 -07002195 private int getCaptivePortalMode() {
2196 return Settings.Global.getInt(mContext.getContentResolver(),
2197 Settings.Global.CAPTIVE_PORTAL_MODE,
2198 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2199 }
2200
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002201 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2202 switch (msg.what) {
2203 default:
2204 return false;
2205 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2206 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2207 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2208 handleLingerComplete(nai);
2209 }
2210 break;
2211 }
2212 }
2213 return true;
2214 }
2215
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002216 @Override
2217 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002218 if (!maybeHandleAsyncChannelMessage(msg) &&
2219 !maybeHandleNetworkMonitorMessage(msg) &&
2220 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002221 maybeHandleNetworkAgentMessage(msg);
2222 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002223 }
2224 }
2225
Erik Klinea24d4592018-01-11 21:07:29 +09002226 private void handlePrivateDnsSettingsChanged() {
2227 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2228
2229 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2230 // Private DNS only ever applies to networks that might provide
2231 // Internet access and therefore also require validation.
2232 if (!NetworkMonitor.isValidationRequired(
2233 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2234 continue;
2235 }
2236
2237 // Notify the NetworkMonitor thread in case it needs to cancel or
2238 // schedule DNS resolutions. If a DNS resolution is required the
2239 // result will be sent back to us.
2240 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2241
2242 if (!cfg.inStrictMode()) {
2243 // No strict mode hostname DNS resolution needed, so just update
2244 // DNS settings directly. In opportunistic and "off" modes this
2245 // just reprograms netd with the network-supplied DNS servers
2246 // (and of course the boolean of whether or not to attempt TLS).
2247 //
2248 // TODO: Consider code flow parity with strict mode, i.e. having
2249 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2250 // performing this call at that time.
2251 updatePrivateDns(nai, cfg);
2252 }
2253 }
2254 }
2255
2256 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2257 final boolean reevaluationRequired = true;
2258 final boolean dontReevaluate = false;
2259
2260 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2261 updateDnses(nai.linkProperties, null, nai.network.netId);
2262
2263 if (newCfg == null) {
2264 if (oldCfg == null) return dontReevaluate;
2265 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2266 }
2267
2268 if (oldCfg == null) {
2269 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2270 }
2271
2272 if (oldCfg.useTls != newCfg.useTls) {
2273 return reevaluationRequired;
2274 }
2275
2276 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2277 return reevaluationRequired;
2278 }
2279
2280 return dontReevaluate;
2281 }
2282
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002283 private void updateLingerState(NetworkAgentInfo nai, long now) {
2284 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2285 // 2. If the network was lingering and there are now requests, unlinger it.
2286 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2287 // one lingered request, start lingering.
2288 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002289 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002290 if (DBG) log("Unlingering " + nai.name());
2291 nai.unlinger();
2292 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002293 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002294 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002295 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002296 nai.linger();
2297 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2298 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2299 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002300 }
2301
Robert Greenwalt7b816022014-04-18 15:25:25 -07002302 private void handleAsyncChannelHalfConnect(Message msg) {
2303 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002304 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002305 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2306 if (VDBG) log("NetworkFactory connected");
2307 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002308 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002309 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002310 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002311 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002312 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002313 }
2314 } else {
2315 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002316 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002317 }
2318 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2319 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2320 if (VDBG) log("NetworkAgent connected");
2321 // A network agent has requested a connection. Establish the connection.
2322 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2323 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2324 } else {
2325 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002326 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002327 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002328 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002329 synchronized (mNetworkForNetId) {
2330 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002331 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002332 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002333 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002334 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002335 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002336 }
2337 }
2338 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002339
Robert Greenwalt7b816022014-04-18 15:25:25 -07002340 private void handleAsyncChannelDisconnected(Message msg) {
2341 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2342 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002343 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002344 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002345 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002346 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002347 // TODO - if we move the logic to the network agent (have them disconnect
2348 // because they lost all their requests or because their score isn't good)
2349 // then they would disconnect organically, report their new state and then
2350 // disconnect the channel.
2351 if (nai.networkInfo.isConnected()) {
2352 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2353 null, null);
2354 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002355 final boolean wasDefault = isDefaultNetwork(nai);
2356 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002357 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002358 // Log default network disconnection before required book-keeping.
2359 // Let rematchAllNetworksAndRequests() below record a new default network event
2360 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2361 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002362 long now = SystemClock.elapsedRealtime();
2363 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002364 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002365 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002366 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2367 // by other networks that are already connected. Perhaps that can be done by
2368 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2369 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002370 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002371 mKeepaliveTracker.handleStopAllKeepalives(nai,
2372 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002373 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2374 // Disable wakeup packet monitoring for each interface.
2375 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2376 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002377 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002378 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002379 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002380 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002381 // Remove the NetworkAgent, but don't mark the netId as
2382 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002383 mNetworkForNetId.remove(nai.network.netId);
2384 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002385 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002386 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2387 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002388 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002389 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002390 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002391 sendUpdatedScoreToFactories(request, 0);
2392 }
2393 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002394 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002395 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002396 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002397 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002398 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002399 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002400 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002401 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002402 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002403 if (nai.created) {
2404 // Tell netd to clean up the configuration for this network
2405 // (routing rules, DNS, etc).
2406 // This may be slow as it requires a lot of netd shelling out to ip and
2407 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2408 // after we've rematched networks with requests which should make a potential
2409 // fallback network the default or requested a new network from the
2410 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2411 // long time.
2412 try {
2413 mNetd.removeNetwork(nai.network.netId);
2414 } catch (Exception e) {
2415 loge("Exception removing network: " + e);
2416 }
Erik Klinea24d4592018-01-11 21:07:29 +09002417 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002418 }
2419 synchronized (mNetworkForNetId) {
2420 mNetIdInUse.delete(nai.network.netId);
2421 }
2422 } else {
2423 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2424 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002425 }
2426 }
2427
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002428 // If this method proves to be too slow then we can maintain a separate
2429 // pendingIntent => NetworkRequestInfo map.
2430 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2431 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2432 Intent intent = pendingIntent.getIntent();
2433 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2434 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2435 if (existingPendingIntent != null &&
2436 existingPendingIntent.getIntent().filterEquals(intent)) {
2437 return entry.getValue();
2438 }
2439 }
2440 return null;
2441 }
2442
2443 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2444 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2445
2446 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2447 if (existingRequest != null) { // remove the existing request.
2448 if (DBG) log("Replacing " + existingRequest.request + " with "
2449 + nri.request + " because their intents matched.");
2450 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2451 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002452 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002453 }
2454
Erik Klineda4bfa82015-04-30 12:58:40 +09002455 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002456 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002457 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002458 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002459 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002460 if (nri.request.networkCapabilities.hasSignalStrength() &&
2461 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2462 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002463 }
2464 }
2465 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002466 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002467 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002468 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002469 }
2470 }
2471
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002472 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2473 int callingUid) {
2474 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2475 if (nri != null) {
2476 handleReleaseNetworkRequest(nri.request, callingUid);
2477 }
2478 }
2479
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002480 // Determines whether the network is the best (or could become the best, if it validated), for
2481 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2482 // on the value of reason:
2483 //
2484 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2485 // then it should be torn down.
2486 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2487 // then it should be lingered.
2488 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2489 final int numRequests;
2490 switch (reason) {
2491 case TEARDOWN:
2492 numRequests = nai.numRequestNetworkRequests();
2493 break;
2494 case LINGER:
2495 numRequests = nai.numForegroundNetworkRequests();
2496 break;
2497 default:
2498 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2499 return true;
2500 }
2501
2502 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002503 return false;
2504 }
Paul Jensene0988542015-06-25 15:30:08 -04002505 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002506 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2507 // Background requests don't affect lingering.
2508 continue;
2509 }
2510
Paul Jensene0988542015-06-25 15:30:08 -04002511 // If this Network is already the highest scoring Network for a request, or if
2512 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002513 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002514 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002515 // Note that this catches two important cases:
2516 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2517 // is currently satisfying the request. This is desirable when
2518 // cellular ends up validating but WiFi does not.
2519 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002520 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002521 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002522 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002523 nai.getCurrentScoreAsValidated())) {
2524 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002525 }
2526 }
Paul Jensene0988542015-06-25 15:30:08 -04002527 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002528 }
2529
Erik Klineacdd6392016-07-07 16:50:58 +09002530 private NetworkRequestInfo getNriForAppRequest(
2531 NetworkRequest request, int callingUid, String requestedOperation) {
2532 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2533
Robert Greenwalt9258c642014-03-26 16:47:06 -07002534 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002535 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002536 log(String.format("UID %d attempted to %s for unowned request %s",
2537 callingUid, requestedOperation, nri));
2538 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002539 }
Erik Klineacdd6392016-07-07 16:50:58 +09002540 }
2541
2542 return nri;
2543 }
2544
Erik Kline57faba92015-11-25 12:49:38 +09002545 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002546 if (mNetworkRequests.get(nri.request) == null) {
2547 return;
Erik Kline57faba92015-11-25 12:49:38 +09002548 }
Hugo Benichicd952782017-09-20 11:20:14 +09002549 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002550 return;
2551 }
2552 if (VDBG || (DBG && nri.request.isRequest())) {
2553 log("releasing " + nri.request + " (timeout)");
2554 }
2555 handleRemoveNetworkRequest(nri);
2556 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002557 }
2558
Erik Klineacdd6392016-07-07 16:50:58 +09002559 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002560 final NetworkRequestInfo nri =
2561 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2562 if (nri == null) {
2563 return;
Erik Kline57faba92015-11-25 12:49:38 +09002564 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002565 if (VDBG || (DBG && nri.request.isRequest())) {
2566 log("releasing " + nri.request + " (release request)");
2567 }
2568 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002569 }
Erik Klineacdd6392016-07-07 16:50:58 +09002570
Hugo Benichidba33db2017-03-23 22:40:44 +09002571 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002572 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002573 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002574
Erik Klineacdd6392016-07-07 16:50:58 +09002575 synchronized (mUidToNetworkRequestCount) {
2576 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2577 if (requests < 1) {
2578 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2579 nri.mUid);
2580 } else if (requests == 1) {
2581 mUidToNetworkRequestCount.removeAt(
2582 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2583 } else {
2584 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2585 }
2586 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002587
Erik Klineacdd6392016-07-07 16:50:58 +09002588 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2589 if (nri.request.isRequest()) {
2590 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002591 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002592 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002593 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002594 nai.removeRequest(nri.request.requestId);
2595 if (VDBG) {
2596 log(" Removing from current network " + nai.name() +
2597 ", leaving " + nai.numNetworkRequests() + " requests.");
2598 }
2599 // If there are still lingered requests on this network, don't tear it down,
2600 // but resume lingering instead.
2601 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002602 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002603 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2604 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002605 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002606 wasKept = true;
2607 }
Hugo Benichicd952782017-09-20 11:20:14 +09002608 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002609 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2610 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002611 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002612 }
Erik Klineacdd6392016-07-07 16:50:58 +09002613 }
2614
2615 // TODO: remove this code once we know that the Slog.wtf is never hit.
2616 //
2617 // Find all networks that are satisfying this request and remove the request
2618 // from their request lists.
2619 // TODO - it's my understanding that for a request there is only a single
2620 // network satisfying it, so this loop is wasteful
2621 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2622 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2623 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2624 otherNai.name() + ", but mNetworkAgentInfos says " +
2625 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002626 }
2627 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002628
Erik Klineacdd6392016-07-07 16:50:58 +09002629 // Maintain the illusion. When this request arrived, we might have pretended
2630 // that a network connected to serve it, even though the network was already
2631 // connected. Now that this request has gone away, we might have to pretend
2632 // that the network disconnected. LegacyTypeTracker will generate that
2633 // phantom disconnect for this type.
2634 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2635 boolean doRemove = true;
2636 if (wasKept) {
2637 // check if any of the remaining requests for this network are for the
2638 // same legacy type - if so, don't remove the nai
2639 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2640 NetworkRequest otherRequest = nai.requestAt(i);
2641 if (otherRequest.legacyType == nri.request.legacyType &&
2642 otherRequest.isRequest()) {
2643 if (DBG) log(" still have other legacy request - leaving");
2644 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002645 }
2646 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002647 }
2648
Erik Klineacdd6392016-07-07 16:50:58 +09002649 if (doRemove) {
2650 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002651 }
2652 }
Erik Klineacdd6392016-07-07 16:50:58 +09002653
2654 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2655 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2656 nri.request);
2657 }
2658 } else {
2659 // listens don't have a singular affectedNetwork. Check all networks to see
2660 // if this listen request applies and remove it.
2661 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2662 nai.removeRequest(nri.request.requestId);
2663 if (nri.request.networkCapabilities.hasSignalStrength() &&
2664 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2665 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2666 }
2667 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002668 }
2669 }
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,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002675 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002676 }
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(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002712 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002713 }
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
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002745 @Override
2746 public void startCaptivePortalApp(Network network) {
2747 enforceConnectivityInternalPermission();
2748 mHandler.post(() -> {
2749 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2750 if (nai == null) return;
2751 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2752 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2753 });
2754 }
2755
Hugo Benichic8e9e122016-09-14 23:23:08 +00002756 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002757 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002758 }
2759
Erik Kline065ab6e2016-10-02 18:02:14 +09002760 private void rematchForAvoidBadWifiUpdate() {
2761 rematchAllNetworksAndRequests(null, 0);
2762 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2763 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2764 sendUpdatedScoreToFactories(nai);
2765 }
2766 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002767 }
2768
Erik Kline065ab6e2016-10-02 18:02:14 +09002769 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002770 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002771 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002772 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002773 if (!configRestrict) {
2774 pw.println("Bad Wi-Fi avoidance: unrestricted");
2775 return;
2776 }
2777
2778 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2779 pw.increaseIndent();
2780 pw.println("Config restrict: " + configRestrict);
2781
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002782 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002783 String description;
2784 // Can't use a switch statement because strings are legal case labels, but null is not.
2785 if ("0".equals(value)) {
2786 description = "get stuck";
2787 } else if (value == null) {
2788 description = "prompt";
2789 } else if ("1".equals(value)) {
2790 description = "avoid";
2791 } else {
2792 description = value + " (?)";
2793 }
2794 pw.println("User setting: " + description);
2795 pw.println("Network overrides:");
2796 pw.increaseIndent();
2797 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2798 if (nai.avoidUnvalidated) {
2799 pw.println(nai.name());
2800 }
2801 }
2802 pw.decreaseIndent();
2803 pw.decreaseIndent();
2804 }
2805
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002806 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2807 final String action;
2808 switch (type) {
2809 case NO_INTERNET:
2810 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2811 break;
2812 case LOST_INTERNET:
2813 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2814 break;
2815 default:
2816 Slog.wtf(TAG, "Unknown notification type " + type);
2817 return;
2818 }
2819
2820 Intent intent = new Intent(action);
2821 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2822 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2823 intent.setClassName("com.android.settings",
2824 "com.android.settings.wifi.WifiNoInternetDialog");
2825
2826 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2827 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2828 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2829 }
2830
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002831 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002832 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002833 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2834
2835 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2836 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002837 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002838 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002839 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2840 return;
2841 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002842 showValidationNotification(nai, NotificationType.NO_INTERNET);
2843 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002844
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002845 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2846 NetworkCapabilities nc = nai.networkCapabilities;
2847 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002848
Erik Kline065ab6e2016-10-02 18:02:14 +09002849 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002850 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002851 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2852 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002853 }
2854
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002855 @Override
2856 public int getMultipathPreference(Network network) {
2857 enforceAccessPermission();
2858
2859 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002860 if (nai != null && nai.networkCapabilities
2861 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002862 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2863 }
2864
2865 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2866 }
2867
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002868 private class InternalHandler extends Handler {
2869 public InternalHandler(Looper looper) {
2870 super(looper);
2871 }
2872
2873 @Override
2874 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002875 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002876 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002877 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002878 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002879 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002880 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002881 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002882 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002883 break;
2884 }
Jason Monkdecd2952013-10-10 14:02:51 -04002885 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002886 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002887 break;
2888 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002889 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002890 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2891 break;
2892 }
2893 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2894 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002895 break;
2896 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002897 case EVENT_REGISTER_NETWORK_AGENT: {
2898 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2899 break;
2900 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002901 case EVENT_REGISTER_NETWORK_REQUEST:
2902 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002903 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002904 break;
2905 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002906 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2907 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002908 handleRegisterNetworkRequestWithIntent(msg);
2909 break;
2910 }
Erik Kline57faba92015-11-25 12:49:38 +09002911 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2912 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2913 handleTimedOutNetworkRequest(nri);
2914 break;
2915 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002916 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2917 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2918 break;
2919 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002920 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002921 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002922 break;
2923 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002924 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002925 Network network = (Network) msg.obj;
2926 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002927 break;
2928 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002929 case EVENT_SET_AVOID_UNVALIDATED: {
2930 handleSetAvoidUnvalidated((Network) msg.obj);
2931 break;
2932 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002933 case EVENT_PROMPT_UNVALIDATED: {
2934 handlePromptUnvalidated((Network) msg.obj);
2935 break;
2936 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002937 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2938 handleMobileDataAlwaysOn();
2939 break;
2940 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002941 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2942 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2943 mKeepaliveTracker.handleStartKeepalive(msg);
2944 break;
2945 }
2946 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2947 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2948 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2949 int slot = msg.arg1;
2950 int reason = msg.arg2;
2951 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2952 break;
2953 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002954 case EVENT_SYSTEM_READY: {
2955 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2956 nai.networkMonitor.systemReady = true;
2957 }
2958 break;
2959 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002960 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002961 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002962 break;
2963 }
Erik Klinea24d4592018-01-11 21:07:29 +09002964 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
2965 handlePrivateDnsSettingsChanged();
2966 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002967 }
2968 }
2969 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002970
2971 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002972 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002973 public int tether(String iface, String callerPkg) {
2974 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002975 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002976 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002977 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002978 } else {
2979 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2980 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002981 }
2982
2983 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002984 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002985 public int untether(String iface, String callerPkg) {
2986 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002987
2988 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002989 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002990 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002991 } else {
2992 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2993 }
2994 }
2995
2996 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002997 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002998 public int getLastTetherError(String iface) {
2999 enforceTetherAccessPermission();
3000
3001 if (isTetheringSupported()) {
3002 return mTethering.getLastTetherError(iface);
3003 } else {
3004 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3005 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003006 }
3007
3008 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003009 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003010 public String[] getTetherableUsbRegexs() {
3011 enforceTetherAccessPermission();
3012 if (isTetheringSupported()) {
3013 return mTethering.getTetherableUsbRegexs();
3014 } else {
3015 return new String[0];
3016 }
3017 }
3018
Lorenzo Colitti18660282016-07-04 12:55:44 +09003019 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003020 public String[] getTetherableWifiRegexs() {
3021 enforceTetherAccessPermission();
3022 if (isTetheringSupported()) {
3023 return mTethering.getTetherableWifiRegexs();
3024 } else {
3025 return new String[0];
3026 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003027 }
3028
Lorenzo Colitti18660282016-07-04 12:55:44 +09003029 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003030 public String[] getTetherableBluetoothRegexs() {
3031 enforceTetherAccessPermission();
3032 if (isTetheringSupported()) {
3033 return mTethering.getTetherableBluetoothRegexs();
3034 } else {
3035 return new String[0];
3036 }
3037 }
3038
Lorenzo Colitti18660282016-07-04 12:55:44 +09003039 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003040 public int setUsbTethering(boolean enable, String callerPkg) {
3041 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003042 if (isTetheringSupported()) {
3043 return mTethering.setUsbTethering(enable);
3044 } else {
3045 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3046 }
3047 }
3048
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003049 // TODO - move iface listing, queries, etc to new module
3050 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003051 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003052 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003053 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003054 return mTethering.getTetherableIfaces();
3055 }
3056
Lorenzo Colitti18660282016-07-04 12:55:44 +09003057 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003058 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003059 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003060 return mTethering.getTetheredIfaces();
3061 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003062
Lorenzo Colitti18660282016-07-04 12:55:44 +09003063 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003064 public String[] getTetheringErroredIfaces() {
3065 enforceTetherAccessPermission();
3066 return mTethering.getErroredIfaces();
3067 }
3068
Lorenzo Colitti18660282016-07-04 12:55:44 +09003069 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003070 public String[] getTetheredDhcpRanges() {
3071 enforceConnectivityInternalPermission();
3072 return mTethering.getTetheredDhcpRanges();
3073 }
3074
Udam Sainic3b640c2017-06-07 12:06:28 -07003075 @Override
3076 public boolean isTetheringSupported(String callerPkg) {
3077 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3078 return isTetheringSupported();
3079 }
3080
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003081 // if ro.tether.denied = true we default to no tethering
3082 // gservices could set the secure setting to 1 though to enable it on a build where it
3083 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003084 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003085 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3086 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3087 Settings.Global.TETHER_SUPPORTED, defaultVal));
3088 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003089 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003090
3091 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3092 boolean adminUser = false;
3093 final long token = Binder.clearCallingIdentity();
3094 try {
3095 adminUser = mUserManager.isAdminUser();
3096 } finally {
3097 Binder.restoreCallingIdentity(token);
3098 }
3099
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003100 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003101 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003102
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003103 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003104 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3105 String callerPkg) {
3106 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003107 if (!isTetheringSupported()) {
3108 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3109 return;
3110 }
3111 mTethering.startTethering(type, receiver, showProvisioningUi);
3112 }
3113
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003114 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003115 public void stopTethering(int type, String callerPkg) {
3116 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003117 mTethering.stopTethering(type);
3118 }
3119
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003120 // Called when we lose the default network and have no replacement yet.
3121 // This will automatically be cleared after X seconds or a new default network
3122 // becomes CONNECTED, whichever happens first. The timer is started by the
3123 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003124 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003125 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003126 if (mNetTransitionWakeLock.isHeld()) {
3127 return;
3128 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003129 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003130 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3131 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003132 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003133 mWakelockLogs.log("ACQUIRE for " + forWhom);
3134 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3135 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003136 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003137
Hugo Benichi4c31b342017-03-30 23:18:10 +09003138 // Called when we gain a new default network to release the network transition wakelock in a
3139 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3140 // message is cancelled.
3141 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003142 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003143 if (!mNetTransitionWakeLock.isHeld()) {
3144 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003145 }
3146 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003147 // Cancel self timeout on wakelock hold.
3148 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3149 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3150 mHandler.sendMessageDelayed(msg, 1000);
3151 }
3152
3153 // Called when either message of ensureNetworkTransitionWakelock or
3154 // scheduleReleaseNetworkTransitionWakelock is processed.
3155 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3156 String event = eventName(eventId);
3157 synchronized (this) {
3158 if (!mNetTransitionWakeLock.isHeld()) {
3159 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3160 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3161 return;
3162 }
3163 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003164 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3165 mTotalWakelockDurationMs += lockDuration;
3166 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3167 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003168 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003169 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003170 }
3171
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003172 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003173 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003174 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003175 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003176 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003177 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003178 }
3179
Lorenzo Colitti18660282016-07-04 12:55:44 +09003180 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003181 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003182 enforceAccessPermission();
3183 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003184 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003185 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003186 mHandler.sendMessage(
3187 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3188 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003189
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003190 private void handleReportNetworkConnectivity(
3191 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003192 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003193 if (network == null) {
3194 nai = getDefaultNetwork();
3195 } else {
3196 nai = getNetworkAgentInfoForNetwork(network);
3197 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003198 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3199 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3200 return;
3201 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003202 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003203 if (hasConnectivity == nai.lastValidated) {
3204 return;
3205 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003206 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003207 int netid = nai.network.netId;
3208 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003209 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003210 // Validating a network that has not yet connected could result in a call to
3211 // rematchNetworkAndRequests() which is not meant to work on such networks.
3212 if (!nai.everConnected) {
3213 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003214 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003215 LinkProperties lp = getLinkProperties(nai);
3216 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3217 return;
3218 }
3219 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003220 }
3221
Paul Jensencee9b512015-05-06 07:32:40 -04003222 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003223 // this information is already available as a world read/writable jvm property
3224 // so this API change wouldn't have a benifit. It also breaks the passing
3225 // of proxy info to all the JVMs.
3226 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003227 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003228 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003229 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3230 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003231 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003232 }
3233
Lorenzo Colitti18660282016-07-04 12:55:44 +09003234 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003235 public ProxyInfo getProxyForNetwork(Network network) {
3236 if (network == null) return getDefaultProxy();
3237 final ProxyInfo globalProxy = getGlobalProxy();
3238 if (globalProxy != null) return globalProxy;
3239 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3240 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3241 // caller may not have.
3242 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3243 if (nai == null) return null;
3244 synchronized (nai) {
3245 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3246 if (proxyInfo == null) return null;
3247 return new ProxyInfo(proxyInfo);
3248 }
3249 }
3250
Paul Jensene0bef712014-12-10 15:12:18 -05003251 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3252 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3253 // proxy is null then there is no proxy in place).
3254 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3255 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3256 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3257 proxy = null;
3258 }
3259 return proxy;
3260 }
3261
3262 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3263 // better for determining if a new proxy broadcast is necessary:
3264 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3265 // avoid unnecessary broadcasts.
3266 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3267 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3268 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3269 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3270 // all set.
3271 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3272 a = canonicalizeProxyInfo(a);
3273 b = canonicalizeProxyInfo(b);
3274 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3275 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3276 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3277 }
3278
Jason Monk207900c2014-04-25 15:00:09 -04003279 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003280 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003281
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003282 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003283 if (proxyProperties == mGlobalProxy) return;
3284 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3285 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3286
3287 String host = "";
3288 int port = 0;
3289 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003290 String pacFileUrl = "";
3291 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003292 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003293 if (!proxyProperties.isValid()) {
3294 if (DBG)
3295 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3296 return;
3297 }
Jason Monk207900c2014-04-25 15:00:09 -04003298 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003299 host = mGlobalProxy.getHost();
3300 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003301 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003302 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003303 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003304 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003305 } else {
3306 mGlobalProxy = null;
3307 }
3308 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003309 final long token = Binder.clearCallingIdentity();
3310 try {
3311 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3312 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3313 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3314 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003315 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003316 } finally {
3317 Binder.restoreCallingIdentity(token);
3318 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003319
Jason Monkcf0f97a2014-10-02 15:39:38 -04003320 if (mGlobalProxy == null) {
3321 proxyProperties = mDefaultProxy;
3322 }
3323 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003324 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003325 }
3326
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003327 private void loadGlobalProxy() {
3328 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003329 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3330 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3331 String exclList = Settings.Global.getString(res,
3332 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003333 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3334 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003335 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003336 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003337 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003338 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003339 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003340 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003341 if (!proxyProperties.isValid()) {
3342 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3343 return;
3344 }
3345
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003346 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003347 mGlobalProxy = proxyProperties;
3348 }
3349 }
3350 }
3351
Jason Monk207900c2014-04-25 15:00:09 -04003352 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003353 // this information is already available as a world read/writable jvm property
3354 // so this API change wouldn't have a benifit. It also breaks the passing
3355 // of proxy info to all the JVMs.
3356 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003357 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003358 return mGlobalProxy;
3359 }
3360 }
3361
Jason Monk207900c2014-04-25 15:00:09 -04003362 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003363 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003364 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003365 proxy = null;
3366 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003367 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003368 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003369 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003370 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003371 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3372 return;
3373 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003374
3375 // This call could be coming from the PacManager, containing the port of the local
3376 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3377 // global (to get the correct local port), and send a broadcast.
3378 // TODO: Switch PacManager to have its own message to send back rather than
3379 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003380 if ((mGlobalProxy != null) && (proxy != null)
3381 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003382 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3383 mGlobalProxy = proxy;
3384 sendProxyBroadcast(mGlobalProxy);
3385 return;
3386 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003387 mDefaultProxy = proxy;
3388
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003389 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003390 if (!mDefaultProxyDisabled) {
3391 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003392 }
3393 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003394 }
3395
Paul Jensene0bef712014-12-10 15:12:18 -05003396 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3397 // This method gets called when any network changes proxy, but the broadcast only ever contains
3398 // the default proxy (even if it hasn't changed).
3399 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3400 // world where an app might be bound to a non-default network.
3401 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3402 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3403 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3404
3405 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3406 sendProxyBroadcast(getDefaultProxy());
3407 }
3408 }
3409
Robert Greenwalt434203a2010-10-11 16:00:27 -07003410 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003411 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3412 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003413 if (!TextUtils.isEmpty(proxy)) {
3414 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003415 if (data.length == 0) {
3416 return;
3417 }
3418
Robert Greenwalt434203a2010-10-11 16:00:27 -07003419 String proxyHost = data[0];
3420 int proxyPort = 8080;
3421 if (data.length > 1) {
3422 try {
3423 proxyPort = Integer.parseInt(data[1]);
3424 } catch (NumberFormatException e) {
3425 return;
3426 }
3427 }
Jason Monk207900c2014-04-25 15:00:09 -04003428 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003429 setGlobalProxy(p);
3430 }
3431 }
3432
Jason Monk207900c2014-04-25 15:00:09 -04003433 private void sendProxyBroadcast(ProxyInfo proxy) {
3434 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003435 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003436 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003437 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003438 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3439 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003440 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003441 final long ident = Binder.clearCallingIdentity();
3442 try {
3443 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3444 } finally {
3445 Binder.restoreCallingIdentity(ident);
3446 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003447 }
3448
3449 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003450 final private HashMap<Uri, Integer> mUriEventMap;
3451 final private Context mContext;
3452 final private Handler mHandler;
3453
3454 SettingsObserver(Context context, Handler handler) {
3455 super(null);
3456 mUriEventMap = new HashMap<Uri, Integer>();
3457 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003458 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003459 }
3460
Erik Klineda4bfa82015-04-30 12:58:40 +09003461 void observe(Uri uri, int what) {
3462 mUriEventMap.put(uri, what);
3463 final ContentResolver resolver = mContext.getContentResolver();
3464 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003465 }
3466
3467 @Override
3468 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003469 Slog.wtf(TAG, "Should never be reached.");
3470 }
3471
3472 @Override
3473 public void onChange(boolean selfChange, Uri uri) {
3474 final Integer what = mUriEventMap.get(uri);
3475 if (what != null) {
3476 mHandler.obtainMessage(what.intValue()).sendToTarget();
3477 } else {
3478 loge("No matching event to send for URI=" + uri);
3479 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003480 }
3481 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003482
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003483 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003484 Slog.d(TAG, s);
3485 }
3486
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003487 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003488 Slog.e(TAG, s);
3489 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003490
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003491 private static void loge(String s, Throwable t) {
3492 Slog.e(TAG, s, t);
3493 }
3494
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003495 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003496 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003497 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3498 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3499 *
3500 * @param oldPackage Package name of the application which currently controls VPN, which will
3501 * be replaced. If there is no such application, this should should either be
3502 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3503 * @param newPackage Package name of the application which should gain control of VPN, or
3504 * {@code null} to disable.
3505 * @param userId User for whom to prepare the new VPN.
3506 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003507 * @hide
3508 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003509 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003510 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3511 int userId) {
3512 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003513
Hugo Benichi20035e02017-04-26 14:53:28 +09003514 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003515 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003516 Vpn vpn = mVpns.get(userId);
3517 if (vpn != null) {
3518 return vpn.prepare(oldPackage, newPackage);
3519 } else {
3520 return false;
3521 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003522 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003523 }
3524
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003525 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003526 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3527 * This method is used by system-privileged apps.
3528 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3529 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3530 *
3531 * @param packageName The package for which authorization state should change.
3532 * @param userId User for whom {@code packageName} is installed.
3533 * @param authorized {@code true} if this app should be able to start a VPN connection without
3534 * explicit user approval, {@code false} if not.
3535 *
Jeff Davidson05542602014-08-11 14:07:27 -07003536 * @hide
3537 */
3538 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003539 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3540 enforceCrossUserPermission(userId);
3541
Hugo Benichi20035e02017-04-26 14:53:28 +09003542 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003543 Vpn vpn = mVpns.get(userId);
3544 if (vpn != null) {
3545 vpn.setPackageAuthorization(packageName, authorized);
3546 }
Jeff Davidson05542602014-08-11 14:07:27 -07003547 }
3548 }
3549
3550 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003551 * Configure a TUN interface and return its file descriptor. Parameters
3552 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003553 * and not available in ConnectivityManager. Permissions are checked in
3554 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003555 * @hide
3556 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003557 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003558 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003559 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003560 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003561 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003562 return mVpns.get(user).establish(config);
3563 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003564 }
3565
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003566 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003567 * Start legacy VPN, controlling native daemons as needed. Creates a
3568 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003569 */
3570 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003571 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003572 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003573 final LinkProperties egress = getActiveLinkProperties();
3574 if (egress == null) {
3575 throw new IllegalStateException("Missing active network connection");
3576 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003577 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003578 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003579 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3580 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003581 }
3582
3583 /**
3584 * Return the information of the ongoing legacy VPN. This method is used
3585 * by VpnSettings and not available in ConnectivityManager. Permissions
3586 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003587 */
3588 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003589 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3590 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003591
Hugo Benichi20035e02017-04-26 14:53:28 +09003592 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003593 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003594 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003595 }
3596
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003597 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003598 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3599 * and not available in ConnectivityManager.
3600 */
3601 @Override
3602 public VpnInfo[] getAllVpnInfo() {
3603 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003604 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003605 if (mLockdownEnabled) {
3606 return new VpnInfo[0];
3607 }
3608
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003609 List<VpnInfo> infoList = new ArrayList<>();
3610 for (int i = 0; i < mVpns.size(); i++) {
3611 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3612 if (info != null) {
3613 infoList.add(info);
3614 }
3615 }
3616 return infoList.toArray(new VpnInfo[infoList.size()]);
3617 }
3618 }
3619
3620 /**
3621 * @return VPN information for accounting, or null if we can't retrieve all required
3622 * information, e.g primary underlying iface.
3623 */
3624 @Nullable
3625 private VpnInfo createVpnInfo(Vpn vpn) {
3626 VpnInfo info = vpn.getVpnInfo();
3627 if (info == null) {
3628 return null;
3629 }
3630 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3631 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3632 // the underlyingNetworks list.
3633 if (underlyingNetworks == null) {
3634 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3635 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3636 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3637 }
3638 } else if (underlyingNetworks.length > 0) {
3639 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3640 if (linkProperties != null) {
3641 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3642 }
3643 }
3644 return info.primaryUnderlyingIface == null ? null : info;
3645 }
3646
3647 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003648 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3649 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003650 * Permissions are checked in Vpn class.
3651 * @hide
3652 */
3653 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003654 public VpnConfig getVpnConfig(int userId) {
3655 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003656 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003657 Vpn vpn = mVpns.get(userId);
3658 if (vpn != null) {
3659 return vpn.getVpnConfig();
3660 } else {
3661 return null;
3662 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003663 }
3664 }
3665
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003666 @Override
3667 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003668 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3669 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3670 return false;
3671 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003672
Hugo Benichi69744342017-11-27 10:57:16 +09003673 synchronized (mVpns) {
3674 // Tear down existing lockdown if profile was removed
3675 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3676 if (mLockdownEnabled) {
3677 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3678 if (profileTag == null) {
3679 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3680 return false;
3681 }
3682 String profileName = new String(profileTag);
3683 final VpnProfile profile = VpnProfile.decode(
3684 profileName, mKeyStore.get(Credentials.VPN + profileName));
3685 if (profile == null) {
3686 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3687 setLockdownTracker(null);
3688 return true;
3689 }
3690 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003691 Vpn vpn = mVpns.get(user);
3692 if (vpn == null) {
3693 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3694 return false;
3695 }
3696 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003697 } else {
3698 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003699 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003700 }
3701
3702 return true;
3703 }
3704
3705 /**
3706 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3707 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3708 */
Hugo Benichi69744342017-11-27 10:57:16 +09003709 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003710 private void setLockdownTracker(LockdownVpnTracker tracker) {
3711 // Shutdown any existing tracker
3712 final LockdownVpnTracker existing = mLockdownTracker;
3713 mLockdownTracker = null;
3714 if (existing != null) {
3715 existing.shutdown();
3716 }
3717
Robin Leec3736bc2017-03-10 16:19:54 +00003718 if (tracker != null) {
3719 mLockdownTracker = tracker;
3720 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003721 }
3722 }
3723
Hugo Benichi69744342017-11-27 10:57:16 +09003724 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003725 private void throwIfLockdownEnabled() {
3726 if (mLockdownEnabled) {
3727 throw new IllegalStateException("Unavailable in lockdown mode");
3728 }
3729 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003730
Robin Lee244ce8e2016-01-05 18:03:46 +00003731 /**
Robin Lee17e61832016-05-09 13:46:28 +01003732 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3733 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003734 *
Robin Lee17e61832016-05-09 13:46:28 +01003735 * @return {@code true} if the service was started, the service was already connected, or there
3736 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003737 */
Robin Lee17e61832016-05-09 13:46:28 +01003738 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003739 synchronized (mVpns) {
3740 Vpn vpn = mVpns.get(userId);
3741 if (vpn == null) {
3742 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3743 // exists already.
3744 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3745 return false;
3746 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003747
Robin Lee812800c2016-05-13 15:38:08 +01003748 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003749 }
3750 }
3751
3752 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003753 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3754 enforceSettingsPermission();
3755 enforceCrossUserPermission(userId);
3756
3757 synchronized (mVpns) {
3758 Vpn vpn = mVpns.get(userId);
3759 if (vpn == null) {
3760 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3761 return false;
3762 }
3763 return vpn.isAlwaysOnPackageSupported(packageName);
3764 }
3765 }
3766
3767 @Override
Robin Leedc679712016-05-03 13:23:03 +01003768 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003769 enforceConnectivityInternalPermission();
3770 enforceCrossUserPermission(userId);
3771
Robin Lee244ce8e2016-01-05 18:03:46 +00003772 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003773 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3774 if (LockdownVpnTracker.isEnabled()) {
3775 return false;
3776 }
3777
Robin Lee244ce8e2016-01-05 18:03:46 +00003778 Vpn vpn = mVpns.get(userId);
3779 if (vpn == null) {
3780 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3781 return false;
3782 }
Robin Lee17e61832016-05-09 13:46:28 +01003783 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003784 return false;
3785 }
Robin Lee17e61832016-05-09 13:46:28 +01003786 if (!startAlwaysOnVpn(userId)) {
3787 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003788 return false;
3789 }
3790 }
3791 return true;
3792 }
3793
3794 @Override
3795 public String getAlwaysOnVpnPackage(int userId) {
3796 enforceConnectivityInternalPermission();
3797 enforceCrossUserPermission(userId);
3798
3799 synchronized (mVpns) {
3800 Vpn vpn = mVpns.get(userId);
3801 if (vpn == null) {
3802 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3803 return null;
3804 }
3805 return vpn.getAlwaysOnPackage();
3806 }
3807 }
3808
Wink Savilleab9321d2013-06-29 21:10:57 -07003809 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003810 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003811 // TODO: Remove? Any reason to trigger a provisioning check?
3812 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003813 }
3814
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003815 /** Location to an updatable file listing carrier provisioning urls.
3816 * An example:
3817 *
3818 * <?xml version="1.0" encoding="utf-8"?>
3819 * <provisioningUrls>
3820 * <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 -07003821 * </provisioningUrls>
3822 */
3823 private static final String PROVISIONING_URL_PATH =
3824 "/data/misc/radio/provisioning_urls.xml";
3825 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003826
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003827 /** XML tag for root element. */
3828 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3829 /** XML tag for individual url */
3830 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003831 /** XML attribute for mcc */
3832 private static final String ATTR_MCC = "mcc";
3833 /** XML attribute for mnc */
3834 private static final String ATTR_MNC = "mnc";
3835
Paul Jensen434dde82015-06-11 09:43:30 -04003836 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003837 FileReader fileReader = null;
3838 XmlPullParser parser = null;
3839 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003840
3841 try {
3842 fileReader = new FileReader(mProvisioningUrlFile);
3843 parser = Xml.newPullParser();
3844 parser.setInput(fileReader);
3845 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3846
3847 while (true) {
3848 XmlUtils.nextElement(parser);
3849
3850 String element = parser.getName();
3851 if (element == null) break;
3852
Paul Jensen434dde82015-06-11 09:43:30 -04003853 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003854 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3855 try {
3856 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3857 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3858 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3859 parser.next();
3860 if (parser.getEventType() == XmlPullParser.TEXT) {
3861 return parser.getText();
3862 }
3863 }
3864 }
3865 } catch (NumberFormatException e) {
3866 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3867 }
3868 }
3869 }
3870 return null;
3871 } catch (FileNotFoundException e) {
3872 loge("Carrier Provisioning Urls file not found");
3873 } catch (XmlPullParserException e) {
3874 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3875 } catch (IOException e) {
3876 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3877 } finally {
3878 if (fileReader != null) {
3879 try {
3880 fileReader.close();
3881 } catch (IOException e) {}
3882 }
3883 }
3884 return null;
3885 }
3886
Wink Saville42d4f082013-07-20 20:31:59 -07003887 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003888 public String getMobileProvisioningUrl() {
3889 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003890 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003891 if (TextUtils.isEmpty(url)) {
3892 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003893 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003894 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003895 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003896 }
Wink Saville8cf35602013-07-10 23:00:07 -07003897 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003898 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003899 String phoneNumber = mTelephonyManager.getLine1Number();
3900 if (TextUtils.isEmpty(phoneNumber)) {
3901 phoneNumber = "0000000000";
3902 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003903 url = String.format(url,
3904 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3905 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003906 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003907 }
3908
Wink Savilleab9321d2013-06-29 21:10:57 -07003909 return url;
3910 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003911
Wink Saville948282b2013-08-29 08:55:16 -07003912 @Override
3913 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003914 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003915 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003916 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3917 return;
3918 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003919 final long ident = Binder.clearCallingIdentity();
3920 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003921 // Concatenate the range of types onto the range of NetIDs.
3922 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3923 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003924 } finally {
3925 Binder.restoreCallingIdentity(ident);
3926 }
Wink Saville948282b2013-08-29 08:55:16 -07003927 }
Wink Saville7788c612013-08-29 14:57:08 -07003928
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003929 @Override
3930 public void setAirplaneMode(boolean enable) {
3931 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003932 final long ident = Binder.clearCallingIdentity();
3933 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003934 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003935 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003936 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3937 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003938 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003939 } finally {
3940 Binder.restoreCallingIdentity(ident);
3941 }
3942 }
3943
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003944 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003945 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003946 Vpn userVpn = mVpns.get(userId);
3947 if (userVpn != null) {
3948 loge("Starting user already has a VPN");
3949 return;
3950 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003951 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003952 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003953 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3954 updateLockdownVpn();
3955 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003956 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003957 }
3958
3959 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003960 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003961 Vpn userVpn = mVpns.get(userId);
3962 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003963 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003964 return;
3965 }
Robin Lee17e61832016-05-09 13:46:28 +01003966 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003967 mVpns.delete(userId);
3968 }
3969 }
3970
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003971 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003972 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003973 final int vpnsSize = mVpns.size();
3974 for (int i = 0; i < vpnsSize; i++) {
3975 Vpn vpn = mVpns.valueAt(i);
3976 vpn.onUserAdded(userId);
3977 }
3978 }
3979 }
3980
3981 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003982 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003983 final int vpnsSize = mVpns.size();
3984 for (int i = 0; i < vpnsSize; i++) {
3985 Vpn vpn = mVpns.valueAt(i);
3986 vpn.onUserRemoved(userId);
3987 }
3988 }
3989 }
3990
Robin Lee89e7a692016-02-29 14:38:17 +00003991 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09003992 synchronized (mVpns) {
3993 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3994 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3995 updateLockdownVpn();
3996 } else {
3997 startAlwaysOnVpn(userId);
3998 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003999 }
4000 }
4001
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004002 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4003 @Override
4004 public void onReceive(Context context, Intent intent) {
4005 final String action = intent.getAction();
4006 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4007 if (userId == UserHandle.USER_NULL) return;
4008
Robin Lee323f29d2016-05-04 16:38:06 +01004009 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004010 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004011 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004012 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004013 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4014 onUserAdded(userId);
4015 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4016 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004017 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4018 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004019 }
4020 }
4021 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004022
Robin Lee95204e02017-01-27 11:59:22 +00004023 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4024 @Override
4025 public void onReceive(Context context, Intent intent) {
4026 // Try creating lockdown tracker, since user present usually means
4027 // unlocked keystore.
4028 updateLockdownVpn();
4029 mContext.unregisterReceiver(this);
4030 }
4031 };
4032
Robert Greenwalta67be032014-05-16 15:49:14 -07004033 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4034 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004035 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4036 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004037
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004038 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4039 // Map from UID to number of NetworkRequests that UID has filed.
4040 @GuardedBy("mUidToNetworkRequestCount")
4041 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4042
Robert Greenwalta67be032014-05-16 15:49:14 -07004043 private static class NetworkFactoryInfo {
4044 public final String name;
4045 public final Messenger messenger;
4046 public final AsyncChannel asyncChannel;
4047
4048 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4049 this.name = name;
4050 this.messenger = messenger;
4051 this.asyncChannel = asyncChannel;
4052 }
4053 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004054
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004055 private void ensureNetworkRequestHasType(NetworkRequest request) {
4056 if (request.type == NetworkRequest.Type.NONE) {
4057 throw new IllegalArgumentException(
4058 "All NetworkRequests in ConnectivityService must have a type");
4059 }
4060 }
4061
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004062 /**
4063 * Tracks info about the requester.
4064 * Also used to notice when the calling process dies so we can self-expire
4065 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004066 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004067 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004068 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004069 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004070 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004071 final int mPid;
4072 final int mUid;
4073 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004074
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004075 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004076 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004077 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004078 mPendingIntent = pi;
4079 messenger = null;
4080 mBinder = null;
4081 mPid = getCallingPid();
4082 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004083 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004084 }
4085
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004086 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004087 super();
4088 messenger = m;
4089 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004090 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004091 mBinder = binder;
4092 mPid = getCallingPid();
4093 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004094 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004095 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004096
4097 try {
4098 mBinder.linkToDeath(this, 0);
4099 } catch (RemoteException e) {
4100 binderDied();
4101 }
4102 }
4103
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004104 private void enforceRequestCountLimit() {
4105 synchronized (mUidToNetworkRequestCount) {
4106 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4107 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004108 throw new ServiceSpecificException(
4109 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004110 }
4111 mUidToNetworkRequestCount.put(mUid, networkRequests);
4112 }
4113 }
4114
Robert Greenwalt9258c642014-03-26 16:47:06 -07004115 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004116 if (mBinder != null) {
4117 mBinder.unlinkToDeath(this, 0);
4118 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004119 }
4120
4121 public void binderDied() {
4122 log("ConnectivityService NetworkRequestInfo binderDied(" +
4123 request + ", " + mBinder + ")");
4124 releaseNetworkRequest(request);
4125 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004126
4127 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004128 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004129 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004130 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004131 }
4132
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004133 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4134 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4135 if (badCapability != null) {
4136 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004137 }
4138 }
4139
Erik Kline9d598e12015-07-13 16:37:51 +09004140 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004141 final SortedSet<Integer> thresholds = new TreeSet();
4142 synchronized (nai) {
4143 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4144 if (nri.request.networkCapabilities.hasSignalStrength() &&
4145 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4146 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4147 }
4148 }
4149 }
Erik Kline9d598e12015-07-13 16:37:51 +09004150 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004151 }
4152
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004153 private void updateSignalStrengthThresholds(
4154 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4155 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004156 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004157 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4158
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004159 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004160 String detail;
4161 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4162 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4163 } else {
4164 detail = reason;
4165 }
4166 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4167 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4168 }
4169
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004170 nai.asyncChannel.sendMessage(
4171 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004172 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004173 }
4174
Etan Cohen859748f2017-04-03 17:42:34 -07004175 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4176 if (nc == null) {
4177 return;
4178 }
4179 NetworkSpecifier ns = nc.getNetworkSpecifier();
4180 if (ns == null) {
4181 return;
4182 }
4183 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4184 ns.assertValidFromUid(Binder.getCallingUid());
4185 }
4186
Robert Greenwalt9258c642014-03-26 16:47:06 -07004187 @Override
4188 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004189 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004190 final NetworkRequest.Type type = (networkCapabilities == null)
4191 ? NetworkRequest.Type.TRACK_DEFAULT
4192 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004193 // If the requested networkCapabilities is null, take them instead from
4194 // the default network request. This allows callers to keep track of
4195 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004196 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004197 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004198 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004199 enforceAccessPermission();
4200 } else {
4201 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4202 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004203 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4204 // of the app when the request is filed, but we never change the request if the app
4205 // changes network state. http://b/29964605
4206 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004207 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004208 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004209 // Set the UID range for this request to the single UID of the requester.
4210 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4211 // are no visible methods to set the UIDs, an app could use reflection to try and get
4212 // networks for other apps so it's essential that the UIDs are overwritten.
4213 // TODO : don't forcefully set the UID when communicating with processes
4214 // that have the NETWORK_SETTINGS permission.
4215 networkCapabilities.setSingleUid(Binder.getCallingUid());
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004216
Etan Cohenba07c8c2017-02-05 10:42:27 -08004217 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004218 throw new IllegalArgumentException("Bad timeout specified");
4219 }
Etan Cohen859748f2017-04-03 17:42:34 -07004220 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004221
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004222 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004223 nextNetworkRequestId(), type);
4224 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004225 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004226
4227 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004228 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004229 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004230 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004231 }
4232 return networkRequest;
4233 }
4234
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004235 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004236 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004237 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004238 } else {
4239 enforceChangePermission();
4240 }
4241 }
4242
fenglub15e72b2015-03-20 11:29:56 -07004243 @Override
fengludb571472015-04-21 17:12:05 -07004244 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004245 enforceAccessPermission();
4246 NetworkAgentInfo nai = null;
4247 if (network == null) {
4248 return false;
4249 }
4250 synchronized (mNetworkForNetId) {
4251 nai = mNetworkForNetId.get(network.netId);
4252 }
4253 if (nai != null) {
4254 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4255 return true;
4256 }
4257 return false;
4258 }
4259
Felipe Lemeee27cab2016-06-20 16:36:29 -07004260 private boolean isSystem(int uid) {
4261 return uid < Process.FIRST_APPLICATION_UID;
4262 }
fenglub15e72b2015-03-20 11:29:56 -07004263
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004264 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004265 final int uid = Binder.getCallingUid();
4266 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004267 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004268 return;
4269 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004270 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4271 // Policy already enforced.
4272 return;
4273 }
4274 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4275 // If UID is restricted, don't allow them to bring up metered APNs.
4276 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004277 }
4278 }
4279
Robert Greenwalt9258c642014-03-26 16:47:06 -07004280 @Override
4281 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4282 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004283 checkNotNull(operation, "PendingIntent cannot be null.");
4284 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4285 enforceNetworkRequestPermissions(networkCapabilities);
4286 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004287 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004288 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004289 // TODO : don't forcefully set the UID when communicating with processes
4290 // that have the NETWORK_SETTINGS permission.
4291 networkCapabilities.setSingleUid(Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004292
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004293 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004294 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4295 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004296 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004297 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4298 nri));
4299 return networkRequest;
4300 }
4301
Jeremy Joslin79294842014-12-03 17:15:28 -08004302 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4303 mHandler.sendMessageDelayed(
4304 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4305 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4306 }
4307
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004308 @Override
4309 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004310 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004311 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4312 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004313 }
4314
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004315 // In order to implement the compatibility measure for pre-M apps that call
4316 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4317 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4318 // This ensures it has permission to do so.
4319 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4320 if (nc == null) {
4321 return false;
4322 }
4323 int[] transportTypes = nc.getTransportTypes();
4324 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4325 return false;
4326 }
4327 try {
4328 mContext.enforceCallingOrSelfPermission(
4329 android.Manifest.permission.ACCESS_WIFI_STATE,
4330 "ConnectivityService");
4331 } catch (SecurityException e) {
4332 return false;
4333 }
4334 return true;
4335 }
4336
Robert Greenwalt9258c642014-03-26 16:47:06 -07004337 @Override
4338 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4339 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004340 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4341 enforceAccessPermission();
4342 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004343
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004344 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004345 // TODO : don't forcefully set the UIDs when communicating with processes
4346 // that have the NETWORK_SETTINGS permission.
4347 nc.setSingleUid(Binder.getCallingUid());
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004348 if (!ConnectivityManager.checkChangePermission(mContext)) {
4349 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4350 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4351 // onLost and onAvailable callbacks when networks move in and out of the background.
4352 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4353 // can't request networks.
4354 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4355 }
Etan Cohen859748f2017-04-03 17:42:34 -07004356 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004357
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004358 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004359 NetworkRequest.Type.LISTEN);
4360 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004361 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004362
4363 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4364 return networkRequest;
4365 }
4366
4367 @Override
4368 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4369 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004370 checkNotNull(operation, "PendingIntent cannot be null.");
4371 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4372 enforceAccessPermission();
4373 }
Etan Cohen859748f2017-04-03 17:42:34 -07004374 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004375
Chalard Jeandda156a2018-01-10 21:19:32 +09004376 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4377 // TODO : don't forcefully set the UIDs when communicating with processes
4378 // that have the NETWORK_SETTINGS permission.
4379 nc.setSingleUid(Binder.getCallingUid());
4380
4381 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004382 NetworkRequest.Type.LISTEN);
4383 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004384 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004385
4386 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004387 }
4388
Erik Klineacdd6392016-07-07 16:50:58 +09004389 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004390 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004391 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004392 mHandler.sendMessage(mHandler.obtainMessage(
4393 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004394 }
4395
4396 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004397 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004398 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004399 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4400 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004401 }
4402
Robert Greenwalta67be032014-05-16 15:49:14 -07004403 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004404 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004405 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4406 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4407 }
4408
4409 @Override
4410 public void unregisterNetworkFactory(Messenger messenger) {
4411 enforceConnectivityInternalPermission();
4412 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4413 }
4414
4415 private void handleUnregisterNetworkFactory(Messenger messenger) {
4416 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4417 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004418 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004419 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004420 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004421 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004422 }
4423
Robert Greenwalt7b816022014-04-18 15:25:25 -07004424 /**
4425 * NetworkAgentInfo supporting a request by requestId.
4426 * These have already been vetted (their Capabilities satisfy the request)
4427 * and the are the highest scored network available.
4428 * the are keyed off the Requests requestId.
4429 */
Hugo Benichicd952782017-09-20 11:20:14 +09004430 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4431 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004432 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4433 new SparseArray<NetworkAgentInfo>();
4434
Paul Jensen31a94f42015-02-13 14:18:39 -05004435 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4436 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004437 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4438 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004439 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4440 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4441 // there may not be a strict 1:1 correlation between the two.
4442 @GuardedBy("mNetworkForNetId")
4443 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004444
Robert Greenwalt7b816022014-04-18 15:25:25 -07004445 // NetworkAgentInfo keyed off its connecting messenger
4446 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004447 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004448 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4449 new HashMap<Messenger, NetworkAgentInfo>();
4450
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004451 @GuardedBy("mBlockedAppUids")
4452 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4453
Paul Jensen2c311d62014-11-17 12:34:51 -05004454 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004455 private final NetworkRequest mDefaultRequest;
4456
Erik Klineda4bfa82015-04-30 12:58:40 +09004457 // Request used to optionally keep mobile data active even when higher
4458 // priority networks like Wi-Fi are active.
4459 private final NetworkRequest mDefaultMobileDataRequest;
4460
Hugo Benichicd952782017-09-20 11:20:14 +09004461 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4462 synchronized (mNetworkForRequestId) {
4463 return mNetworkForRequestId.get(requestId);
4464 }
4465 }
4466
4467 private void clearNetworkForRequest(int requestId) {
4468 synchronized (mNetworkForRequestId) {
4469 mNetworkForRequestId.remove(requestId);
4470 }
4471 }
4472
4473 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4474 synchronized (mNetworkForRequestId) {
4475 mNetworkForRequestId.put(requestId, nai);
4476 }
4477 }
4478
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004479 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004480 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004481 }
4482
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004483 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004484 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004485 }
4486
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004487 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4488 return nri.request.requestId == mDefaultRequest.requestId;
4489 }
4490
Paul Jensen31a94f42015-02-13 14:18:39 -05004491 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004493 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004494 enforceConnectivityInternalPermission();
4495
Rubin Xu1bb5c082017-09-05 18:40:49 +01004496 LinkProperties lp = new LinkProperties(linkProperties);
4497 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004498 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4499 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004500 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004501 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4502 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004503 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004504 synchronized (this) {
4505 nai.networkMonitor.systemReady = mSystemReady;
4506 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004507 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4508 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004509 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004510 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004511 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004512 }
4513
4514 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4515 if (VDBG) log("Got NetworkAgent Messenger");
4516 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004517 synchronized (mNetworkForNetId) {
4518 mNetworkForNetId.put(na.network.netId, na);
4519 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004520 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4521 NetworkInfo networkInfo = na.networkInfo;
4522 na.networkInfo = null;
4523 updateNetworkInfo(na, networkInfo);
Chalard Jeanf213ca12018-01-16 18:43:05 +09004524 updateUids(na, null, na.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004525 }
4526
4527 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4528 LinkProperties newLp = networkAgent.linkProperties;
4529 int netId = networkAgent.network.netId;
4530
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004531 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4532 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004533 if (networkAgent.clatd != null) {
4534 networkAgent.clatd.fixupLinkProperties(oldLp);
4535 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004536
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004537 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004538 updateMtu(newLp, oldLp);
4539 // TODO - figure out what to do for clat
4540// for (LinkProperties lp : newLp.getStackedLinks()) {
4541// updateMtu(lp, null);
4542// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004543 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004544
Erik Kline94887872016-04-05 13:30:49 +09004545 updateRoutes(newLp, oldLp, netId);
4546 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004547
Hugo Benichib577d652017-06-27 15:13:20 +09004548 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004549 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004550 if (isDefaultNetwork(networkAgent)) {
4551 handleApplyDefaultProxy(newLp.getHttpProxy());
4552 } else {
4553 updateProxy(newLp, oldLp, networkAgent);
4554 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004555 // TODO - move this check to cover the whole function
4556 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004557 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004558 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4559 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004560
4561 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004562 }
4563
Joel Scherpelz668370b2017-06-08 15:35:21 +09004564 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004565 // Marks are only available on WiFi interaces. Checking for
4566 // marks on unsupported interfaces is harmless.
4567 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4568 return;
4569 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004570
Joel Scherpelz668370b2017-06-08 15:35:21 +09004571 int mark = mContext.getResources().getInteger(
4572 com.android.internal.R.integer.config_networkWakeupPacketMark);
4573 int mask = mContext.getResources().getInteger(
4574 com.android.internal.R.integer.config_networkWakeupPacketMask);
4575
4576 // Mask/mark of zero will not detect anything interesting.
4577 // Don't install rules unless both values are nonzero.
4578 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004579 return;
4580 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004581
4582 final String prefix = "iface:" + iface;
4583 try {
4584 if (add) {
4585 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4586 } else {
4587 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4588 }
4589 } catch (Exception e) {
4590 loge("Exception modifying wakeup packet monitoring: " + e);
4591 }
4592
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004593 }
4594
4595 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4596 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004597 CompareResult<String> interfaceDiff = new CompareResult<String>(
4598 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4599 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004600 for (String iface : interfaceDiff.added) {
4601 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004602 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004603 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004604 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004605 } catch (Exception e) {
4606 loge("Exception adding interface: " + e);
4607 }
4608 }
4609 for (String iface : interfaceDiff.removed) {
4610 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004611 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004612 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004613 mNetd.removeInterfaceFromNetwork(iface, netId);
4614 } catch (Exception e) {
4615 loge("Exception removing interface: " + e);
4616 }
4617 }
4618 }
4619
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004620 /**
4621 * Have netd update routes from oldLp to newLp.
4622 * @return true if routes changed between oldLp and newLp
4623 */
4624 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004625 // Compare the route diff to determine which routes should be added and removed.
4626 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4627 oldLp != null ? oldLp.getAllRoutes() : null,
4628 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004629
4630 // add routes before removing old in case it helps with continuous connectivity
4631
4632 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4633 for (RouteInfo route : routeDiff.added) {
4634 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004635 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004636 try {
4637 mNetd.addRoute(netId, route);
4638 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004639 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4640 loge("Exception in addRoute for non-gateway: " + e);
4641 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004642 }
4643 }
4644 for (RouteInfo route : routeDiff.added) {
4645 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004646 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004647 try {
4648 mNetd.addRoute(netId, route);
4649 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004650 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4651 loge("Exception in addRoute for gateway: " + e);
4652 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004653 }
4654 }
4655
4656 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004657 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004658 try {
4659 mNetd.removeRoute(netId, route);
4660 } catch (Exception e) {
4661 loge("Exception in removeRoute: " + e);
4662 }
4663 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004664 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004665 }
Erik Kline41368502015-06-17 13:19:54 +09004666
Erik Kline94887872016-04-05 13:30:49 +09004667 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4668 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4669 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004670 }
Erik Kline94887872016-04-05 13:30:49 +09004671
Erik Kline1742fe12017-12-13 19:40:49 +09004672 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4673 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4674
Erik Klinea24d4592018-01-11 21:07:29 +09004675 if (DBG) {
4676 final Collection<InetAddress> dnses = newLp.getDnsServers();
4677 log("Setting DNS servers for network " + netId + " to " + dnses);
4678 }
Erik Kline94887872016-04-05 13:30:49 +09004679 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004680 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004681 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004682 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004683 }
Erik Kline4edba012017-04-07 15:29:29 +09004684 }
4685
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004686 private String getNetworkPermission(NetworkCapabilities nc) {
4687 // TODO: make these permission strings AIDL constants instead.
4688 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4689 return NetworkManagementService.PERMISSION_SYSTEM;
4690 }
4691 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4692 return NetworkManagementService.PERMISSION_NETWORK;
4693 }
4694 return null;
4695 }
4696
Paul Jensen3d194ea2015-06-16 14:27:36 -04004697 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004698 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4699 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4700 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004701 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004702 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004703 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004704 if (nai.everConnected &&
4705 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4706 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004707 // does not cause any request (that is not a listen) currently matching that agent to
4708 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004709 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004710 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004711 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004712 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004713 }
4714
Paul Jensen3d194ea2015-06-16 14:27:36 -04004715 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004716 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004717 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004718 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004719 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004720 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004721 }
Paul Jensene0988542015-06-25 15:30:08 -04004722 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004723 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004724 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004725 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004726 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004727 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004728 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004729 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004730 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004731 }
4732
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004733 return newNc;
4734 }
4735
4736 /**
4737 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4738 *
4739 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4740 * capabilities we manage and store in {@code nai}, such as validated status and captive
4741 * portal status)
4742 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4743 * potentially triggers rematches.
4744 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4745 * change.)
4746 *
4747 * @param oldScore score of the network before any of the changes that prompted us
4748 * to call this function.
4749 * @param nai the network having its capabilities updated.
4750 * @param nc the new network capabilities.
4751 */
4752 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4753 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4754
4755 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004756
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004757 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004758 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004759 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004760 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004761 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004762 } catch (RemoteException e) {
4763 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004764 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004765 }
4766
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004767 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004768 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004769 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004770 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004771 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004772
Chalard Jeanf213ca12018-01-16 18:43:05 +09004773 updateUids(nai, prevNc, newNc);
4774
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004775 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004776 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4777 // the change we're processing can't affect any requests, it can only affect the listens
4778 // on this network. We might have been called by rematchNetworkAndRequests when a
4779 // network changed foreground state.
4780 processListenRequests(nai, true);
4781 } else {
4782 // If the requestable capabilities have changed or the score changed, we can't have been
4783 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004784 rematchAllNetworksAndRequests(nai, oldScore);
4785 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004786 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004787
4788 // Report changes that are interesting for network statistics tracking.
4789 if (prevNc != null) {
4790 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004791 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004792 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004793 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004794 if (meteredChanged || roamingChanged) {
4795 notifyIfacesChangedForNetworkStats();
4796 }
4797 }
4798
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004799 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004800 // Tell VPNs about updated capabilities, since they may need to
4801 // bubble those changes through.
4802 synchronized (mVpns) {
4803 for (int i = 0; i < mVpns.size(); i++) {
4804 final Vpn vpn = mVpns.valueAt(i);
4805 vpn.updateCapabilities();
4806 }
4807 }
4808 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004809 }
4810
Chalard Jeanf213ca12018-01-16 18:43:05 +09004811 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4812 NetworkCapabilities newNc) {
4813 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4814 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4815 if (null == prevRanges) prevRanges = new ArraySet<>();
4816 if (null == newRanges) newRanges = new ArraySet<>();
4817 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4818
4819 prevRanges.removeAll(newRanges);
4820 newRanges.removeAll(prevRangesCopy);
4821
4822 try {
4823 if (!newRanges.isEmpty()) {
4824 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4825 newRanges.toArray(addedRangesArray);
4826 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4827 }
4828 if (!prevRanges.isEmpty()) {
4829 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4830 prevRanges.toArray(removedRangesArray);
4831 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4832 }
4833 } catch (Exception e) {
4834 // Never crash!
4835 loge("Exception in updateUids: " + e);
4836 }
4837 }
4838
Hugo Benichief502882017-09-01 01:23:32 +00004839 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4840 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4841 // Ignore updates for disconnected networks
4842 return;
4843 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004844 // newLp is already a defensive copy.
4845 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004846 if (VDBG) {
4847 log("Update of LinkProperties for " + nai.name() +
4848 "; created=" + nai.created +
4849 "; everConnected=" + nai.everConnected);
4850 }
4851 LinkProperties oldLp = nai.linkProperties;
4852 synchronized (nai) {
4853 nai.linkProperties = newLp;
4854 }
4855 if (nai.everConnected) {
4856 updateLinkProperties(nai, oldLp);
4857 }
4858 }
4859
Paul Jensenc8b9a742014-09-30 15:37:41 -04004860 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004861 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4862 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004863 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004864 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004865 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4866 }
4867 }
4868
Robert Greenwalt7b816022014-04-18 15:25:25 -07004869 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4870 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004871 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004872 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4873 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004874 }
4875 }
4876
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004877 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4878 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004879 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004880 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004881 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4882 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004883 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004884 sendIntent(nri.mPendingIntent, intent);
4885 }
4886 // else not handled
4887 }
4888
4889 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4890 mPendingIntentWakeLock.acquire();
4891 try {
4892 if (DBG) log("Sending " + pendingIntent);
4893 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4894 } catch (PendingIntent.CanceledException e) {
4895 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4896 mPendingIntentWakeLock.release();
4897 releasePendingNetworkRequest(pendingIntent);
4898 }
4899 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4900 }
4901
4902 @Override
4903 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4904 String resultData, Bundle resultExtras) {
4905 if (DBG) log("Finished sending " + pendingIntent);
4906 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004907 // Release with a delay so the receiving client has an opportunity to put in its
4908 // own request.
4909 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004910 }
4911
Hugo Benichidba33db2017-03-23 22:40:44 +09004912 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004913 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004914 if (nri.messenger == null) {
4915 return; // Default request has no msgr
4916 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004917 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004918 // TODO: check if defensive copies of data is needed.
4919 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004920 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004921 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4922 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004923 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004924 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004925 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004926 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004927 break;
4928 }
4929 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeandda156a2018-01-10 21:19:32 +09004930 final NetworkCapabilities nc =
4931 new NetworkCapabilities(networkAgent.networkCapabilities);
4932 // TODO : don't remove the UIDs when communicating with processes
4933 // that have the NETWORK_SETTINGS permission.
4934 nc.setSingleUid(nri.mUid);
4935 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004936 break;
4937 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004938 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004939 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004940 break;
4941 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004942 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004943 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004944 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004945 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004946 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004947 String notification = ConnectivityManager.getCallbackName(notificationType);
4948 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004949 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004950 nri.messenger.send(msg);
4951 } catch (RemoteException e) {
4952 // may occur naturally in the race of binder death.
4953 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4954 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004955 }
4956
Hugo Benichidba33db2017-03-23 22:40:44 +09004957 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4958 bundle.putParcelable(t.getClass().getSimpleName(), t);
4959 }
4960
Paul Jensenc8b9a742014-09-30 15:37:41 -04004961 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004962 if (nai.numRequestNetworkRequests() != 0) {
4963 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4964 NetworkRequest nr = nai.requestAt(i);
4965 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004966 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004967 loge("Dead network still had at least " + nr);
4968 break;
4969 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004970 }
4971 nai.asyncChannel.disconnect();
4972 }
4973
Robert Greenwalt7b816022014-04-18 15:25:25 -07004974 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4975 if (oldNetwork == null) {
4976 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4977 return;
4978 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004979 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004980
4981 // If we get here it means that the last linger timeout for this network expired. So there
4982 // must be no other active linger timers, and we must stop lingering.
4983 oldNetwork.clearLingerState();
4984
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004985 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004986 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004987 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004988 } else {
4989 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004990 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4991 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004992 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004993 }
4994
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004995 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004996 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004997 setupDataActivityTracking(newNetwork);
4998 try {
4999 mNetd.setDefaultNetId(newNetwork.network.netId);
5000 } catch (Exception e) {
5001 loge("Exception setting default network :" + e);
5002 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005003
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005004 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005005 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005006 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005007 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005008 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005009 }
5010
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005011 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005012 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5013 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5014 NetworkRequest nr = nri.request;
5015 if (!nr.isListen()) continue;
5016 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5017 nai.removeRequest(nri.request.requestId);
5018 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5019 }
5020 }
5021
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005022 if (capabilitiesChanged) {
5023 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5024 }
5025
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005026 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5027 NetworkRequest nr = nri.request;
5028 if (!nr.isListen()) continue;
5029 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5030 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005031 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005032 }
5033 }
5034 }
5035
Paul Jensen2161a8e2014-09-11 11:00:39 -04005036 // Handles a network appearing or improving its score.
5037 //
5038 // - Evaluates all current NetworkRequests that can be
5039 // satisfied by newNetwork, and reassigns to newNetwork
5040 // any such requests for which newNetwork is the best.
5041 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005042 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005043 // needed. A network is needed if it is the best network for
5044 // one or more NetworkRequests, or if it is a VPN.
5045 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005046 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005047 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005048 //
5049 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5050 // networks that have no chance (i.e. even if validated)
5051 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005052 //
5053 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5054 // it does not remove NetworkRequests that other Networks could better satisfy.
5055 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5056 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5057 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005058 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005059 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005060 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5061 // performed to tear down unvalidated networks that have no chance (i.e. even if
5062 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005063 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005064 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005065 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005066 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005067 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005068 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005069
5070 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5071 final int score = newNetwork.getCurrentScore();
5072
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005073 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005074
Paul Jensen2161a8e2014-09-11 11:00:39 -04005075 // Find and migrate to this Network any NetworkRequests for
5076 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005077 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005078 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005079 NetworkCapabilities nc = newNetwork.networkCapabilities;
5080 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005081 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005082 // Process requests in the first pass and listens in the second pass. This allows us to
5083 // change a network's capabilities depending on which requests it has. This is only
5084 // correct if the change in capabilities doesn't affect whether the network satisfies
5085 // requests or not, and doesn't affect the network's score.
5086 if (nri.request.isListen()) continue;
5087
Hugo Benichicd952782017-09-20 11:20:14 +09005088 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005089 final boolean satisfies = newNetwork.satisfies(nri.request);
5090 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005091 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005092 log("Network " + newNetwork.name() + " was already satisfying" +
5093 " request " + nri.request.requestId + ". No change.");
5094 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005095 keep = true;
5096 continue;
5097 }
5098
5099 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005100 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005101 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005102 // next check if it's better than any current network we're using for
5103 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005104 if (VDBG) {
5105 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005106 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005107 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005108 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005109 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005110 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005111 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005112 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005113 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005114 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005115 affectedNetworks.add(currentNetwork);
5116 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005117 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005118 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005119 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005120 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005121 if (!newNetwork.addRequest(nri.request)) {
5122 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5123 }
5124 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005125 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005126 // Tell NetworkFactories about the new score, so they can stop
5127 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005128 // TODO - this could get expensive if we have alot of requests for this
5129 // network. Think about if there is a way to reduce this. Push
5130 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005131 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005132 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005133 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005134 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005135 if (currentNetwork != null) {
5136 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5137 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005138 }
5139 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005140 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005141 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5142 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005143 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005144 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5145 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5146 // This means this code doesn't have to handle the case where "currentNetwork" no
5147 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5148 if (DBG) {
5149 log("Network " + newNetwork.name() + " stopped satisfying" +
5150 " request " + nri.request.requestId);
5151 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005152 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005153 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005154 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005155 sendUpdatedScoreToFactories(nri.request, 0);
5156 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005157 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5158 newNetwork.name() +
5159 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005160 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005161 // TODO: Technically, sending CALLBACK_LOST here is
5162 // incorrect if there is a replacement network currently
5163 // connected that can satisfy nri, which is a request
5164 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005165 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5166 // so this code is only incorrect for a network that loses
5167 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005168 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005169 }
5170 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005171 if (isNewDefault) {
5172 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005173 makeDefault(newNetwork);
5174 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005175 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005176 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005177 // Have a new default network, release the transition wakelock in
5178 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005179 }
5180
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005181 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5182 Slog.wtf(TAG, String.format(
5183 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005184 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005185 }
5186 if (newNetwork.getCurrentScore() != score) {
5187 Slog.wtf(TAG, String.format(
5188 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005189 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005190 }
5191
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005192 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005193 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5194 // If the network went from background to foreground or vice versa, we need to update
5195 // its foreground state. It is safe to do this after rematching the requests because
5196 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5197 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005198 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005199 } else {
5200 processListenRequests(newNetwork, false);
5201 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005202
Paul Jensencf4c2c62015-07-01 14:16:32 -04005203 // do this after the default net is switched, but
5204 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005205 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005206
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005207 // Linger any networks that are no longer needed. This should be done after sending the
5208 // available callback for newNetwork.
5209 for (NetworkAgentInfo nai : affectedNetworks) {
5210 updateLingerState(nai, now);
5211 }
5212 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5213 // does not need to be done in any particular order.
5214 updateLingerState(newNetwork, now);
5215
Paul Jensencf4c2c62015-07-01 14:16:32 -04005216 if (isNewDefault) {
5217 // Maintain the illusion: since the legacy API only
5218 // understands one network at a time, we must pretend
5219 // that the current default network disconnected before
5220 // the new one connected.
5221 if (oldDefaultNetwork != null) {
5222 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5223 oldDefaultNetwork, true);
5224 }
5225 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5226 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5227 notifyLockdownVpn(newNetwork);
5228 }
5229
Robert Greenwalt7b816022014-04-18 15:25:25 -07005230 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005231 // Notify battery stats service about this network, both the normal
5232 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005233 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005234 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005235 final IBatteryStats bs = BatteryStatsService.getService();
5236 final int type = newNetwork.networkInfo.getType();
5237
5238 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5239 bs.noteNetworkInterfaceType(baseIface, type);
5240 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5241 final String stackedIface = stacked.getInterfaceName();
5242 bs.noteNetworkInterfaceType(stackedIface, type);
5243 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5244 }
5245 } catch (RemoteException ignored) {
5246 }
5247
Robert Greenwalt152ed372014-12-17 17:19:53 -08005248 // This has to happen after the notifyNetworkCallbacks as that tickles each
5249 // ConnectivityManager instance so that legacy requests correctly bind dns
5250 // requests to this network. The legacy users are listening for this bcast
5251 // and will generally do a dns request so they can ensureRouteToHost and if
5252 // they do that before the callbacks happen they'll use the default network.
5253 //
5254 // TODO: Is there still a race here? We send the broadcast
5255 // after sending the callback, but if the app can receive the
5256 // broadcast before the callback, it might still break.
5257 //
5258 // This *does* introduce a race where if the user uses the new api
5259 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5260 // they may get old info. Reverse this after the old startUsing api is removed.
5261 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005262 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5263 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005264 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005265 // legacy type tracker filters out repeat adds
5266 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5267 }
5268 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005269
5270 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5271 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5272 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5273 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5274 if (newNetwork.isVPN()) {
5275 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5276 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005277 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005278 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5279 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005280 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005281 if (nai.getLingerExpiry() > 0) {
5282 // This network has active linger timers and no requests, but is not
5283 // lingering. Linger it.
5284 //
5285 // One way (the only way?) this can happen if this network is unvalidated
5286 // and became unneeded due to another network improving its score to the
5287 // point where this network will no longer be able to satisfy any requests
5288 // even if it validates.
5289 updateLingerState(nai, now);
5290 } else {
5291 if (DBG) log("Reaping " + nai.name());
5292 teardownUnneededNetwork(nai);
5293 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005294 }
5295 }
5296 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005297 }
5298
Paul Jensen1c7ba022015-06-16 14:27:36 -04005299 /**
5300 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5301 * being disconnected.
5302 * @param changed If only one Network's score or capabilities have been modified since the last
5303 * time this function was called, pass this Network in this argument, otherwise pass
5304 * null.
5305 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5306 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5307 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5308 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5309 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005310 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005311 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005312 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5313 // to avoid the slowness. It is not simply enough to process just "changed", for
5314 // example in the case where "changed"'s score decreases and another network should begin
5315 // satifying a NetworkRequest that "changed" currently satisfies.
5316
5317 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5318 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5319 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005320 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005321 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005322 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005323 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005324 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5325 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5326 // Rematch higher scoring networks first to prevent requests first matching a lower
5327 // scoring network and then a higher scoring network, which could produce multiple
5328 // callbacks and inadvertently unlinger networks.
5329 Arrays.sort(nais);
5330 for (NetworkAgentInfo nai : nais) {
5331 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005332 // Only reap the last time through the loop. Reaping before all rematching
5333 // is complete could incorrectly teardown a network that hasn't yet been
5334 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005335 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005336 : ReapUnvalidatedNetworks.REAP,
5337 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005338 }
5339 }
5340 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005341
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005342 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005343 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005344 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005345 // For now only update icons for default connection.
5346 // TODO: Update WiFi and cellular icons separately. b/17237507
5347 if (!isDefaultNetwork(nai)) return;
5348
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005349 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005350 // Don't repeat publish.
5351 if (newInetCondition == mDefaultInetConditionPublished) return;
5352
5353 mDefaultInetConditionPublished = newInetCondition;
5354 sendInetConditionBroadcast(nai.networkInfo);
5355 }
5356
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005357 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005358 synchronized (mVpns) {
5359 if (mLockdownTracker != null) {
5360 if (nai != null && nai.isVPN()) {
5361 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5362 } else {
5363 mLockdownTracker.onNetworkInfoChanged();
5364 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005365 }
5366 }
5367 }
5368
Robert Greenwalt7b816022014-04-18 15:25:25 -07005369 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005370 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005371 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005372 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005373 synchronized (networkAgent) {
5374 oldInfo = networkAgent.networkInfo;
5375 networkAgent.networkInfo = newInfo;
5376 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005377 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005378
Robert Greenwalt7b816022014-04-18 15:25:25 -07005379 if (DBG) {
5380 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5381 (oldInfo == null ? "null" : oldInfo.getState()) +
5382 " to " + state);
5383 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005384
Robin Lee585e2482016-05-01 23:00:00 +01005385 if (!networkAgent.created
5386 && (state == NetworkInfo.State.CONNECTED
5387 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005388
5389 // A network that has just connected has zero requests and is thus a foreground network.
5390 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5391
Robert Greenwalt7b816022014-04-18 15:25:25 -07005392 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005393 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005394 if (networkAgent.isVPN()) {
5395 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005396 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5397 (networkAgent.networkMisc == null ||
5398 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005399 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005400 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005401 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005402 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005403 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005404 loge("Error creating network " + networkAgent.network.netId + ": "
5405 + e.getMessage());
5406 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005407 }
Paul Jenseneec75412014-08-04 12:21:19 -04005408 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005409 }
5410
5411 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5412 networkAgent.everConnected = true;
5413
Robert Greenwalt7b816022014-04-18 15:25:25 -07005414 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005415 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005416
Paul Jensenca8f16a2014-05-09 12:47:55 -04005417 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005418 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005419
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005420 if (networkAgent.isVPN()) {
5421 // Temporarily disable the default proxy (not global).
5422 synchronized (mProxyLock) {
5423 if (!mDefaultProxyDisabled) {
5424 mDefaultProxyDisabled = true;
5425 if (mGlobalProxy == null && mDefaultProxy != null) {
5426 sendProxyBroadcast(null);
5427 }
5428 }
5429 }
5430 // TODO: support proxy per network.
5431 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005432
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005433 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5434 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5435 // capabilities, so it only needs to be done once on initial connect, not every time the
5436 // network's capabilities change. Note that we do this before rematching the network,
5437 // so we could decide to tear it down immediately afterwards. That's fine though - on
5438 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5439 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005440 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005441
Paul Jensen2161a8e2014-09-11 11:00:39 -04005442 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005443 final long now = SystemClock.elapsedRealtime();
5444 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005445
5446 // This has to happen after matching the requests, because callbacks are just requests.
5447 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005448 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005449 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005450 if (networkAgent.isVPN()) {
5451 synchronized (mProxyLock) {
5452 if (mDefaultProxyDisabled) {
5453 mDefaultProxyDisabled = false;
5454 if (mGlobalProxy == null && mDefaultProxy != null) {
5455 sendProxyBroadcast(mDefaultProxy);
5456 }
5457 }
5458 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005459 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005460 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005461 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5462 state == NetworkInfo.State.SUSPENDED) {
5463 // going into or coming out of SUSPEND: rescore and notify
5464 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005465 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005466 }
5467 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5468 ConnectivityManager.CALLBACK_SUSPENDED :
5469 ConnectivityManager.CALLBACK_RESUMED));
5470 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005471 }
5472 }
5473
Robert Greenwaltac96c522014-06-03 16:43:57 -07005474 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005475 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005476 if (score < 0) {
5477 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5478 "). Bumping score to min of 0");
5479 score = 0;
5480 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005481
Paul Jensen2161a8e2014-09-11 11:00:39 -04005482 final int oldScore = nai.getCurrentScore();
5483 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005484
Paul Jensen85cf78e2015-06-25 13:25:07 -04005485 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005486
Paul Jensenc8b9a742014-09-30 15:37:41 -04005487 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005488 }
5489
Erik Klinec75d4fa2017-02-15 19:59:17 +09005490 // Notify only this one new request of the current state. Transfer all the
5491 // current state by calling NetworkCapabilities and LinkProperties callbacks
5492 // so that callers can be guaranteed to have as close to atomicity in state
5493 // transfer as can be supported by this current API.
5494 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005495 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005496 if (nri.mPendingIntent != null) {
5497 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5498 // Attempt no subsequent state pushes where intents are involved.
5499 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005500 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005501
5502 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5503 // Whether a network is currently suspended is also an important
5504 // element of state to be transferred (it would not otherwise be
5505 // delivered by any currently available mechanism).
5506 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5507 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5508 }
5509 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5510 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005511 }
5512
Robert Greenwalt8d482522015-06-24 13:23:42 -07005513 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005514 // The NetworkInfo we actually send out has no bearing on the real
5515 // state of affairs. For example, if the default connection is mobile,
5516 // and a request for HIPRI has just gone away, we need to pretend that
5517 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5518 // the state to DISCONNECTED, even though the network is of type MOBILE
5519 // and is still connected.
5520 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5521 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005522 if (state != DetailedState.DISCONNECTED) {
5523 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005524 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005525 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005526 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005527 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5528 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5529 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5530 if (info.isFailover()) {
5531 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5532 nai.networkInfo.setFailover(false);
5533 }
5534 if (info.getReason() != null) {
5535 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5536 }
5537 if (info.getExtraInfo() != null) {
5538 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5539 }
5540 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005541 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005542 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005543 if (newDefaultAgent != null) {
5544 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5545 newDefaultAgent.networkInfo);
5546 } else {
5547 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5548 }
5549 }
5550 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5551 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005552 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005553 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005554 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005555 }
5556 }
5557 }
5558
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005559 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005560 if (VDBG) {
5561 String notification = ConnectivityManager.getCallbackName(notifyType);
5562 log("notifyType " + notification + " for " + networkAgent.name());
5563 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005564 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5565 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005566 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5567 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005568 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5569 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005570 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005571 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005572 } else {
5573 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5574 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005575 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005576 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005577
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005578 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5579 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5580 }
5581
Jeff Sharkey69736342014-12-08 14:50:12 -08005582 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005583 * Returns the list of all interfaces that could be used by network traffic that does not
5584 * explicitly specify a network. This includes the default network, but also all VPNs that are
5585 * currently connected.
5586 *
5587 * Must be called on the handler thread.
5588 */
5589 private Network[] getDefaultNetworks() {
5590 ArrayList<Network> defaultNetworks = new ArrayList<>();
5591 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5592 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5593 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5594 defaultNetworks.add(nai.network);
5595 }
5596 }
5597 return defaultNetworks.toArray(new Network[0]);
5598 }
5599
5600 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005601 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5602 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005603 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005604 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005605 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005606 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005607 } catch (Exception ignored) {
5608 }
5609 }
5610
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005611 @Override
5612 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005613 int user = UserHandle.getUserId(Binder.getCallingUid());
5614 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005615 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005616 return mVpns.get(user).addAddress(address, prefixLength);
5617 }
5618 }
5619
5620 @Override
5621 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005622 int user = UserHandle.getUserId(Binder.getCallingUid());
5623 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005624 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005625 return mVpns.get(user).removeAddress(address, prefixLength);
5626 }
5627 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005628
5629 @Override
5630 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005631 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005632 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005633 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005634 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005635 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005636 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005637 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005638 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005639 }
5640 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005641 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005642
5643 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005644 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005645 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005646 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005647 }
5648
5649 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005650 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5651 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5652 enforceKeepalivePermission();
5653 mKeepaliveTracker.startNattKeepalive(
5654 getNetworkAgentInfoForNetwork(network),
5655 intervalSeconds, messenger, binder,
5656 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5657 }
5658
5659 @Override
5660 public void stopKeepalive(Network network, int slot) {
5661 mHandler.sendMessage(mHandler.obtainMessage(
5662 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5663 }
5664
5665 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005666 public void factoryReset() {
5667 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005668
5669 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5670 return;
5671 }
5672
Robin Lee3b3dd942015-05-12 18:14:58 +01005673 final int userId = UserHandle.getCallingUserId();
5674
Stuart Scottf1fb3972015-04-02 18:00:02 -07005675 // Turn airplane mode off
5676 setAirplaneMode(false);
5677
Stuart Scotte3e314d2015-04-20 14:07:45 -07005678 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5679 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005680 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005681 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005682 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005683 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005684 }
5685
Stuart Scotte3e314d2015-04-20 14:07:45 -07005686 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005687 // Remove always-on package
5688 synchronized (mVpns) {
5689 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5690 if (alwaysOnPackage != null) {
5691 setAlwaysOnVpnPackage(userId, null, false);
5692 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5693 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005694
Hugo Benichi69744342017-11-27 10:57:16 +09005695 // Turn Always-on VPN off
5696 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5697 final long ident = Binder.clearCallingIdentity();
5698 try {
5699 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5700 mLockdownEnabled = false;
5701 setLockdownTracker(null);
5702 } finally {
5703 Binder.restoreCallingIdentity(ident);
5704 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005705 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005706
Hugo Benichi69744342017-11-27 10:57:16 +09005707 // Turn VPN off
5708 VpnConfig vpnConfig = getVpnConfig(userId);
5709 if (vpnConfig != null) {
5710 if (vpnConfig.legacy) {
5711 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5712 } else {
5713 // Prevent this app (packagename = vpnConfig.user) from initiating
5714 // VPN connections in the future without user intervention.
5715 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005716
Hugo Benichi69744342017-11-27 10:57:16 +09005717 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5718 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005719 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005720 }
5721 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005722
5723 Settings.Global.putString(mContext.getContentResolver(),
5724 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005725 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005726
5727 @VisibleForTesting
5728 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5729 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5730 return new NetworkMonitor(context, handler, nai, defaultRequest);
5731 }
Erik Kline48f12f22016-04-14 17:30:59 +09005732
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005733 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005734 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5735 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005736 }
5737
5738 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005739 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5740 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5741 }
5742
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005743 @VisibleForTesting
5744 public boolean hasService(String name) {
5745 return ServiceManager.checkService(name) != null;
5746 }
5747
Hugo Benichi64901e52017-10-19 14:42:40 +09005748 @VisibleForTesting
5749 protected IpConnectivityMetrics.Logger metricsLogger() {
5750 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5751 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005752 }
5753
5754 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005755 int[] transports = nai.networkCapabilities.getTransportTypes();
5756 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005757 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005758
5759 private static boolean toBool(int encodedBoolean) {
5760 return encodedBoolean != 0; // Only 0 means false.
5761 }
5762
5763 private static int encodeBool(boolean b) {
5764 return b ? 1 : 0;
5765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005766}