blob: dc70347035ce2942b6df766ad0075597476736b6 [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
Benedict Wong8149f6e2018-01-18 18:31:45 -0800459 private static final int MIN_NET_ID = 100; // some reserved marks
460 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700461 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);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001263 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001264 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001265 }
1266 }
1267 }
1268 }
1269 }
1270 }
1271
1272 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1273 out = result.values().toArray(out);
1274 return out;
1275 }
1276
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001277 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001278 public boolean isNetworkSupported(int networkType) {
1279 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001280 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001281 }
1282
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001283 /**
1284 * Return LinkProperties for the active (i.e., connected) default
1285 * network interface. It is assumed that at most one default network
1286 * is active at a time. If more than one is active, it is indeterminate
1287 * which will be returned.
1288 * @return the ip properties for the active network, or {@code null} if
1289 * none is active
1290 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001291 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001292 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001293 enforceAccessPermission();
1294 final int uid = Binder.getCallingUid();
1295 NetworkState state = getUnfilteredActiveNetworkState(uid);
1296 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001297 }
1298
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001299 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001300 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001301 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001302 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1303 if (nai != null) {
1304 synchronized (nai) {
1305 return new LinkProperties(nai.linkProperties);
1306 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001307 }
1308 return null;
1309 }
1310
Robert Greenwalt12e67352014-05-13 21:41:06 -07001311 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001312 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001313 public LinkProperties getLinkProperties(Network network) {
1314 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001315 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1316 }
1317
1318 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1319 if (nai == null) {
1320 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001321 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001322 synchronized (nai) {
1323 return new LinkProperties(nai.linkProperties);
1324 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001325 }
1326
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001327 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001328 if (nai != null) {
1329 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001330 if (nai.networkCapabilities != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001331 // TODO : don't remove the UIDs when communicating with processes
1332 // that have the NETWORK_SETTINGS permission.
1333 return networkCapabilitiesWithoutUids(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001334 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001335 }
1336 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001337 return null;
1338 }
1339
1340 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001341 public NetworkCapabilities getNetworkCapabilities(Network network) {
1342 enforceAccessPermission();
1343 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1344 }
1345
Chalard Jeanf19db372018-01-26 19:24:40 +09001346 private NetworkCapabilities networkCapabilitiesWithoutUids(NetworkCapabilities nc) {
1347 return new NetworkCapabilities(nc).setUids(null);
1348 }
1349
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001350 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001351 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001352 // Require internal since we're handing out IMSI details
1353 enforceConnectivityInternalPermission();
1354
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001355 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001356 for (Network network : getAllNetworks()) {
1357 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1358 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001359 // TODO (b/73321673) : NetworkState contains a copy of the
1360 // NetworkCapabilities, which may contain UIDs of apps to which the
1361 // network applies. Should the UIDs be cleared so as not to leak or
1362 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001363 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001364 }
1365 }
1366 return result.toArray(new NetworkState[result.size()]);
1367 }
1368
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001369 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001370 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001371 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001372 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1373 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1374 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001375 }
1376
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001377 @Override
1378 public boolean isActiveNetworkMetered() {
1379 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001380
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001381 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1382 if (caps != null) {
1383 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1384 } else {
1385 // Always return the most conservative value
1386 return true;
1387 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001388 }
1389
Jeff Sharkey216c1812012-08-05 14:29:23 -07001390 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1391 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001392 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001393 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001394 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001395 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001396 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001397
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001398 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001399 * Ensure that a network route exists to deliver traffic to the specified
1400 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001401 * @param networkType the type of the network over which traffic to the
1402 * specified host is to be routed
1403 * @param hostAddress the IP address of the host to which the route is
1404 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 * @return {@code true} on success, {@code false} on failure
1406 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001407 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001408 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001409 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001410 if (mProtectedNetworks.contains(networkType)) {
1411 enforceConnectivityInternalPermission();
1412 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001413
Chad Brubakerc0234532014-02-14 13:24:29 -08001414 InetAddress addr;
1415 try {
1416 addr = InetAddress.getByAddress(hostAddress);
1417 } catch (UnknownHostException e) {
1418 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1419 return false;
1420 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001421
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001422 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001423 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 return false;
1425 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001426
1427 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1428 if (nai == null) {
1429 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1430 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1431 } else {
1432 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1433 }
1434 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001435 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001436
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001437 DetailedState netState;
1438 synchronized (nai) {
1439 netState = nai.networkInfo.getDetailedState();
1440 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001441
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001442 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001443 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001444 log("requestRouteToHostAddress on down network "
1445 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001446 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001447 }
1448 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001450
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001451 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001452 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001453 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001454 LinkProperties lp;
1455 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001456 synchronized (nai) {
1457 lp = nai.linkProperties;
1458 netId = nai.network.netId;
1459 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001460 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001461 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1462 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001463 } finally {
1464 Binder.restoreCallingIdentity(token);
1465 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001466 }
1467
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001468 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001469 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001470 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001471 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001472 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001473 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001474 if (bestRoute.getGateway().equals(addr)) {
1475 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001476 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001477 } else {
1478 // if we will connect to this through another route, add a direct route
1479 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001480 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001481 }
1482 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001483 if (DBG) log("Adding legacy route " + bestRoute +
1484 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001485 try {
1486 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1487 } catch (Exception e) {
1488 // never crash - catch them all
1489 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001490 return false;
1491 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001492 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001493 }
1494
Jeff Sharkey75d31892018-01-18 22:01:59 +09001495 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001496 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001497 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001498 // TODO: notify UID when it has requested targeted updates
1499 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001500 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001501 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001502 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001503 if (restrictBackground) {
1504 log("onRestrictBackgroundChanged(true): disabling tethering");
1505 mTethering.untetherAll();
1506 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001507 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001508 };
1509
Robin Lee3b3dd942015-05-12 18:14:58 +01001510 /**
1511 * Require that the caller is either in the same user or has appropriate permission to interact
1512 * across users.
1513 *
1514 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1515 */
1516 private void enforceCrossUserPermission(int userId) {
1517 if (userId == UserHandle.getCallingUserId()) {
1518 // Not a cross-user call.
1519 return;
1520 }
1521 mContext.enforceCallingOrSelfPermission(
1522 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1523 "ConnectivityService");
1524 }
1525
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001526 private void enforceInternetPermission() {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.INTERNET,
1529 "ConnectivityService");
1530 }
1531
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001532 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001533 mContext.enforceCallingOrSelfPermission(
1534 android.Manifest.permission.ACCESS_NETWORK_STATE,
1535 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001536 }
1537
1538 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001539 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001540 }
1541
Charles Hea0a87e82017-05-15 17:07:18 +01001542 private void enforceSettingsPermission() {
1543 mContext.enforceCallingOrSelfPermission(
1544 android.Manifest.permission.NETWORK_SETTINGS,
1545 "ConnectivityService");
1546 }
1547
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001548 private void enforceTetherAccessPermission() {
1549 mContext.enforceCallingOrSelfPermission(
1550 android.Manifest.permission.ACCESS_NETWORK_STATE,
1551 "ConnectivityService");
1552 }
1553
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001554 private void enforceConnectivityInternalPermission() {
1555 mContext.enforceCallingOrSelfPermission(
1556 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1557 "ConnectivityService");
1558 }
1559
Hugo Benichi514da602016-07-19 15:59:27 +09001560 private void enforceConnectivityRestrictedNetworksPermission() {
1561 try {
1562 mContext.enforceCallingOrSelfPermission(
1563 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1564 "ConnectivityService");
1565 return;
1566 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1567 enforceConnectivityInternalPermission();
1568 }
1569
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001570 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001571 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001572 }
1573
Lorenzo Colitti18660282016-07-04 12:55:44 +09001574 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001575 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001576 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001577 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001578 }
1579
1580 private void sendInetConditionBroadcast(NetworkInfo info) {
1581 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1582 }
1583
Wink Saville628b0852011-08-04 15:01:58 -07001584 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001585 synchronized (mVpns) {
1586 if (mLockdownTracker != null) {
1587 info = new NetworkInfo(info);
1588 mLockdownTracker.augmentNetworkInfo(info);
1589 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001590 }
1591
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001592 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001593 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001594 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001595 if (info.isFailover()) {
1596 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1597 info.setFailover(false);
1598 }
1599 if (info.getReason() != null) {
1600 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1601 }
1602 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001603 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1604 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001605 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001606 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001607 return intent;
1608 }
1609
1610 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1611 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1612 }
1613
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001614 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001615 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1616 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1617 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001618 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001619 final long ident = Binder.clearCallingIdentity();
1620 try {
1621 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1622 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1623 } finally {
1624 Binder.restoreCallingIdentity(ident);
1625 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001626 }
1627
Mike Lockwood0f79b542009-08-14 14:18:49 -04001628 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001629 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001630 if (!mSystemReady) {
1631 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001632 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001633 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001634 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001635 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001636 }
1637
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001638 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001639 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001640 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001641 final NetworkInfo ni = intent.getParcelableExtra(
1642 ConnectivityManager.EXTRA_NETWORK_INFO);
1643 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1644 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1645 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001646 } else {
1647 BroadcastOptions opts = BroadcastOptions.makeBasic();
1648 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1649 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001650 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001651 final IBatteryStats bs = BatteryStatsService.getService();
1652 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001653 bs.noteConnectivityChanged(intent.getIntExtra(
1654 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1655 ni != null ? ni.getState().toString() : "?");
1656 } catch (RemoteException e) {
1657 }
1658 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001659 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001660 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001661 } finally {
1662 Binder.restoreCallingIdentity(ident);
1663 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001664 }
1665 }
1666
1667 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001668 loadGlobalProxy();
1669
Hugo Benichi20035e02017-04-26 14:53:28 +09001670 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001671 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001672 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001673 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001674 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001675 }
1676 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001677 // load the global proxy at startup
1678 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001679
Robin Lee244ce8e2016-01-05 18:03:46 +00001680 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1681 // for user to unlock device too.
1682 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001683
Erik Klineda4bfa82015-04-30 12:58:40 +09001684 // Configure whether mobile data is always on.
1685 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1686
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001687 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001688
1689 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 }
1691
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001693 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001694 *
1695 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001696 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001697 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001698 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1699 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001700
1701 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001702 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001703
Robert Greenwalt7b816022014-04-18 15:25:25 -07001704 if (networkAgent.networkCapabilities.hasTransport(
1705 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001706 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1707 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001708 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001709 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001710 } else if (networkAgent.networkCapabilities.hasTransport(
1711 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001712 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1713 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001714 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001715 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001716 } else {
1717 // do not track any other networks
1718 timeout = 0;
1719 }
1720
Robert Greenwalt7b816022014-04-18 15:25:25 -07001721 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001722 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001723 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001724 } catch (Exception e) {
1725 // You shall not crash!
1726 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001727 }
1728 }
1729 }
1730
1731 /**
1732 * Remove data activity tracking when network disconnects.
1733 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001734 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1735 final String iface = networkAgent.linkProperties.getInterfaceName();
1736 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001737
Robert Greenwalt7b816022014-04-18 15:25:25 -07001738 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1739 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001740 try {
1741 // the call fails silently if no idletimer setup for this interface
1742 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001743 } catch (Exception e) {
1744 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001745 }
1746 }
1747 }
1748
1749 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001750 * Reads the network specific MTU size from reources.
1751 * and set it on it's iface.
1752 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001753 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1754 final String iface = newLp.getInterfaceName();
1755 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001756 if (oldLp == null && mtu == 0) {
1757 // Silently ignore unset MTU value.
1758 return;
1759 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001760 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1761 if (VDBG) log("identical MTU - not setting");
1762 return;
1763 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001764 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001765 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001766 return;
1767 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001768
w1997615afd812014-08-05 15:18:11 -07001769 // Cannot set MTU without interface name
1770 if (TextUtils.isEmpty(iface)) {
1771 loge("Setting MTU size with null iface.");
1772 return;
1773 }
1774
Robert Greenwalt7b816022014-04-18 15:25:25 -07001775 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001776 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001777 mNetd.setMtu(iface, mtu);
1778 } catch (Exception e) {
1779 Slog.e(TAG, "exception in setMtu()" + e);
1780 }
1781 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001782
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001783 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001784 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1785
1786 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001787 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001788 protected MockableSystemProperties getSystemProperties() {
1789 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001790 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001791
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001792 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1793 if (isDefaultNetwork(nai) == false) {
1794 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001795 }
1796
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001797 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1798 String[] values = null;
1799 if (tcpBufferSizes != null) {
1800 values = tcpBufferSizes.split(",");
1801 }
1802
1803 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001804 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001805 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1806 values = tcpBufferSizes.split(",");
1807 }
1808
1809 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1810
1811 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001812 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001813
1814 final String prefix = "/sys/kernel/ipv4/tcp_";
1815 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1816 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1817 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1818 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1819 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1820 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1821 mCurrentTcpBufferSizes = tcpBufferSizes;
1822 } catch (IOException e) {
1823 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001824 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001825
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001826 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001827 Settings.Global.TCP_DEFAULT_INIT_RWND,
1828 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001829 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1830 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001831 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001832 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001833 }
1834
Robert Greenwalt562cc542014-05-15 18:07:26 -07001835 @Override
1836 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001837 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001838 NETWORK_RESTORE_DELAY_PROP_NAME);
1839 if(restoreDefaultNetworkDelayStr != null &&
1840 restoreDefaultNetworkDelayStr.length() != 0) {
1841 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001842 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001843 } catch (NumberFormatException e) {
1844 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001846 // if the system property isn't set, use the value for the apn type
1847 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1848
1849 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1850 (mNetConfigs[networkType] != null)) {
1851 ret = mNetConfigs[networkType].restoreTime;
1852 }
1853 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001854 }
1855
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001856 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001857 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001858 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001859 }
1860 return false;
1861 }
1862
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001863 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1864 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1865 final long DIAG_TIME_MS = 5000;
1866 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1867 // Start gathering diagnostic information.
1868 netDiags.add(new NetworkDiagnostics(
1869 nai.network,
1870 new LinkProperties(nai.linkProperties), // Must be a copy.
1871 DIAG_TIME_MS));
1872 }
1873
1874 for (NetworkDiagnostics netDiag : netDiags) {
1875 pw.println();
1876 netDiag.waitForMeasurements();
1877 netDiag.dump(pw);
1878 }
1879 }
1880
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001881 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001882 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1883 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001884 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001885
Erik Kline7747fd42017-05-12 16:52:48 +09001886 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001887 dumpNetworkDiagnostics(pw);
1888 return;
Erik Klineee363c42017-05-29 09:11:03 +09001889 } else if (argsContain(args, TETHERING_ARG)) {
1890 mTethering.dump(fd, pw, args);
1891 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001892 }
Erik Kline379747a2015-06-05 17:47:34 +09001893
Lorenzo Colittie3805462015-06-03 11:18:24 +09001894 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001895 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001896 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001897 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001898 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001899 pw.println();
1900
Paul Jensen85cf78e2015-06-25 13:25:07 -04001901 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001902 pw.print("Active default network: ");
1903 if (defaultNai == null) {
1904 pw.println("none");
1905 } else {
1906 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001907 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001908 pw.println();
1909
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001910 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001911 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001912 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1913 pw.println(nai.toString());
1914 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001915 pw.println(String.format(
1916 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1917 nai.numForegroundNetworkRequests(),
1918 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1919 nai.numBackgroundNetworkRequests(),
1920 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001921 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001922 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1923 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001924 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001925 pw.decreaseIndent();
1926 pw.println("Lingered:");
1927 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001928 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001929 pw.decreaseIndent();
1930 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001931 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001932 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001933 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001934
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001935 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001936 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001937 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1938 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001939 }
1940 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001941 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001942
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001943 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001944
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001945 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001946 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001947
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001948 pw.println();
1949 mKeepaliveTracker.dump(pw);
1950
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001951 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001952 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001953
Erik Kline7747fd42017-05-12 16:52:48 +09001954 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001955 pw.println();
1956 synchronized (mValidationLogs) {
1957 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001958 for (ValidationLog p : mValidationLogs) {
1959 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001960 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001961 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001962 pw.decreaseIndent();
1963 }
1964 }
Erik Kline7523eb32015-07-09 18:24:03 +09001965
1966 pw.println();
1967 pw.println("mNetworkRequestInfoLogs (most recent first):");
1968 pw.increaseIndent();
1969 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1970 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001971
1972 pw.println();
1973 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1974 pw.increaseIndent();
1975 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1976 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001977
1978 pw.println();
1979 pw.println("NetTransition WakeLock activity (most recent first):");
1980 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09001981 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1982 pw.println("total releases: " + mTotalWakelockReleases);
1983 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1984 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1985 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1986 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1987 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1988 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001989 mWakelockLogs.reverseDump(fd, pw, args);
1990 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001991 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001992 }
1993
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001994 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001995 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001996 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001997 if (officialNai != null && officialNai.equals(nai)) return true;
1998 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001999 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002000 " - " + nai);
2001 }
2002 return false;
2003 }
2004
Robert Greenwalt42acef32009-08-12 16:08:25 -07002005 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002006 private class NetworkStateTrackerHandler extends Handler {
2007 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002008 super(looper);
2009 }
2010
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002011 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002012 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002013 default:
2014 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002015 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002016 handleAsyncChannelHalfConnect(msg);
2017 break;
2018 }
2019 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2020 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2021 if (nai != null) nai.asyncChannel.disconnect();
2022 break;
2023 }
2024 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2025 handleAsyncChannelDisconnected(msg);
2026 break;
2027 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002028 }
2029 return true;
2030 }
2031
2032 private void maybeHandleNetworkAgentMessage(Message msg) {
2033 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2034 if (nai == null) {
2035 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002036 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002037 }
2038 return;
2039 }
2040
2041 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002042 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002043 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2044 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002045 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2046 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002047 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002048 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002049 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002050 break;
2051 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002052 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002053 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002054 break;
2055 }
2056 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002057 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002058 updateNetworkInfo(nai, info);
2059 break;
2060 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002061 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002062 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002063 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002064 break;
2065 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002066 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002067 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2068 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002069 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002070 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002071 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002072 break;
2073 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002074 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002075 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2076 break;
2077 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002078 }
2079 }
2080
2081 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2082 switch (msg.what) {
2083 default:
2084 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002085 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002086 final NetworkAgentInfo nai;
2087 synchronized (mNetworkForNetId) {
2088 nai = mNetworkForNetId.get(msg.arg2);
2089 }
Erik Klinea24d4592018-01-11 21:07:29 +09002090 if (nai == null) break;
2091
2092 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2093 final boolean wasValidated = nai.lastValidated;
2094 final boolean wasDefault = isDefaultNetwork(nai);
2095
2096 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2097 ? (PrivateDnsConfig) msg.obj : null;
2098 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2099
2100 final boolean reevaluationRequired;
2101 final String logMsg;
2102 if (valid) {
2103 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2104 logMsg = (DBG && (privateDnsCfg != null))
2105 ? " with " + privateDnsCfg.toString() : "";
2106 } else {
2107 reevaluationRequired = false;
2108 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2109 ? " with redirect to " + redirectUrl : "";
2110 }
2111 if (DBG) {
2112 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2113 }
2114 // If there is a change in Private DNS configuration,
2115 // trigger reevaluation of the network to test it.
2116 if (reevaluationRequired) {
2117 nai.networkMonitor.sendMessage(
2118 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2119 break;
2120 }
2121 if (valid != nai.lastValidated) {
2122 if (wasDefault) {
2123 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2124 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002125 }
Erik Klinea24d4592018-01-11 21:07:29 +09002126 final int oldScore = nai.getCurrentScore();
2127 nai.lastValidated = valid;
2128 nai.everValidated |= valid;
2129 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2130 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2131 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2132 }
2133 updateInetCondition(nai);
2134 // Let the NetworkAgent know the state of its network
2135 Bundle redirectUrlBundle = new Bundle();
2136 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2137 nai.asyncChannel.sendMessage(
2138 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2139 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2140 0, redirectUrlBundle);
2141 if (wasValidated && !nai.lastValidated) {
2142 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002143 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 break;
2145 }
Paul Jensen869868be2014-05-15 10:33:05 -04002146 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002147 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002148 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002149 final NetworkAgentInfo nai;
2150 synchronized (mNetworkForNetId) {
2151 nai = mNetworkForNetId.get(netId);
2152 }
Calvin Onbe96da12016-10-11 15:10:46 -07002153 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002154 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002155 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002156 nai.lastCaptivePortalDetected = visible;
2157 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002158 if (nai.lastCaptivePortalDetected &&
2159 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2160 if (DBG) log("Avoiding captive portal network: " + nai.name());
2161 nai.asyncChannel.sendMessage(
2162 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2163 teardownUnneededNetwork(nai);
2164 break;
2165 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002166 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002167 }
2168 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002169 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002170 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002171 if (nai == null) {
2172 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2173 break;
2174 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002175 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002176 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002177 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002178 }
Paul Jensen869868be2014-05-15 10:33:05 -04002179 }
Paul Jensen869868be2014-05-15 10:33:05 -04002180 break;
2181 }
Erik Klinea24d4592018-01-11 21:07:29 +09002182 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2183 final NetworkAgentInfo nai;
2184 synchronized (mNetworkForNetId) {
2185 nai = mNetworkForNetId.get(msg.arg2);
2186 }
2187 if (nai == null) break;
2188
2189 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2190 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2191 if (nai.lastValidated && reevaluationRequired) {
2192 nai.networkMonitor.sendMessage(
2193 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2194 }
2195 break;
2196 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002197 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002198 return true;
2199 }
2200
Calvin Onbe96da12016-10-11 15:10:46 -07002201 private int getCaptivePortalMode() {
2202 return Settings.Global.getInt(mContext.getContentResolver(),
2203 Settings.Global.CAPTIVE_PORTAL_MODE,
2204 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2205 }
2206
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002207 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2208 switch (msg.what) {
2209 default:
2210 return false;
2211 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2212 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2213 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2214 handleLingerComplete(nai);
2215 }
2216 break;
2217 }
2218 }
2219 return true;
2220 }
2221
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002222 @Override
2223 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002224 if (!maybeHandleAsyncChannelMessage(msg) &&
2225 !maybeHandleNetworkMonitorMessage(msg) &&
2226 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002227 maybeHandleNetworkAgentMessage(msg);
2228 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002229 }
2230 }
2231
Erik Klinea24d4592018-01-11 21:07:29 +09002232 private void handlePrivateDnsSettingsChanged() {
2233 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2234
2235 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2236 // Private DNS only ever applies to networks that might provide
2237 // Internet access and therefore also require validation.
2238 if (!NetworkMonitor.isValidationRequired(
2239 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2240 continue;
2241 }
2242
2243 // Notify the NetworkMonitor thread in case it needs to cancel or
2244 // schedule DNS resolutions. If a DNS resolution is required the
2245 // result will be sent back to us.
2246 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2247
2248 if (!cfg.inStrictMode()) {
2249 // No strict mode hostname DNS resolution needed, so just update
2250 // DNS settings directly. In opportunistic and "off" modes this
2251 // just reprograms netd with the network-supplied DNS servers
2252 // (and of course the boolean of whether or not to attempt TLS).
2253 //
2254 // TODO: Consider code flow parity with strict mode, i.e. having
2255 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2256 // performing this call at that time.
2257 updatePrivateDns(nai, cfg);
2258 }
2259 }
2260 }
2261
2262 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2263 final boolean reevaluationRequired = true;
2264 final boolean dontReevaluate = false;
2265
2266 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2267 updateDnses(nai.linkProperties, null, nai.network.netId);
2268
2269 if (newCfg == null) {
2270 if (oldCfg == null) return dontReevaluate;
2271 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2272 }
2273
2274 if (oldCfg == null) {
2275 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2276 }
2277
2278 if (oldCfg.useTls != newCfg.useTls) {
2279 return reevaluationRequired;
2280 }
2281
2282 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2283 return reevaluationRequired;
2284 }
2285
2286 return dontReevaluate;
2287 }
2288
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002289 private void updateLingerState(NetworkAgentInfo nai, long now) {
2290 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2291 // 2. If the network was lingering and there are now requests, unlinger it.
2292 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2293 // one lingered request, start lingering.
2294 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002295 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002296 if (DBG) log("Unlingering " + nai.name());
2297 nai.unlinger();
2298 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002299 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002300 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002301 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002302 nai.linger();
2303 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2304 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2305 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002306 }
2307
Robert Greenwalt7b816022014-04-18 15:25:25 -07002308 private void handleAsyncChannelHalfConnect(Message msg) {
2309 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002310 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002311 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2312 if (VDBG) log("NetworkFactory connected");
2313 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002314 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002315 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002316 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002317 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002318 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002319 }
2320 } else {
2321 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002322 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002323 }
2324 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2325 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2326 if (VDBG) log("NetworkAgent connected");
2327 // A network agent has requested a connection. Establish the connection.
2328 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2329 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2330 } else {
2331 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002332 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002333 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002334 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002335 synchronized (mNetworkForNetId) {
2336 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002337 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002338 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002339 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002340 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002341 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342 }
2343 }
2344 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002345
Robert Greenwalt7b816022014-04-18 15:25:25 -07002346 private void handleAsyncChannelDisconnected(Message msg) {
2347 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2348 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002349 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002350 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002351 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002352 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002353 // TODO - if we move the logic to the network agent (have them disconnect
2354 // because they lost all their requests or because their score isn't good)
2355 // then they would disconnect organically, report their new state and then
2356 // disconnect the channel.
2357 if (nai.networkInfo.isConnected()) {
2358 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2359 null, null);
2360 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002361 final boolean wasDefault = isDefaultNetwork(nai);
2362 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002363 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002364 // Log default network disconnection before required book-keeping.
2365 // Let rematchAllNetworksAndRequests() below record a new default network event
2366 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2367 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002368 long now = SystemClock.elapsedRealtime();
2369 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002370 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002371 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002372 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2373 // by other networks that are already connected. Perhaps that can be done by
2374 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2375 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002376 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002377 mKeepaliveTracker.handleStopAllKeepalives(nai,
2378 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002379 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2380 // Disable wakeup packet monitoring for each interface.
2381 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2382 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002383 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002384 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002385 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002386 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002387 // Remove the NetworkAgent, but don't mark the netId as
2388 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002389 mNetworkForNetId.remove(nai.network.netId);
2390 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002391 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002392 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2393 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002394 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002395 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002396 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002397 sendUpdatedScoreToFactories(request, 0);
2398 }
2399 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002400 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002401 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002402 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002403 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002404 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002405 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002406 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002407 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002408 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002409 if (nai.created) {
2410 // Tell netd to clean up the configuration for this network
2411 // (routing rules, DNS, etc).
2412 // This may be slow as it requires a lot of netd shelling out to ip and
2413 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2414 // after we've rematched networks with requests which should make a potential
2415 // fallback network the default or requested a new network from the
2416 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2417 // long time.
2418 try {
2419 mNetd.removeNetwork(nai.network.netId);
2420 } catch (Exception e) {
2421 loge("Exception removing network: " + e);
2422 }
Erik Klinea24d4592018-01-11 21:07:29 +09002423 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002424 }
2425 synchronized (mNetworkForNetId) {
2426 mNetIdInUse.delete(nai.network.netId);
2427 }
2428 } else {
2429 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2430 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002431 }
2432 }
2433
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002434 // If this method proves to be too slow then we can maintain a separate
2435 // pendingIntent => NetworkRequestInfo map.
2436 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2437 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2438 Intent intent = pendingIntent.getIntent();
2439 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2440 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2441 if (existingPendingIntent != null &&
2442 existingPendingIntent.getIntent().filterEquals(intent)) {
2443 return entry.getValue();
2444 }
2445 }
2446 return null;
2447 }
2448
2449 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2450 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2451
2452 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2453 if (existingRequest != null) { // remove the existing request.
2454 if (DBG) log("Replacing " + existingRequest.request + " with "
2455 + nri.request + " because their intents matched.");
2456 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2457 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002458 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002459 }
2460
Erik Klineda4bfa82015-04-30 12:58:40 +09002461 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002462 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002463 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002464 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002465 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002466 if (nri.request.networkCapabilities.hasSignalStrength() &&
2467 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2468 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002469 }
2470 }
2471 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002472 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002473 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002474 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002475 }
2476 }
2477
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002478 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2479 int callingUid) {
2480 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2481 if (nri != null) {
2482 handleReleaseNetworkRequest(nri.request, callingUid);
2483 }
2484 }
2485
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002486 // Determines whether the network is the best (or could become the best, if it validated), for
2487 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2488 // on the value of reason:
2489 //
2490 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2491 // then it should be torn down.
2492 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2493 // then it should be lingered.
2494 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2495 final int numRequests;
2496 switch (reason) {
2497 case TEARDOWN:
2498 numRequests = nai.numRequestNetworkRequests();
2499 break;
2500 case LINGER:
2501 numRequests = nai.numForegroundNetworkRequests();
2502 break;
2503 default:
2504 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2505 return true;
2506 }
2507
2508 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002509 return false;
2510 }
Paul Jensene0988542015-06-25 15:30:08 -04002511 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002512 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2513 // Background requests don't affect lingering.
2514 continue;
2515 }
2516
Paul Jensene0988542015-06-25 15:30:08 -04002517 // If this Network is already the highest scoring Network for a request, or if
2518 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002519 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002520 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002521 // Note that this catches two important cases:
2522 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2523 // is currently satisfying the request. This is desirable when
2524 // cellular ends up validating but WiFi does not.
2525 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002526 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002527 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002528 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002529 nai.getCurrentScoreAsValidated())) {
2530 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002531 }
2532 }
Paul Jensene0988542015-06-25 15:30:08 -04002533 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002534 }
2535
Erik Klineacdd6392016-07-07 16:50:58 +09002536 private NetworkRequestInfo getNriForAppRequest(
2537 NetworkRequest request, int callingUid, String requestedOperation) {
2538 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2539
Robert Greenwalt9258c642014-03-26 16:47:06 -07002540 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002541 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002542 log(String.format("UID %d attempted to %s for unowned request %s",
2543 callingUid, requestedOperation, nri));
2544 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002545 }
Erik Klineacdd6392016-07-07 16:50:58 +09002546 }
2547
2548 return nri;
2549 }
2550
Erik Kline57faba92015-11-25 12:49:38 +09002551 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002552 if (mNetworkRequests.get(nri.request) == null) {
2553 return;
Erik Kline57faba92015-11-25 12:49:38 +09002554 }
Hugo Benichicd952782017-09-20 11:20:14 +09002555 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002556 return;
2557 }
2558 if (VDBG || (DBG && nri.request.isRequest())) {
2559 log("releasing " + nri.request + " (timeout)");
2560 }
2561 handleRemoveNetworkRequest(nri);
2562 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002563 }
2564
Erik Klineacdd6392016-07-07 16:50:58 +09002565 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002566 final NetworkRequestInfo nri =
2567 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2568 if (nri == null) {
2569 return;
Erik Kline57faba92015-11-25 12:49:38 +09002570 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002571 if (VDBG || (DBG && nri.request.isRequest())) {
2572 log("releasing " + nri.request + " (release request)");
2573 }
2574 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002575 }
Erik Klineacdd6392016-07-07 16:50:58 +09002576
Hugo Benichidba33db2017-03-23 22:40:44 +09002577 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002578 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002579 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002580
Erik Klineacdd6392016-07-07 16:50:58 +09002581 synchronized (mUidToNetworkRequestCount) {
2582 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2583 if (requests < 1) {
2584 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2585 nri.mUid);
2586 } else if (requests == 1) {
2587 mUidToNetworkRequestCount.removeAt(
2588 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2589 } else {
2590 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2591 }
2592 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002593
Erik Klineacdd6392016-07-07 16:50:58 +09002594 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2595 if (nri.request.isRequest()) {
2596 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002597 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002598 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002599 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002600 nai.removeRequest(nri.request.requestId);
2601 if (VDBG) {
2602 log(" Removing from current network " + nai.name() +
2603 ", leaving " + nai.numNetworkRequests() + " requests.");
2604 }
2605 // If there are still lingered requests on this network, don't tear it down,
2606 // but resume lingering instead.
2607 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002608 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002609 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2610 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002611 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002612 wasKept = true;
2613 }
Hugo Benichicd952782017-09-20 11:20:14 +09002614 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002615 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2616 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002617 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002618 }
Erik Klineacdd6392016-07-07 16:50:58 +09002619 }
2620
2621 // TODO: remove this code once we know that the Slog.wtf is never hit.
2622 //
2623 // Find all networks that are satisfying this request and remove the request
2624 // from their request lists.
2625 // TODO - it's my understanding that for a request there is only a single
2626 // network satisfying it, so this loop is wasteful
2627 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2628 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2629 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2630 otherNai.name() + ", but mNetworkAgentInfos says " +
2631 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002632 }
2633 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002634
Erik Klineacdd6392016-07-07 16:50:58 +09002635 // Maintain the illusion. When this request arrived, we might have pretended
2636 // that a network connected to serve it, even though the network was already
2637 // connected. Now that this request has gone away, we might have to pretend
2638 // that the network disconnected. LegacyTypeTracker will generate that
2639 // phantom disconnect for this type.
2640 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2641 boolean doRemove = true;
2642 if (wasKept) {
2643 // check if any of the remaining requests for this network are for the
2644 // same legacy type - if so, don't remove the nai
2645 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2646 NetworkRequest otherRequest = nai.requestAt(i);
2647 if (otherRequest.legacyType == nri.request.legacyType &&
2648 otherRequest.isRequest()) {
2649 if (DBG) log(" still have other legacy request - leaving");
2650 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002651 }
2652 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002653 }
2654
Erik Klineacdd6392016-07-07 16:50:58 +09002655 if (doRemove) {
2656 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002657 }
2658 }
Erik Klineacdd6392016-07-07 16:50:58 +09002659
2660 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2661 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2662 nri.request);
2663 }
2664 } else {
2665 // listens don't have a singular affectedNetwork. Check all networks to see
2666 // if this listen request applies and remove it.
2667 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2668 nai.removeRequest(nri.request.requestId);
2669 if (nri.request.networkCapabilities.hasSignalStrength() &&
2670 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2671 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2672 }
2673 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002674 }
2675 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002676
Lorenzo Colitti18660282016-07-04 12:55:44 +09002677 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002678 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2679 enforceConnectivityInternalPermission();
2680 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002681 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002682 }
2683
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002684 @Override
2685 public void setAvoidUnvalidated(Network network) {
2686 enforceConnectivityInternalPermission();
2687 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2688 }
2689
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002690 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2691 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2692 " accept=" + accept + " always=" + always);
2693
2694 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2695 if (nai == null) {
2696 // Nothing to do.
2697 return;
2698 }
2699
2700 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002701 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002702 return;
2703 }
2704
2705 if (!nai.networkMisc.explicitlySelected) {
2706 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2707 }
2708
2709 if (accept != nai.networkMisc.acceptUnvalidated) {
2710 int oldScore = nai.getCurrentScore();
2711 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002712 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002713 sendUpdatedScoreToFactories(nai);
2714 }
2715
2716 if (always) {
2717 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002718 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002719 }
2720
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002721 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002722 // Tell the NetworkAgent to not automatically reconnect to the network.
2723 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2724 // Teardown the nework.
2725 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002726 }
2727
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002728 }
2729
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002730 private void handleSetAvoidUnvalidated(Network network) {
2731 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2732 if (nai == null || nai.lastValidated) {
2733 // Nothing to do. The network either disconnected or revalidated.
2734 return;
2735 }
2736 if (!nai.avoidUnvalidated) {
2737 int oldScore = nai.getCurrentScore();
2738 nai.avoidUnvalidated = true;
2739 rematchAllNetworksAndRequests(nai, oldScore);
2740 sendUpdatedScoreToFactories(nai);
2741 }
2742 }
2743
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002744 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002745 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002746 mHandler.sendMessageDelayed(
2747 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2748 PROMPT_UNVALIDATED_DELAY_MS);
2749 }
2750
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002751 @Override
2752 public void startCaptivePortalApp(Network network) {
2753 enforceConnectivityInternalPermission();
2754 mHandler.post(() -> {
2755 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2756 if (nai == null) return;
2757 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2758 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2759 });
2760 }
2761
Hugo Benichic8e9e122016-09-14 23:23:08 +00002762 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002763 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002764 }
2765
Erik Kline065ab6e2016-10-02 18:02:14 +09002766 private void rematchForAvoidBadWifiUpdate() {
2767 rematchAllNetworksAndRequests(null, 0);
2768 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2769 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2770 sendUpdatedScoreToFactories(nai);
2771 }
2772 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002773 }
2774
Erik Kline065ab6e2016-10-02 18:02:14 +09002775 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002776 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002777 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002778 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002779 if (!configRestrict) {
2780 pw.println("Bad Wi-Fi avoidance: unrestricted");
2781 return;
2782 }
2783
2784 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2785 pw.increaseIndent();
2786 pw.println("Config restrict: " + configRestrict);
2787
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002788 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002789 String description;
2790 // Can't use a switch statement because strings are legal case labels, but null is not.
2791 if ("0".equals(value)) {
2792 description = "get stuck";
2793 } else if (value == null) {
2794 description = "prompt";
2795 } else if ("1".equals(value)) {
2796 description = "avoid";
2797 } else {
2798 description = value + " (?)";
2799 }
2800 pw.println("User setting: " + description);
2801 pw.println("Network overrides:");
2802 pw.increaseIndent();
2803 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2804 if (nai.avoidUnvalidated) {
2805 pw.println(nai.name());
2806 }
2807 }
2808 pw.decreaseIndent();
2809 pw.decreaseIndent();
2810 }
2811
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002812 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2813 final String action;
2814 switch (type) {
2815 case NO_INTERNET:
2816 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2817 break;
2818 case LOST_INTERNET:
2819 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2820 break;
2821 default:
2822 Slog.wtf(TAG, "Unknown notification type " + type);
2823 return;
2824 }
2825
2826 Intent intent = new Intent(action);
2827 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2828 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2829 intent.setClassName("com.android.settings",
2830 "com.android.settings.wifi.WifiNoInternetDialog");
2831
2832 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2833 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2834 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2835 }
2836
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002837 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002838 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002839 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2840
2841 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2842 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002843 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002844 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002845 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2846 return;
2847 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002848 showValidationNotification(nai, NotificationType.NO_INTERNET);
2849 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002850
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002851 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2852 NetworkCapabilities nc = nai.networkCapabilities;
2853 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002854
Erik Kline065ab6e2016-10-02 18:02:14 +09002855 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002856 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002857 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2858 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002859 }
2860
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002861 @Override
2862 public int getMultipathPreference(Network network) {
2863 enforceAccessPermission();
2864
2865 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002866 if (nai != null && nai.networkCapabilities
2867 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002868 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2869 }
2870
2871 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2872 }
2873
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002874 private class InternalHandler extends Handler {
2875 public InternalHandler(Looper looper) {
2876 super(looper);
2877 }
2878
2879 @Override
2880 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002881 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002882 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002883 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002884 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002885 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002886 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002887 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002888 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002889 break;
2890 }
Jason Monkdecd2952013-10-10 14:02:51 -04002891 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002892 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002893 break;
2894 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002895 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002896 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2897 break;
2898 }
2899 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2900 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002901 break;
2902 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002903 case EVENT_REGISTER_NETWORK_AGENT: {
2904 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2905 break;
2906 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002907 case EVENT_REGISTER_NETWORK_REQUEST:
2908 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002909 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002910 break;
2911 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002912 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2913 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002914 handleRegisterNetworkRequestWithIntent(msg);
2915 break;
2916 }
Erik Kline57faba92015-11-25 12:49:38 +09002917 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2918 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2919 handleTimedOutNetworkRequest(nri);
2920 break;
2921 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002922 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2923 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2924 break;
2925 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002926 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002927 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002928 break;
2929 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002930 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002931 Network network = (Network) msg.obj;
2932 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002933 break;
2934 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002935 case EVENT_SET_AVOID_UNVALIDATED: {
2936 handleSetAvoidUnvalidated((Network) msg.obj);
2937 break;
2938 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002939 case EVENT_PROMPT_UNVALIDATED: {
2940 handlePromptUnvalidated((Network) msg.obj);
2941 break;
2942 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002943 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2944 handleMobileDataAlwaysOn();
2945 break;
2946 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002947 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2948 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2949 mKeepaliveTracker.handleStartKeepalive(msg);
2950 break;
2951 }
2952 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2953 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2954 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2955 int slot = msg.arg1;
2956 int reason = msg.arg2;
2957 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2958 break;
2959 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002960 case EVENT_SYSTEM_READY: {
2961 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2962 nai.networkMonitor.systemReady = true;
2963 }
2964 break;
2965 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002966 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002967 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002968 break;
2969 }
Erik Klinea24d4592018-01-11 21:07:29 +09002970 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
2971 handlePrivateDnsSettingsChanged();
2972 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002973 }
2974 }
2975 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002976
2977 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002978 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002979 public int tether(String iface, String callerPkg) {
2980 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002981 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002982 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002983 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002984 } else {
2985 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2986 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002987 }
2988
2989 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002990 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002991 public int untether(String iface, String callerPkg) {
2992 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002993
2994 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002995 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002996 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002997 } else {
2998 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2999 }
3000 }
3001
3002 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003003 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003004 public int getLastTetherError(String iface) {
3005 enforceTetherAccessPermission();
3006
3007 if (isTetheringSupported()) {
3008 return mTethering.getLastTetherError(iface);
3009 } else {
3010 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3011 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003012 }
3013
3014 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003015 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003016 public String[] getTetherableUsbRegexs() {
3017 enforceTetherAccessPermission();
3018 if (isTetheringSupported()) {
3019 return mTethering.getTetherableUsbRegexs();
3020 } else {
3021 return new String[0];
3022 }
3023 }
3024
Lorenzo Colitti18660282016-07-04 12:55:44 +09003025 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003026 public String[] getTetherableWifiRegexs() {
3027 enforceTetherAccessPermission();
3028 if (isTetheringSupported()) {
3029 return mTethering.getTetherableWifiRegexs();
3030 } else {
3031 return new String[0];
3032 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003033 }
3034
Lorenzo Colitti18660282016-07-04 12:55:44 +09003035 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003036 public String[] getTetherableBluetoothRegexs() {
3037 enforceTetherAccessPermission();
3038 if (isTetheringSupported()) {
3039 return mTethering.getTetherableBluetoothRegexs();
3040 } else {
3041 return new String[0];
3042 }
3043 }
3044
Lorenzo Colitti18660282016-07-04 12:55:44 +09003045 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003046 public int setUsbTethering(boolean enable, String callerPkg) {
3047 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003048 if (isTetheringSupported()) {
3049 return mTethering.setUsbTethering(enable);
3050 } else {
3051 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3052 }
3053 }
3054
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003055 // TODO - move iface listing, queries, etc to new module
3056 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003057 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003058 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003059 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003060 return mTethering.getTetherableIfaces();
3061 }
3062
Lorenzo Colitti18660282016-07-04 12:55:44 +09003063 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003064 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003065 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003066 return mTethering.getTetheredIfaces();
3067 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003068
Lorenzo Colitti18660282016-07-04 12:55:44 +09003069 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003070 public String[] getTetheringErroredIfaces() {
3071 enforceTetherAccessPermission();
3072 return mTethering.getErroredIfaces();
3073 }
3074
Lorenzo Colitti18660282016-07-04 12:55:44 +09003075 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003076 public String[] getTetheredDhcpRanges() {
3077 enforceConnectivityInternalPermission();
3078 return mTethering.getTetheredDhcpRanges();
3079 }
3080
Udam Sainic3b640c2017-06-07 12:06:28 -07003081 @Override
3082 public boolean isTetheringSupported(String callerPkg) {
3083 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3084 return isTetheringSupported();
3085 }
3086
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003087 // if ro.tether.denied = true we default to no tethering
3088 // gservices could set the secure setting to 1 though to enable it on a build where it
3089 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003090 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003091 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3092 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3093 Settings.Global.TETHER_SUPPORTED, defaultVal));
3094 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003095 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003096
3097 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3098 boolean adminUser = false;
3099 final long token = Binder.clearCallingIdentity();
3100 try {
3101 adminUser = mUserManager.isAdminUser();
3102 } finally {
3103 Binder.restoreCallingIdentity(token);
3104 }
3105
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003106 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003107 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003108
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003109 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003110 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3111 String callerPkg) {
3112 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003113 if (!isTetheringSupported()) {
3114 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3115 return;
3116 }
3117 mTethering.startTethering(type, receiver, showProvisioningUi);
3118 }
3119
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003120 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003121 public void stopTethering(int type, String callerPkg) {
3122 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003123 mTethering.stopTethering(type);
3124 }
3125
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003126 // Called when we lose the default network and have no replacement yet.
3127 // This will automatically be cleared after X seconds or a new default network
3128 // becomes CONNECTED, whichever happens first. The timer is started by the
3129 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003130 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003131 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003132 if (mNetTransitionWakeLock.isHeld()) {
3133 return;
3134 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003135 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003136 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3137 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003138 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003139 mWakelockLogs.log("ACQUIRE for " + forWhom);
3140 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3141 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003142 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003143
Hugo Benichi4c31b342017-03-30 23:18:10 +09003144 // Called when we gain a new default network to release the network transition wakelock in a
3145 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3146 // message is cancelled.
3147 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003148 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003149 if (!mNetTransitionWakeLock.isHeld()) {
3150 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003151 }
3152 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003153 // Cancel self timeout on wakelock hold.
3154 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3155 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3156 mHandler.sendMessageDelayed(msg, 1000);
3157 }
3158
3159 // Called when either message of ensureNetworkTransitionWakelock or
3160 // scheduleReleaseNetworkTransitionWakelock is processed.
3161 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3162 String event = eventName(eventId);
3163 synchronized (this) {
3164 if (!mNetTransitionWakeLock.isHeld()) {
3165 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3166 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3167 return;
3168 }
3169 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003170 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3171 mTotalWakelockDurationMs += lockDuration;
3172 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3173 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003174 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003175 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003176 }
3177
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003178 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003179 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003180 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003181 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003182 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003183 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003184 }
3185
Lorenzo Colitti18660282016-07-04 12:55:44 +09003186 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003187 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003188 enforceAccessPermission();
3189 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003190 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003191 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003192 mHandler.sendMessage(
3193 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3194 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003195
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003196 private void handleReportNetworkConnectivity(
3197 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003198 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003199 if (network == null) {
3200 nai = getDefaultNetwork();
3201 } else {
3202 nai = getNetworkAgentInfoForNetwork(network);
3203 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003204 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3205 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3206 return;
3207 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003208 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003209 if (hasConnectivity == nai.lastValidated) {
3210 return;
3211 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003212 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003213 int netid = nai.network.netId;
3214 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003215 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003216 // Validating a network that has not yet connected could result in a call to
3217 // rematchNetworkAndRequests() which is not meant to work on such networks.
3218 if (!nai.everConnected) {
3219 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003220 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003221 LinkProperties lp = getLinkProperties(nai);
3222 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3223 return;
3224 }
3225 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003226 }
3227
Paul Jensencee9b512015-05-06 07:32:40 -04003228 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003229 // this information is already available as a world read/writable jvm property
3230 // so this API change wouldn't have a benifit. It also breaks the passing
3231 // of proxy info to all the JVMs.
3232 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003233 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003234 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003235 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3236 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003237 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003238 }
3239
Lorenzo Colitti18660282016-07-04 12:55:44 +09003240 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003241 public ProxyInfo getProxyForNetwork(Network network) {
3242 if (network == null) return getDefaultProxy();
3243 final ProxyInfo globalProxy = getGlobalProxy();
3244 if (globalProxy != null) return globalProxy;
3245 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3246 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3247 // caller may not have.
3248 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3249 if (nai == null) return null;
3250 synchronized (nai) {
3251 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3252 if (proxyInfo == null) return null;
3253 return new ProxyInfo(proxyInfo);
3254 }
3255 }
3256
Paul Jensene0bef712014-12-10 15:12:18 -05003257 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3258 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3259 // proxy is null then there is no proxy in place).
3260 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3261 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3262 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3263 proxy = null;
3264 }
3265 return proxy;
3266 }
3267
3268 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3269 // better for determining if a new proxy broadcast is necessary:
3270 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3271 // avoid unnecessary broadcasts.
3272 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3273 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3274 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3275 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3276 // all set.
3277 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3278 a = canonicalizeProxyInfo(a);
3279 b = canonicalizeProxyInfo(b);
3280 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3281 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3282 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3283 }
3284
Jason Monk207900c2014-04-25 15:00:09 -04003285 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003286 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003287
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003288 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003289 if (proxyProperties == mGlobalProxy) return;
3290 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3291 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3292
3293 String host = "";
3294 int port = 0;
3295 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003296 String pacFileUrl = "";
3297 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003298 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003299 if (!proxyProperties.isValid()) {
3300 if (DBG)
3301 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3302 return;
3303 }
Jason Monk207900c2014-04-25 15:00:09 -04003304 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003305 host = mGlobalProxy.getHost();
3306 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003307 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003308 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003309 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003310 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003311 } else {
3312 mGlobalProxy = null;
3313 }
3314 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003315 final long token = Binder.clearCallingIdentity();
3316 try {
3317 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3318 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3319 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3320 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003321 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003322 } finally {
3323 Binder.restoreCallingIdentity(token);
3324 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003325
Jason Monkcf0f97a2014-10-02 15:39:38 -04003326 if (mGlobalProxy == null) {
3327 proxyProperties = mDefaultProxy;
3328 }
3329 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003330 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003331 }
3332
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003333 private void loadGlobalProxy() {
3334 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003335 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3336 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3337 String exclList = Settings.Global.getString(res,
3338 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003339 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3340 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003341 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003342 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003343 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003344 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003345 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003346 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003347 if (!proxyProperties.isValid()) {
3348 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3349 return;
3350 }
3351
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003352 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003353 mGlobalProxy = proxyProperties;
3354 }
3355 }
3356 }
3357
Jason Monk207900c2014-04-25 15:00:09 -04003358 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003359 // this information is already available as a world read/writable jvm property
3360 // so this API change wouldn't have a benifit. It also breaks the passing
3361 // of proxy info to all the JVMs.
3362 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003363 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003364 return mGlobalProxy;
3365 }
3366 }
3367
Jason Monk207900c2014-04-25 15:00:09 -04003368 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003369 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003370 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003371 proxy = null;
3372 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003373 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003374 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003375 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003376 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003377 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3378 return;
3379 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003380
3381 // This call could be coming from the PacManager, containing the port of the local
3382 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3383 // global (to get the correct local port), and send a broadcast.
3384 // TODO: Switch PacManager to have its own message to send back rather than
3385 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003386 if ((mGlobalProxy != null) && (proxy != null)
3387 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003388 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3389 mGlobalProxy = proxy;
3390 sendProxyBroadcast(mGlobalProxy);
3391 return;
3392 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003393 mDefaultProxy = proxy;
3394
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003395 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003396 if (!mDefaultProxyDisabled) {
3397 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003398 }
3399 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003400 }
3401
Paul Jensene0bef712014-12-10 15:12:18 -05003402 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3403 // This method gets called when any network changes proxy, but the broadcast only ever contains
3404 // the default proxy (even if it hasn't changed).
3405 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3406 // world where an app might be bound to a non-default network.
3407 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3408 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3409 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3410
3411 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3412 sendProxyBroadcast(getDefaultProxy());
3413 }
3414 }
3415
Robert Greenwalt434203a2010-10-11 16:00:27 -07003416 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003417 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3418 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003419 if (!TextUtils.isEmpty(proxy)) {
3420 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003421 if (data.length == 0) {
3422 return;
3423 }
3424
Robert Greenwalt434203a2010-10-11 16:00:27 -07003425 String proxyHost = data[0];
3426 int proxyPort = 8080;
3427 if (data.length > 1) {
3428 try {
3429 proxyPort = Integer.parseInt(data[1]);
3430 } catch (NumberFormatException e) {
3431 return;
3432 }
3433 }
Jason Monk207900c2014-04-25 15:00:09 -04003434 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003435 setGlobalProxy(p);
3436 }
3437 }
3438
Jason Monk207900c2014-04-25 15:00:09 -04003439 private void sendProxyBroadcast(ProxyInfo proxy) {
3440 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003441 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003442 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003443 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003444 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3445 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003446 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003447 final long ident = Binder.clearCallingIdentity();
3448 try {
3449 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3450 } finally {
3451 Binder.restoreCallingIdentity(ident);
3452 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003453 }
3454
3455 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003456 final private HashMap<Uri, Integer> mUriEventMap;
3457 final private Context mContext;
3458 final private Handler mHandler;
3459
3460 SettingsObserver(Context context, Handler handler) {
3461 super(null);
3462 mUriEventMap = new HashMap<Uri, Integer>();
3463 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003464 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003465 }
3466
Erik Klineda4bfa82015-04-30 12:58:40 +09003467 void observe(Uri uri, int what) {
3468 mUriEventMap.put(uri, what);
3469 final ContentResolver resolver = mContext.getContentResolver();
3470 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003471 }
3472
3473 @Override
3474 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003475 Slog.wtf(TAG, "Should never be reached.");
3476 }
3477
3478 @Override
3479 public void onChange(boolean selfChange, Uri uri) {
3480 final Integer what = mUriEventMap.get(uri);
3481 if (what != null) {
3482 mHandler.obtainMessage(what.intValue()).sendToTarget();
3483 } else {
3484 loge("No matching event to send for URI=" + uri);
3485 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003486 }
3487 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003488
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003489 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003490 Slog.d(TAG, s);
3491 }
3492
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003493 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003494 Slog.e(TAG, s);
3495 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003496
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003497 private static void loge(String s, Throwable t) {
3498 Slog.e(TAG, s, t);
3499 }
3500
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003501 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003502 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003503 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3504 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3505 *
3506 * @param oldPackage Package name of the application which currently controls VPN, which will
3507 * be replaced. If there is no such application, this should should either be
3508 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3509 * @param newPackage Package name of the application which should gain control of VPN, or
3510 * {@code null} to disable.
3511 * @param userId User for whom to prepare the new VPN.
3512 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003513 * @hide
3514 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003515 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003516 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3517 int userId) {
3518 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003519
Hugo Benichi20035e02017-04-26 14:53:28 +09003520 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003521 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003522 Vpn vpn = mVpns.get(userId);
3523 if (vpn != null) {
3524 return vpn.prepare(oldPackage, newPackage);
3525 } else {
3526 return false;
3527 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003528 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003529 }
3530
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003531 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003532 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3533 * This method is used by system-privileged apps.
3534 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3535 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3536 *
3537 * @param packageName The package for which authorization state should change.
3538 * @param userId User for whom {@code packageName} is installed.
3539 * @param authorized {@code true} if this app should be able to start a VPN connection without
3540 * explicit user approval, {@code false} if not.
3541 *
Jeff Davidson05542602014-08-11 14:07:27 -07003542 * @hide
3543 */
3544 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003545 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3546 enforceCrossUserPermission(userId);
3547
Hugo Benichi20035e02017-04-26 14:53:28 +09003548 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003549 Vpn vpn = mVpns.get(userId);
3550 if (vpn != null) {
3551 vpn.setPackageAuthorization(packageName, authorized);
3552 }
Jeff Davidson05542602014-08-11 14:07:27 -07003553 }
3554 }
3555
3556 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003557 * Configure a TUN interface and return its file descriptor. Parameters
3558 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003559 * and not available in ConnectivityManager. Permissions are checked in
3560 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003561 * @hide
3562 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003563 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003564 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003565 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003566 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003567 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003568 return mVpns.get(user).establish(config);
3569 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003570 }
3571
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003572 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003573 * Start legacy VPN, controlling native daemons as needed. Creates a
3574 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003575 */
3576 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003577 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003578 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003579 final LinkProperties egress = getActiveLinkProperties();
3580 if (egress == null) {
3581 throw new IllegalStateException("Missing active network connection");
3582 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003583 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003584 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003585 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3586 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003587 }
3588
3589 /**
3590 * Return the information of the ongoing legacy VPN. This method is used
3591 * by VpnSettings and not available in ConnectivityManager. Permissions
3592 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003593 */
3594 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003595 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3596 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003597
Hugo Benichi20035e02017-04-26 14:53:28 +09003598 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003599 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003600 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003601 }
3602
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003603 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003604 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3605 * and not available in ConnectivityManager.
3606 */
3607 @Override
3608 public VpnInfo[] getAllVpnInfo() {
3609 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003610 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003611 if (mLockdownEnabled) {
3612 return new VpnInfo[0];
3613 }
3614
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003615 List<VpnInfo> infoList = new ArrayList<>();
3616 for (int i = 0; i < mVpns.size(); i++) {
3617 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3618 if (info != null) {
3619 infoList.add(info);
3620 }
3621 }
3622 return infoList.toArray(new VpnInfo[infoList.size()]);
3623 }
3624 }
3625
3626 /**
3627 * @return VPN information for accounting, or null if we can't retrieve all required
3628 * information, e.g primary underlying iface.
3629 */
3630 @Nullable
3631 private VpnInfo createVpnInfo(Vpn vpn) {
3632 VpnInfo info = vpn.getVpnInfo();
3633 if (info == null) {
3634 return null;
3635 }
3636 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3637 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3638 // the underlyingNetworks list.
3639 if (underlyingNetworks == null) {
3640 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3641 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3642 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3643 }
3644 } else if (underlyingNetworks.length > 0) {
3645 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3646 if (linkProperties != null) {
3647 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3648 }
3649 }
3650 return info.primaryUnderlyingIface == null ? null : info;
3651 }
3652
3653 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003654 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3655 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003656 * Permissions are checked in Vpn class.
3657 * @hide
3658 */
3659 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003660 public VpnConfig getVpnConfig(int userId) {
3661 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003662 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003663 Vpn vpn = mVpns.get(userId);
3664 if (vpn != null) {
3665 return vpn.getVpnConfig();
3666 } else {
3667 return null;
3668 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003669 }
3670 }
3671
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003672 @Override
3673 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003674 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3675 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3676 return false;
3677 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003678
Hugo Benichi69744342017-11-27 10:57:16 +09003679 synchronized (mVpns) {
3680 // Tear down existing lockdown if profile was removed
3681 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3682 if (mLockdownEnabled) {
3683 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3684 if (profileTag == null) {
3685 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3686 return false;
3687 }
3688 String profileName = new String(profileTag);
3689 final VpnProfile profile = VpnProfile.decode(
3690 profileName, mKeyStore.get(Credentials.VPN + profileName));
3691 if (profile == null) {
3692 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3693 setLockdownTracker(null);
3694 return true;
3695 }
3696 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003697 Vpn vpn = mVpns.get(user);
3698 if (vpn == null) {
3699 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3700 return false;
3701 }
3702 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003703 } else {
3704 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003705 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003706 }
3707
3708 return true;
3709 }
3710
3711 /**
3712 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3713 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3714 */
Hugo Benichi69744342017-11-27 10:57:16 +09003715 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003716 private void setLockdownTracker(LockdownVpnTracker tracker) {
3717 // Shutdown any existing tracker
3718 final LockdownVpnTracker existing = mLockdownTracker;
3719 mLockdownTracker = null;
3720 if (existing != null) {
3721 existing.shutdown();
3722 }
3723
Robin Leec3736bc2017-03-10 16:19:54 +00003724 if (tracker != null) {
3725 mLockdownTracker = tracker;
3726 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003727 }
3728 }
3729
Hugo Benichi69744342017-11-27 10:57:16 +09003730 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003731 private void throwIfLockdownEnabled() {
3732 if (mLockdownEnabled) {
3733 throw new IllegalStateException("Unavailable in lockdown mode");
3734 }
3735 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003736
Robin Lee244ce8e2016-01-05 18:03:46 +00003737 /**
Robin Lee17e61832016-05-09 13:46:28 +01003738 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3739 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003740 *
Robin Lee17e61832016-05-09 13:46:28 +01003741 * @return {@code true} if the service was started, the service was already connected, or there
3742 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003743 */
Robin Lee17e61832016-05-09 13:46:28 +01003744 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003745 synchronized (mVpns) {
3746 Vpn vpn = mVpns.get(userId);
3747 if (vpn == null) {
3748 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3749 // exists already.
3750 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3751 return false;
3752 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003753
Robin Lee812800c2016-05-13 15:38:08 +01003754 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003755 }
3756 }
3757
3758 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003759 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3760 enforceSettingsPermission();
3761 enforceCrossUserPermission(userId);
3762
3763 synchronized (mVpns) {
3764 Vpn vpn = mVpns.get(userId);
3765 if (vpn == null) {
3766 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3767 return false;
3768 }
3769 return vpn.isAlwaysOnPackageSupported(packageName);
3770 }
3771 }
3772
3773 @Override
Robin Leedc679712016-05-03 13:23:03 +01003774 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003775 enforceConnectivityInternalPermission();
3776 enforceCrossUserPermission(userId);
3777
Robin Lee244ce8e2016-01-05 18:03:46 +00003778 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003779 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3780 if (LockdownVpnTracker.isEnabled()) {
3781 return false;
3782 }
3783
Robin Lee244ce8e2016-01-05 18:03:46 +00003784 Vpn vpn = mVpns.get(userId);
3785 if (vpn == null) {
3786 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3787 return false;
3788 }
Robin Lee17e61832016-05-09 13:46:28 +01003789 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003790 return false;
3791 }
Robin Lee17e61832016-05-09 13:46:28 +01003792 if (!startAlwaysOnVpn(userId)) {
3793 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003794 return false;
3795 }
3796 }
3797 return true;
3798 }
3799
3800 @Override
3801 public String getAlwaysOnVpnPackage(int userId) {
3802 enforceConnectivityInternalPermission();
3803 enforceCrossUserPermission(userId);
3804
3805 synchronized (mVpns) {
3806 Vpn vpn = mVpns.get(userId);
3807 if (vpn == null) {
3808 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3809 return null;
3810 }
3811 return vpn.getAlwaysOnPackage();
3812 }
3813 }
3814
Wink Savilleab9321d2013-06-29 21:10:57 -07003815 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003816 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003817 // TODO: Remove? Any reason to trigger a provisioning check?
3818 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003819 }
3820
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003821 /** Location to an updatable file listing carrier provisioning urls.
3822 * An example:
3823 *
3824 * <?xml version="1.0" encoding="utf-8"?>
3825 * <provisioningUrls>
3826 * <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 -07003827 * </provisioningUrls>
3828 */
3829 private static final String PROVISIONING_URL_PATH =
3830 "/data/misc/radio/provisioning_urls.xml";
3831 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003832
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003833 /** XML tag for root element. */
3834 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3835 /** XML tag for individual url */
3836 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003837 /** XML attribute for mcc */
3838 private static final String ATTR_MCC = "mcc";
3839 /** XML attribute for mnc */
3840 private static final String ATTR_MNC = "mnc";
3841
Paul Jensen434dde82015-06-11 09:43:30 -04003842 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003843 FileReader fileReader = null;
3844 XmlPullParser parser = null;
3845 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003846
3847 try {
3848 fileReader = new FileReader(mProvisioningUrlFile);
3849 parser = Xml.newPullParser();
3850 parser.setInput(fileReader);
3851 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3852
3853 while (true) {
3854 XmlUtils.nextElement(parser);
3855
3856 String element = parser.getName();
3857 if (element == null) break;
3858
Paul Jensen434dde82015-06-11 09:43:30 -04003859 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003860 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3861 try {
3862 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3863 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3864 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3865 parser.next();
3866 if (parser.getEventType() == XmlPullParser.TEXT) {
3867 return parser.getText();
3868 }
3869 }
3870 }
3871 } catch (NumberFormatException e) {
3872 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3873 }
3874 }
3875 }
3876 return null;
3877 } catch (FileNotFoundException e) {
3878 loge("Carrier Provisioning Urls file not found");
3879 } catch (XmlPullParserException e) {
3880 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3881 } catch (IOException e) {
3882 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3883 } finally {
3884 if (fileReader != null) {
3885 try {
3886 fileReader.close();
3887 } catch (IOException e) {}
3888 }
3889 }
3890 return null;
3891 }
3892
Wink Saville42d4f082013-07-20 20:31:59 -07003893 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003894 public String getMobileProvisioningUrl() {
3895 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003896 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003897 if (TextUtils.isEmpty(url)) {
3898 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003899 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003900 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003901 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003902 }
Wink Saville8cf35602013-07-10 23:00:07 -07003903 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003904 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003905 String phoneNumber = mTelephonyManager.getLine1Number();
3906 if (TextUtils.isEmpty(phoneNumber)) {
3907 phoneNumber = "0000000000";
3908 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003909 url = String.format(url,
3910 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3911 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003912 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003913 }
3914
Wink Savilleab9321d2013-06-29 21:10:57 -07003915 return url;
3916 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003917
Wink Saville948282b2013-08-29 08:55:16 -07003918 @Override
3919 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003920 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003921 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003922 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3923 return;
3924 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003925 final long ident = Binder.clearCallingIdentity();
3926 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003927 // Concatenate the range of types onto the range of NetIDs.
3928 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3929 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003930 } finally {
3931 Binder.restoreCallingIdentity(ident);
3932 }
Wink Saville948282b2013-08-29 08:55:16 -07003933 }
Wink Saville7788c612013-08-29 14:57:08 -07003934
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003935 @Override
3936 public void setAirplaneMode(boolean enable) {
3937 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003938 final long ident = Binder.clearCallingIdentity();
3939 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003940 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003941 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003942 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3943 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003944 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003945 } finally {
3946 Binder.restoreCallingIdentity(ident);
3947 }
3948 }
3949
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003950 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003951 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003952 Vpn userVpn = mVpns.get(userId);
3953 if (userVpn != null) {
3954 loge("Starting user already has a VPN");
3955 return;
3956 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003957 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003958 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003959 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3960 updateLockdownVpn();
3961 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003962 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003963 }
3964
3965 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003966 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003967 Vpn userVpn = mVpns.get(userId);
3968 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003969 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003970 return;
3971 }
Robin Lee17e61832016-05-09 13:46:28 +01003972 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003973 mVpns.delete(userId);
3974 }
3975 }
3976
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003977 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003978 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003979 final int vpnsSize = mVpns.size();
3980 for (int i = 0; i < vpnsSize; i++) {
3981 Vpn vpn = mVpns.valueAt(i);
3982 vpn.onUserAdded(userId);
3983 }
3984 }
3985 }
3986
3987 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003988 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003989 final int vpnsSize = mVpns.size();
3990 for (int i = 0; i < vpnsSize; i++) {
3991 Vpn vpn = mVpns.valueAt(i);
3992 vpn.onUserRemoved(userId);
3993 }
3994 }
3995 }
3996
Robin Lee89e7a692016-02-29 14:38:17 +00003997 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09003998 synchronized (mVpns) {
3999 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4000 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4001 updateLockdownVpn();
4002 } else {
4003 startAlwaysOnVpn(userId);
4004 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004005 }
4006 }
4007
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004008 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4009 @Override
4010 public void onReceive(Context context, Intent intent) {
4011 final String action = intent.getAction();
4012 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4013 if (userId == UserHandle.USER_NULL) return;
4014
Robin Lee323f29d2016-05-04 16:38:06 +01004015 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004016 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004017 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004018 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004019 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4020 onUserAdded(userId);
4021 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4022 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004023 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4024 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004025 }
4026 }
4027 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004028
Robin Lee95204e02017-01-27 11:59:22 +00004029 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4030 @Override
4031 public void onReceive(Context context, Intent intent) {
4032 // Try creating lockdown tracker, since user present usually means
4033 // unlocked keystore.
4034 updateLockdownVpn();
4035 mContext.unregisterReceiver(this);
4036 }
4037 };
4038
Robert Greenwalta67be032014-05-16 15:49:14 -07004039 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4040 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004041 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4042 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004043
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004044 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4045 // Map from UID to number of NetworkRequests that UID has filed.
4046 @GuardedBy("mUidToNetworkRequestCount")
4047 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4048
Robert Greenwalta67be032014-05-16 15:49:14 -07004049 private static class NetworkFactoryInfo {
4050 public final String name;
4051 public final Messenger messenger;
4052 public final AsyncChannel asyncChannel;
4053
4054 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4055 this.name = name;
4056 this.messenger = messenger;
4057 this.asyncChannel = asyncChannel;
4058 }
4059 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004061 private void ensureNetworkRequestHasType(NetworkRequest request) {
4062 if (request.type == NetworkRequest.Type.NONE) {
4063 throw new IllegalArgumentException(
4064 "All NetworkRequests in ConnectivityService must have a type");
4065 }
4066 }
4067
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004068 /**
4069 * Tracks info about the requester.
4070 * Also used to notice when the calling process dies so we can self-expire
4071 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004072 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004073 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004074 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004075 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004076 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004077 final int mPid;
4078 final int mUid;
4079 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004080
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004081 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004082 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004083 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004084 mPendingIntent = pi;
4085 messenger = null;
4086 mBinder = null;
4087 mPid = getCallingPid();
4088 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004089 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004090 }
4091
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004092 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004093 super();
4094 messenger = m;
4095 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004096 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004097 mBinder = binder;
4098 mPid = getCallingPid();
4099 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004100 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004101 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102
4103 try {
4104 mBinder.linkToDeath(this, 0);
4105 } catch (RemoteException e) {
4106 binderDied();
4107 }
4108 }
4109
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004110 private void enforceRequestCountLimit() {
4111 synchronized (mUidToNetworkRequestCount) {
4112 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4113 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004114 throw new ServiceSpecificException(
4115 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004116 }
4117 mUidToNetworkRequestCount.put(mUid, networkRequests);
4118 }
4119 }
4120
Robert Greenwalt9258c642014-03-26 16:47:06 -07004121 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004122 if (mBinder != null) {
4123 mBinder.unlinkToDeath(this, 0);
4124 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004125 }
4126
4127 public void binderDied() {
4128 log("ConnectivityService NetworkRequestInfo binderDied(" +
4129 request + ", " + mBinder + ")");
4130 releaseNetworkRequest(request);
4131 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004132
4133 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004134 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004135 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004136 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004137 }
4138
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004139 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4140 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4141 if (badCapability != null) {
4142 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004143 }
4144 }
4145
Erik Kline9d598e12015-07-13 16:37:51 +09004146 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004147 final SortedSet<Integer> thresholds = new TreeSet();
4148 synchronized (nai) {
4149 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4150 if (nri.request.networkCapabilities.hasSignalStrength() &&
4151 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4152 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4153 }
4154 }
4155 }
Erik Kline9d598e12015-07-13 16:37:51 +09004156 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004157 }
4158
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004159 private void updateSignalStrengthThresholds(
4160 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4161 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004162 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004163 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4164
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004165 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004166 String detail;
4167 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4168 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4169 } else {
4170 detail = reason;
4171 }
4172 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4173 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4174 }
4175
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004176 nai.asyncChannel.sendMessage(
4177 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004178 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004179 }
4180
Etan Cohen859748f2017-04-03 17:42:34 -07004181 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4182 if (nc == null) {
4183 return;
4184 }
4185 NetworkSpecifier ns = nc.getNetworkSpecifier();
4186 if (ns == null) {
4187 return;
4188 }
4189 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4190 ns.assertValidFromUid(Binder.getCallingUid());
4191 }
4192
Robert Greenwalt9258c642014-03-26 16:47:06 -07004193 @Override
4194 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004195 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004196 final NetworkRequest.Type type = (networkCapabilities == null)
4197 ? NetworkRequest.Type.TRACK_DEFAULT
4198 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004199 // If the requested networkCapabilities is null, take them instead from
4200 // the default network request. This allows callers to keep track of
4201 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004202 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004203 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004204 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004205 enforceAccessPermission();
4206 } else {
4207 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4208 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004209 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4210 // of the app when the request is filed, but we never change the request if the app
4211 // changes network state. http://b/29964605
4212 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004213 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004214 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004215 // Set the UID range for this request to the single UID of the requester.
4216 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4217 // are no visible methods to set the UIDs, an app could use reflection to try and get
4218 // networks for other apps so it's essential that the UIDs are overwritten.
4219 // TODO : don't forcefully set the UID when communicating with processes
4220 // that have the NETWORK_SETTINGS permission.
4221 networkCapabilities.setSingleUid(Binder.getCallingUid());
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004222
Etan Cohenba07c8c2017-02-05 10:42:27 -08004223 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004224 throw new IllegalArgumentException("Bad timeout specified");
4225 }
Etan Cohen859748f2017-04-03 17:42:34 -07004226 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004227
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004228 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004229 nextNetworkRequestId(), type);
4230 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004231 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004232
4233 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004234 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004235 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004236 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004237 }
4238 return networkRequest;
4239 }
4240
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004241 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004242 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004243 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004244 } else {
4245 enforceChangePermission();
4246 }
4247 }
4248
fenglub15e72b2015-03-20 11:29:56 -07004249 @Override
fengludb571472015-04-21 17:12:05 -07004250 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004251 enforceAccessPermission();
4252 NetworkAgentInfo nai = null;
4253 if (network == null) {
4254 return false;
4255 }
4256 synchronized (mNetworkForNetId) {
4257 nai = mNetworkForNetId.get(network.netId);
4258 }
4259 if (nai != null) {
4260 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4261 return true;
4262 }
4263 return false;
4264 }
4265
Felipe Lemeee27cab2016-06-20 16:36:29 -07004266 private boolean isSystem(int uid) {
4267 return uid < Process.FIRST_APPLICATION_UID;
4268 }
fenglub15e72b2015-03-20 11:29:56 -07004269
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004270 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004271 final int uid = Binder.getCallingUid();
4272 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004273 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004274 return;
4275 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004276 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4277 // Policy already enforced.
4278 return;
4279 }
4280 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4281 // If UID is restricted, don't allow them to bring up metered APNs.
4282 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004283 }
4284 }
4285
Robert Greenwalt9258c642014-03-26 16:47:06 -07004286 @Override
4287 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4288 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004289 checkNotNull(operation, "PendingIntent cannot be null.");
4290 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4291 enforceNetworkRequestPermissions(networkCapabilities);
4292 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004293 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004294 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004295 // TODO : don't forcefully set the UID when communicating with processes
4296 // that have the NETWORK_SETTINGS permission.
4297 networkCapabilities.setSingleUid(Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004298
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004299 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004300 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4301 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004302 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004303 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4304 nri));
4305 return networkRequest;
4306 }
4307
Jeremy Joslin79294842014-12-03 17:15:28 -08004308 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4309 mHandler.sendMessageDelayed(
4310 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4311 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4312 }
4313
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004314 @Override
4315 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004316 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004317 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4318 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004319 }
4320
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004321 // In order to implement the compatibility measure for pre-M apps that call
4322 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4323 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4324 // This ensures it has permission to do so.
4325 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4326 if (nc == null) {
4327 return false;
4328 }
4329 int[] transportTypes = nc.getTransportTypes();
4330 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4331 return false;
4332 }
4333 try {
4334 mContext.enforceCallingOrSelfPermission(
4335 android.Manifest.permission.ACCESS_WIFI_STATE,
4336 "ConnectivityService");
4337 } catch (SecurityException e) {
4338 return false;
4339 }
4340 return true;
4341 }
4342
Robert Greenwalt9258c642014-03-26 16:47:06 -07004343 @Override
4344 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4345 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004346 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4347 enforceAccessPermission();
4348 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004349
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004350 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004351 // TODO : don't forcefully set the UIDs when communicating with processes
4352 // that have the NETWORK_SETTINGS permission.
4353 nc.setSingleUid(Binder.getCallingUid());
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004354 if (!ConnectivityManager.checkChangePermission(mContext)) {
4355 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4356 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4357 // onLost and onAvailable callbacks when networks move in and out of the background.
4358 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4359 // can't request networks.
4360 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4361 }
Etan Cohen859748f2017-04-03 17:42:34 -07004362 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004363
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004364 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004365 NetworkRequest.Type.LISTEN);
4366 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004367 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004368
4369 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4370 return networkRequest;
4371 }
4372
4373 @Override
4374 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4375 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004376 checkNotNull(operation, "PendingIntent cannot be null.");
4377 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4378 enforceAccessPermission();
4379 }
Etan Cohen859748f2017-04-03 17:42:34 -07004380 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004381
Chalard Jeandda156a2018-01-10 21:19:32 +09004382 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4383 // TODO : don't forcefully set the UIDs when communicating with processes
4384 // that have the NETWORK_SETTINGS permission.
4385 nc.setSingleUid(Binder.getCallingUid());
4386
4387 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004388 NetworkRequest.Type.LISTEN);
4389 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004390 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004391
4392 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004393 }
4394
Erik Klineacdd6392016-07-07 16:50:58 +09004395 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004396 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004397 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004398 mHandler.sendMessage(mHandler.obtainMessage(
4399 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004400 }
4401
4402 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004403 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004404 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004405 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4406 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004407 }
4408
Robert Greenwalta67be032014-05-16 15:49:14 -07004409 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004410 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004411 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4412 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4413 }
4414
4415 @Override
4416 public void unregisterNetworkFactory(Messenger messenger) {
4417 enforceConnectivityInternalPermission();
4418 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4419 }
4420
4421 private void handleUnregisterNetworkFactory(Messenger messenger) {
4422 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4423 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004424 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004425 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004426 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004427 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004428 }
4429
Robert Greenwalt7b816022014-04-18 15:25:25 -07004430 /**
4431 * NetworkAgentInfo supporting a request by requestId.
4432 * These have already been vetted (their Capabilities satisfy the request)
4433 * and the are the highest scored network available.
4434 * the are keyed off the Requests requestId.
4435 */
Hugo Benichicd952782017-09-20 11:20:14 +09004436 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4437 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004438 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4439 new SparseArray<NetworkAgentInfo>();
4440
Paul Jensen31a94f42015-02-13 14:18:39 -05004441 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4442 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004443 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4444 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004445 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4446 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4447 // there may not be a strict 1:1 correlation between the two.
4448 @GuardedBy("mNetworkForNetId")
4449 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004450
Robert Greenwalt7b816022014-04-18 15:25:25 -07004451 // NetworkAgentInfo keyed off its connecting messenger
4452 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004453 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004454 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4455 new HashMap<Messenger, NetworkAgentInfo>();
4456
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004457 @GuardedBy("mBlockedAppUids")
4458 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4459
Paul Jensen2c311d62014-11-17 12:34:51 -05004460 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004461 private final NetworkRequest mDefaultRequest;
4462
Erik Klineda4bfa82015-04-30 12:58:40 +09004463 // Request used to optionally keep mobile data active even when higher
4464 // priority networks like Wi-Fi are active.
4465 private final NetworkRequest mDefaultMobileDataRequest;
4466
Hugo Benichicd952782017-09-20 11:20:14 +09004467 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4468 synchronized (mNetworkForRequestId) {
4469 return mNetworkForRequestId.get(requestId);
4470 }
4471 }
4472
4473 private void clearNetworkForRequest(int requestId) {
4474 synchronized (mNetworkForRequestId) {
4475 mNetworkForRequestId.remove(requestId);
4476 }
4477 }
4478
4479 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4480 synchronized (mNetworkForRequestId) {
4481 mNetworkForRequestId.put(requestId, nai);
4482 }
4483 }
4484
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004485 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004486 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004487 }
4488
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004489 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004490 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004491 }
4492
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004493 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4494 return nri.request.requestId == mDefaultRequest.requestId;
4495 }
4496
Paul Jensen31a94f42015-02-13 14:18:39 -05004497 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004498 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004499 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004500 enforceConnectivityInternalPermission();
4501
Rubin Xu1bb5c082017-09-05 18:40:49 +01004502 LinkProperties lp = new LinkProperties(linkProperties);
4503 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004504 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4505 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004506 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004507 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4508 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004509 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004510 synchronized (this) {
4511 nai.networkMonitor.systemReady = mSystemReady;
4512 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004513 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4514 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004515 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004516 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004517 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004518 }
4519
4520 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4521 if (VDBG) log("Got NetworkAgent Messenger");
4522 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004523 synchronized (mNetworkForNetId) {
4524 mNetworkForNetId.put(na.network.netId, na);
4525 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004526 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4527 NetworkInfo networkInfo = na.networkInfo;
4528 na.networkInfo = null;
4529 updateNetworkInfo(na, networkInfo);
Chalard Jeanf213ca12018-01-16 18:43:05 +09004530 updateUids(na, null, na.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004531 }
4532
4533 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4534 LinkProperties newLp = networkAgent.linkProperties;
4535 int netId = networkAgent.network.netId;
4536
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004537 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4538 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004539 if (networkAgent.clatd != null) {
4540 networkAgent.clatd.fixupLinkProperties(oldLp);
4541 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004542
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004543 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004544 updateMtu(newLp, oldLp);
4545 // TODO - figure out what to do for clat
4546// for (LinkProperties lp : newLp.getStackedLinks()) {
4547// updateMtu(lp, null);
4548// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004549 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004550
Erik Kline94887872016-04-05 13:30:49 +09004551 updateRoutes(newLp, oldLp, netId);
4552 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004553
Hugo Benichib577d652017-06-27 15:13:20 +09004554 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004555 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004556 if (isDefaultNetwork(networkAgent)) {
4557 handleApplyDefaultProxy(newLp.getHttpProxy());
4558 } else {
4559 updateProxy(newLp, oldLp, networkAgent);
4560 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004561 // TODO - move this check to cover the whole function
4562 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004563 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004564 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4565 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004566
4567 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004568 }
4569
Joel Scherpelz668370b2017-06-08 15:35:21 +09004570 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004571 // Marks are only available on WiFi interaces. Checking for
4572 // marks on unsupported interfaces is harmless.
4573 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4574 return;
4575 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004576
Joel Scherpelz668370b2017-06-08 15:35:21 +09004577 int mark = mContext.getResources().getInteger(
4578 com.android.internal.R.integer.config_networkWakeupPacketMark);
4579 int mask = mContext.getResources().getInteger(
4580 com.android.internal.R.integer.config_networkWakeupPacketMask);
4581
4582 // Mask/mark of zero will not detect anything interesting.
4583 // Don't install rules unless both values are nonzero.
4584 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004585 return;
4586 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004587
4588 final String prefix = "iface:" + iface;
4589 try {
4590 if (add) {
4591 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4592 } else {
4593 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4594 }
4595 } catch (Exception e) {
4596 loge("Exception modifying wakeup packet monitoring: " + e);
4597 }
4598
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004599 }
4600
4601 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4602 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004603 CompareResult<String> interfaceDiff = new CompareResult<String>(
4604 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4605 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004606 for (String iface : interfaceDiff.added) {
4607 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004608 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004609 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004610 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004611 } catch (Exception e) {
4612 loge("Exception adding interface: " + e);
4613 }
4614 }
4615 for (String iface : interfaceDiff.removed) {
4616 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004617 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004618 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004619 mNetd.removeInterfaceFromNetwork(iface, netId);
4620 } catch (Exception e) {
4621 loge("Exception removing interface: " + e);
4622 }
4623 }
4624 }
4625
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004626 /**
4627 * Have netd update routes from oldLp to newLp.
4628 * @return true if routes changed between oldLp and newLp
4629 */
4630 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004631 // Compare the route diff to determine which routes should be added and removed.
4632 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4633 oldLp != null ? oldLp.getAllRoutes() : null,
4634 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004635
4636 // add routes before removing old in case it helps with continuous connectivity
4637
4638 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4639 for (RouteInfo route : routeDiff.added) {
4640 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004641 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004642 try {
4643 mNetd.addRoute(netId, route);
4644 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004645 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4646 loge("Exception in addRoute for non-gateway: " + e);
4647 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004648 }
4649 }
4650 for (RouteInfo route : routeDiff.added) {
4651 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004652 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004653 try {
4654 mNetd.addRoute(netId, route);
4655 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004656 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4657 loge("Exception in addRoute for gateway: " + e);
4658 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004659 }
4660 }
4661
4662 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004663 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004664 try {
4665 mNetd.removeRoute(netId, route);
4666 } catch (Exception e) {
4667 loge("Exception in removeRoute: " + e);
4668 }
4669 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004670 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004671 }
Erik Kline41368502015-06-17 13:19:54 +09004672
Erik Kline94887872016-04-05 13:30:49 +09004673 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4674 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4675 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004676 }
Erik Kline94887872016-04-05 13:30:49 +09004677
Erik Kline1742fe12017-12-13 19:40:49 +09004678 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4679 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4680
Erik Klinea24d4592018-01-11 21:07:29 +09004681 if (DBG) {
4682 final Collection<InetAddress> dnses = newLp.getDnsServers();
4683 log("Setting DNS servers for network " + netId + " to " + dnses);
4684 }
Erik Kline94887872016-04-05 13:30:49 +09004685 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004686 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004687 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004688 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004689 }
Erik Kline4edba012017-04-07 15:29:29 +09004690 }
4691
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004692 private String getNetworkPermission(NetworkCapabilities nc) {
4693 // TODO: make these permission strings AIDL constants instead.
4694 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4695 return NetworkManagementService.PERMISSION_SYSTEM;
4696 }
4697 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4698 return NetworkManagementService.PERMISSION_NETWORK;
4699 }
4700 return null;
4701 }
4702
Paul Jensen3d194ea2015-06-16 14:27:36 -04004703 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004704 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4705 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4706 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004707 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004708 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004709 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004710 if (nai.everConnected &&
4711 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4712 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004713 // does not cause any request (that is not a listen) currently matching that agent to
4714 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004715 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004716 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004717 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004718 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004719 }
4720
Paul Jensen3d194ea2015-06-16 14:27:36 -04004721 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004722 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004723 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004724 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004725 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004726 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004727 }
Paul Jensene0988542015-06-25 15:30:08 -04004728 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004729 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004730 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004731 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004732 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004733 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004734 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004735 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004736 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004737 }
4738
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004739 return newNc;
4740 }
4741
4742 /**
4743 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4744 *
4745 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4746 * capabilities we manage and store in {@code nai}, such as validated status and captive
4747 * portal status)
4748 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4749 * potentially triggers rematches.
4750 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4751 * change.)
4752 *
4753 * @param oldScore score of the network before any of the changes that prompted us
4754 * to call this function.
4755 * @param nai the network having its capabilities updated.
4756 * @param nc the new network capabilities.
4757 */
4758 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4759 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4760
4761 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004762
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004763 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004764 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004765 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004766 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004767 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004768 } catch (RemoteException e) {
4769 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004770 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004771 }
4772
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004773 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004774 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004775 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004776 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004777 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004778
Chalard Jeanf213ca12018-01-16 18:43:05 +09004779 updateUids(nai, prevNc, newNc);
4780
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004781 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004782 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4783 // the change we're processing can't affect any requests, it can only affect the listens
4784 // on this network. We might have been called by rematchNetworkAndRequests when a
4785 // network changed foreground state.
4786 processListenRequests(nai, true);
4787 } else {
4788 // If the requestable capabilities have changed or the score changed, we can't have been
4789 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004790 rematchAllNetworksAndRequests(nai, oldScore);
4791 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004792 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004793
4794 // Report changes that are interesting for network statistics tracking.
4795 if (prevNc != null) {
4796 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004797 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004798 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004799 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004800 if (meteredChanged || roamingChanged) {
4801 notifyIfacesChangedForNetworkStats();
4802 }
4803 }
4804
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004805 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004806 // Tell VPNs about updated capabilities, since they may need to
4807 // bubble those changes through.
4808 synchronized (mVpns) {
4809 for (int i = 0; i < mVpns.size(); i++) {
4810 final Vpn vpn = mVpns.valueAt(i);
4811 vpn.updateCapabilities();
4812 }
4813 }
4814 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004815 }
4816
Chalard Jeanf213ca12018-01-16 18:43:05 +09004817 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4818 NetworkCapabilities newNc) {
4819 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4820 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4821 if (null == prevRanges) prevRanges = new ArraySet<>();
4822 if (null == newRanges) newRanges = new ArraySet<>();
4823 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4824
4825 prevRanges.removeAll(newRanges);
4826 newRanges.removeAll(prevRangesCopy);
4827
4828 try {
4829 if (!newRanges.isEmpty()) {
4830 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4831 newRanges.toArray(addedRangesArray);
4832 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4833 }
4834 if (!prevRanges.isEmpty()) {
4835 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4836 prevRanges.toArray(removedRangesArray);
4837 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4838 }
4839 } catch (Exception e) {
4840 // Never crash!
4841 loge("Exception in updateUids: " + e);
4842 }
4843 }
4844
Hugo Benichief502882017-09-01 01:23:32 +00004845 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4846 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4847 // Ignore updates for disconnected networks
4848 return;
4849 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004850 // newLp is already a defensive copy.
4851 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004852 if (VDBG) {
4853 log("Update of LinkProperties for " + nai.name() +
4854 "; created=" + nai.created +
4855 "; everConnected=" + nai.everConnected);
4856 }
4857 LinkProperties oldLp = nai.linkProperties;
4858 synchronized (nai) {
4859 nai.linkProperties = newLp;
4860 }
4861 if (nai.everConnected) {
4862 updateLinkProperties(nai, oldLp);
4863 }
4864 }
4865
Paul Jensenc8b9a742014-09-30 15:37:41 -04004866 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004867 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4868 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004869 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004870 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004871 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4872 }
4873 }
4874
Robert Greenwalt7b816022014-04-18 15:25:25 -07004875 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4876 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004877 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004878 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4879 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004880 }
4881 }
4882
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004883 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4884 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004885 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004886 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004887 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4888 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004889 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004890 sendIntent(nri.mPendingIntent, intent);
4891 }
4892 // else not handled
4893 }
4894
4895 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4896 mPendingIntentWakeLock.acquire();
4897 try {
4898 if (DBG) log("Sending " + pendingIntent);
4899 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4900 } catch (PendingIntent.CanceledException e) {
4901 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4902 mPendingIntentWakeLock.release();
4903 releasePendingNetworkRequest(pendingIntent);
4904 }
4905 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4906 }
4907
4908 @Override
4909 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4910 String resultData, Bundle resultExtras) {
4911 if (DBG) log("Finished sending " + pendingIntent);
4912 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004913 // Release with a delay so the receiving client has an opportunity to put in its
4914 // own request.
4915 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004916 }
4917
Chalard Jeanf19db372018-01-26 19:24:40 +09004918 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004919 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004920 if (nri.messenger == null) {
4921 return; // Default request has no msgr
4922 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004923 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004924 // TODO: check if defensive copies of data is needed.
4925 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004926 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004927 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4928 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004929 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004930 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004931 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004932 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004933 break;
4934 }
4935 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09004936 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeandda156a2018-01-10 21:19:32 +09004937 final NetworkCapabilities nc =
Chalard Jeanf19db372018-01-26 19:24:40 +09004938 networkCapabilitiesWithoutUids(networkAgent.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004939 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004940 break;
4941 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004942 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004943 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004944 break;
4945 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004946 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004947 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004948 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004949 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004950 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004951 String notification = ConnectivityManager.getCallbackName(notificationType);
4952 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004953 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004954 nri.messenger.send(msg);
4955 } catch (RemoteException e) {
4956 // may occur naturally in the race of binder death.
4957 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4958 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004959 }
4960
Hugo Benichidba33db2017-03-23 22:40:44 +09004961 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4962 bundle.putParcelable(t.getClass().getSimpleName(), t);
4963 }
4964
Paul Jensenc8b9a742014-09-30 15:37:41 -04004965 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004966 if (nai.numRequestNetworkRequests() != 0) {
4967 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4968 NetworkRequest nr = nai.requestAt(i);
4969 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004970 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004971 loge("Dead network still had at least " + nr);
4972 break;
4973 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004974 }
4975 nai.asyncChannel.disconnect();
4976 }
4977
Robert Greenwalt7b816022014-04-18 15:25:25 -07004978 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4979 if (oldNetwork == null) {
4980 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4981 return;
4982 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004983 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004984
4985 // If we get here it means that the last linger timeout for this network expired. So there
4986 // must be no other active linger timers, and we must stop lingering.
4987 oldNetwork.clearLingerState();
4988
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004989 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004990 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004991 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004992 } else {
4993 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004994 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4995 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004996 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004997 }
4998
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004999 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005000 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005001 setupDataActivityTracking(newNetwork);
5002 try {
5003 mNetd.setDefaultNetId(newNetwork.network.netId);
5004 } catch (Exception e) {
5005 loge("Exception setting default network :" + e);
5006 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005007
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005008 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005009 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005010 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005011 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005012 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005013 }
5014
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005015 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005016 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5017 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5018 NetworkRequest nr = nri.request;
5019 if (!nr.isListen()) continue;
5020 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5021 nai.removeRequest(nri.request.requestId);
5022 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5023 }
5024 }
5025
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005026 if (capabilitiesChanged) {
5027 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5028 }
5029
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005030 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5031 NetworkRequest nr = nri.request;
5032 if (!nr.isListen()) continue;
5033 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5034 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005035 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005036 }
5037 }
5038 }
5039
Paul Jensen2161a8e2014-09-11 11:00:39 -04005040 // Handles a network appearing or improving its score.
5041 //
5042 // - Evaluates all current NetworkRequests that can be
5043 // satisfied by newNetwork, and reassigns to newNetwork
5044 // any such requests for which newNetwork is the best.
5045 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005046 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005047 // needed. A network is needed if it is the best network for
5048 // one or more NetworkRequests, or if it is a VPN.
5049 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005050 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005051 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005052 //
5053 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5054 // networks that have no chance (i.e. even if validated)
5055 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005056 //
5057 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5058 // it does not remove NetworkRequests that other Networks could better satisfy.
5059 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5060 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5061 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005062 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005063 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005064 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5065 // performed to tear down unvalidated networks that have no chance (i.e. even if
5066 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005067 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005068 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005069 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005070 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005071 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005072 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005073
5074 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5075 final int score = newNetwork.getCurrentScore();
5076
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005077 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005078
Paul Jensen2161a8e2014-09-11 11:00:39 -04005079 // Find and migrate to this Network any NetworkRequests for
5080 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005081 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005082 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005083 NetworkCapabilities nc = newNetwork.networkCapabilities;
5084 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005085 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005086 // Process requests in the first pass and listens in the second pass. This allows us to
5087 // change a network's capabilities depending on which requests it has. This is only
5088 // correct if the change in capabilities doesn't affect whether the network satisfies
5089 // requests or not, and doesn't affect the network's score.
5090 if (nri.request.isListen()) continue;
5091
Hugo Benichicd952782017-09-20 11:20:14 +09005092 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005093 final boolean satisfies = newNetwork.satisfies(nri.request);
5094 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005095 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005096 log("Network " + newNetwork.name() + " was already satisfying" +
5097 " request " + nri.request.requestId + ". No change.");
5098 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005099 keep = true;
5100 continue;
5101 }
5102
5103 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005104 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005105 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005106 // next check if it's better than any current network we're using for
5107 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005108 if (VDBG) {
5109 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005110 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005111 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005112 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005113 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005114 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005116 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005117 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005118 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005119 affectedNetworks.add(currentNetwork);
5120 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005121 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005122 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005123 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005124 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005125 if (!newNetwork.addRequest(nri.request)) {
5126 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5127 }
5128 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005129 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005130 // Tell NetworkFactories about the new score, so they can stop
5131 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005132 // TODO - this could get expensive if we have alot of requests for this
5133 // network. Think about if there is a way to reduce this. Push
5134 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005135 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005136 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005137 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005138 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005139 if (currentNetwork != null) {
5140 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5141 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005142 }
5143 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005144 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005145 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5146 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005147 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005148 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5149 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5150 // This means this code doesn't have to handle the case where "currentNetwork" no
5151 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5152 if (DBG) {
5153 log("Network " + newNetwork.name() + " stopped satisfying" +
5154 " request " + nri.request.requestId);
5155 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005156 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005157 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005158 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005159 sendUpdatedScoreToFactories(nri.request, 0);
5160 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005161 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5162 newNetwork.name() +
5163 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005164 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005165 // TODO: Technically, sending CALLBACK_LOST here is
5166 // incorrect if there is a replacement network currently
5167 // connected that can satisfy nri, which is a request
5168 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005169 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5170 // so this code is only incorrect for a network that loses
5171 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005172 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005173 }
5174 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005175 if (isNewDefault) {
5176 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005177 makeDefault(newNetwork);
5178 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005179 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005180 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005181 // Have a new default network, release the transition wakelock in
5182 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005183 }
5184
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005185 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5186 Slog.wtf(TAG, String.format(
5187 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005188 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005189 }
5190 if (newNetwork.getCurrentScore() != score) {
5191 Slog.wtf(TAG, String.format(
5192 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005193 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005194 }
5195
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005196 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005197 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5198 // If the network went from background to foreground or vice versa, we need to update
5199 // its foreground state. It is safe to do this after rematching the requests because
5200 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5201 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005202 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005203 } else {
5204 processListenRequests(newNetwork, false);
5205 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005206
Paul Jensencf4c2c62015-07-01 14:16:32 -04005207 // do this after the default net is switched, but
5208 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005209 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005210
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005211 // Linger any networks that are no longer needed. This should be done after sending the
5212 // available callback for newNetwork.
5213 for (NetworkAgentInfo nai : affectedNetworks) {
5214 updateLingerState(nai, now);
5215 }
5216 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5217 // does not need to be done in any particular order.
5218 updateLingerState(newNetwork, now);
5219
Paul Jensencf4c2c62015-07-01 14:16:32 -04005220 if (isNewDefault) {
5221 // Maintain the illusion: since the legacy API only
5222 // understands one network at a time, we must pretend
5223 // that the current default network disconnected before
5224 // the new one connected.
5225 if (oldDefaultNetwork != null) {
5226 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5227 oldDefaultNetwork, true);
5228 }
5229 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5230 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5231 notifyLockdownVpn(newNetwork);
5232 }
5233
Robert Greenwalt7b816022014-04-18 15:25:25 -07005234 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005235 // Notify battery stats service about this network, both the normal
5236 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005237 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005238 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005239 final IBatteryStats bs = BatteryStatsService.getService();
5240 final int type = newNetwork.networkInfo.getType();
5241
5242 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5243 bs.noteNetworkInterfaceType(baseIface, type);
5244 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5245 final String stackedIface = stacked.getInterfaceName();
5246 bs.noteNetworkInterfaceType(stackedIface, type);
5247 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5248 }
5249 } catch (RemoteException ignored) {
5250 }
5251
Robert Greenwalt152ed372014-12-17 17:19:53 -08005252 // This has to happen after the notifyNetworkCallbacks as that tickles each
5253 // ConnectivityManager instance so that legacy requests correctly bind dns
5254 // requests to this network. The legacy users are listening for this bcast
5255 // and will generally do a dns request so they can ensureRouteToHost and if
5256 // they do that before the callbacks happen they'll use the default network.
5257 //
5258 // TODO: Is there still a race here? We send the broadcast
5259 // after sending the callback, but if the app can receive the
5260 // broadcast before the callback, it might still break.
5261 //
5262 // This *does* introduce a race where if the user uses the new api
5263 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5264 // they may get old info. Reverse this after the old startUsing api is removed.
5265 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005266 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5267 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005268 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005269 // legacy type tracker filters out repeat adds
5270 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5271 }
5272 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005273
5274 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5275 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5276 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5277 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5278 if (newNetwork.isVPN()) {
5279 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5280 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005281 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005282 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5283 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005284 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005285 if (nai.getLingerExpiry() > 0) {
5286 // This network has active linger timers and no requests, but is not
5287 // lingering. Linger it.
5288 //
5289 // One way (the only way?) this can happen if this network is unvalidated
5290 // and became unneeded due to another network improving its score to the
5291 // point where this network will no longer be able to satisfy any requests
5292 // even if it validates.
5293 updateLingerState(nai, now);
5294 } else {
5295 if (DBG) log("Reaping " + nai.name());
5296 teardownUnneededNetwork(nai);
5297 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005298 }
5299 }
5300 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005301 }
5302
Paul Jensen1c7ba022015-06-16 14:27:36 -04005303 /**
5304 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5305 * being disconnected.
5306 * @param changed If only one Network's score or capabilities have been modified since the last
5307 * time this function was called, pass this Network in this argument, otherwise pass
5308 * null.
5309 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5310 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5311 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5312 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5313 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005314 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005315 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005316 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5317 // to avoid the slowness. It is not simply enough to process just "changed", for
5318 // example in the case where "changed"'s score decreases and another network should begin
5319 // satifying a NetworkRequest that "changed" currently satisfies.
5320
5321 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5322 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5323 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005324 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005325 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005326 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005327 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005328 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5329 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5330 // Rematch higher scoring networks first to prevent requests first matching a lower
5331 // scoring network and then a higher scoring network, which could produce multiple
5332 // callbacks and inadvertently unlinger networks.
5333 Arrays.sort(nais);
5334 for (NetworkAgentInfo nai : nais) {
5335 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005336 // Only reap the last time through the loop. Reaping before all rematching
5337 // is complete could incorrectly teardown a network that hasn't yet been
5338 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005339 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005340 : ReapUnvalidatedNetworks.REAP,
5341 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005342 }
5343 }
5344 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005345
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005346 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005347 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005348 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005349 // For now only update icons for default connection.
5350 // TODO: Update WiFi and cellular icons separately. b/17237507
5351 if (!isDefaultNetwork(nai)) return;
5352
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005353 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005354 // Don't repeat publish.
5355 if (newInetCondition == mDefaultInetConditionPublished) return;
5356
5357 mDefaultInetConditionPublished = newInetCondition;
5358 sendInetConditionBroadcast(nai.networkInfo);
5359 }
5360
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005361 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005362 synchronized (mVpns) {
5363 if (mLockdownTracker != null) {
5364 if (nai != null && nai.isVPN()) {
5365 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5366 } else {
5367 mLockdownTracker.onNetworkInfoChanged();
5368 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005369 }
5370 }
5371 }
5372
Robert Greenwalt7b816022014-04-18 15:25:25 -07005373 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005374 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005375 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005376 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005377 synchronized (networkAgent) {
5378 oldInfo = networkAgent.networkInfo;
5379 networkAgent.networkInfo = newInfo;
5380 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005381 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005382
Robert Greenwalt7b816022014-04-18 15:25:25 -07005383 if (DBG) {
5384 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5385 (oldInfo == null ? "null" : oldInfo.getState()) +
5386 " to " + state);
5387 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005388
Robin Lee585e2482016-05-01 23:00:00 +01005389 if (!networkAgent.created
5390 && (state == NetworkInfo.State.CONNECTED
5391 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005392
5393 // A network that has just connected has zero requests and is thus a foreground network.
5394 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5395
Robert Greenwalt7b816022014-04-18 15:25:25 -07005396 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005397 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005398 if (networkAgent.isVPN()) {
5399 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005400 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5401 (networkAgent.networkMisc == null ||
5402 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005403 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005404 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005405 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005406 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005407 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005408 loge("Error creating network " + networkAgent.network.netId + ": "
5409 + e.getMessage());
5410 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005411 }
Paul Jenseneec75412014-08-04 12:21:19 -04005412 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005413 }
5414
5415 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5416 networkAgent.everConnected = true;
5417
Robert Greenwalt7b816022014-04-18 15:25:25 -07005418 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005419 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005420
Paul Jensenca8f16a2014-05-09 12:47:55 -04005421 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005422 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005423
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005424 if (networkAgent.isVPN()) {
5425 // Temporarily disable the default proxy (not global).
5426 synchronized (mProxyLock) {
5427 if (!mDefaultProxyDisabled) {
5428 mDefaultProxyDisabled = true;
5429 if (mGlobalProxy == null && mDefaultProxy != null) {
5430 sendProxyBroadcast(null);
5431 }
5432 }
5433 }
5434 // TODO: support proxy per network.
5435 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005436
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005437 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5438 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5439 // capabilities, so it only needs to be done once on initial connect, not every time the
5440 // network's capabilities change. Note that we do this before rematching the network,
5441 // so we could decide to tear it down immediately afterwards. That's fine though - on
5442 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5443 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005444 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005445
Paul Jensen2161a8e2014-09-11 11:00:39 -04005446 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005447 final long now = SystemClock.elapsedRealtime();
5448 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005449
5450 // This has to happen after matching the requests, because callbacks are just requests.
5451 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005452 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005453 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005454 if (networkAgent.isVPN()) {
5455 synchronized (mProxyLock) {
5456 if (mDefaultProxyDisabled) {
5457 mDefaultProxyDisabled = false;
5458 if (mGlobalProxy == null && mDefaultProxy != null) {
5459 sendProxyBroadcast(mDefaultProxy);
5460 }
5461 }
5462 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005463 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005464 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005465 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5466 state == NetworkInfo.State.SUSPENDED) {
5467 // going into or coming out of SUSPEND: rescore and notify
5468 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005469 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005470 }
5471 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5472 ConnectivityManager.CALLBACK_SUSPENDED :
5473 ConnectivityManager.CALLBACK_RESUMED));
5474 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005475 }
5476 }
5477
Robert Greenwaltac96c522014-06-03 16:43:57 -07005478 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005479 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005480 if (score < 0) {
5481 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5482 "). Bumping score to min of 0");
5483 score = 0;
5484 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005485
Paul Jensen2161a8e2014-09-11 11:00:39 -04005486 final int oldScore = nai.getCurrentScore();
5487 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005488
Paul Jensen85cf78e2015-06-25 13:25:07 -04005489 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005490
Paul Jensenc8b9a742014-09-30 15:37:41 -04005491 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005492 }
5493
Erik Klinec75d4fa2017-02-15 19:59:17 +09005494 // Notify only this one new request of the current state. Transfer all the
5495 // current state by calling NetworkCapabilities and LinkProperties callbacks
5496 // so that callers can be guaranteed to have as close to atomicity in state
5497 // transfer as can be supported by this current API.
5498 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005499 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005500 if (nri.mPendingIntent != null) {
5501 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5502 // Attempt no subsequent state pushes where intents are involved.
5503 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005504 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005505
5506 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5507 // Whether a network is currently suspended is also an important
5508 // element of state to be transferred (it would not otherwise be
5509 // delivered by any currently available mechanism).
5510 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5511 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5512 }
5513 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5514 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005515 }
5516
Robert Greenwalt8d482522015-06-24 13:23:42 -07005517 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005518 // The NetworkInfo we actually send out has no bearing on the real
5519 // state of affairs. For example, if the default connection is mobile,
5520 // and a request for HIPRI has just gone away, we need to pretend that
5521 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5522 // the state to DISCONNECTED, even though the network is of type MOBILE
5523 // and is still connected.
5524 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5525 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005526 if (state != DetailedState.DISCONNECTED) {
5527 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005528 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005529 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005530 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005531 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5532 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5533 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5534 if (info.isFailover()) {
5535 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5536 nai.networkInfo.setFailover(false);
5537 }
5538 if (info.getReason() != null) {
5539 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5540 }
5541 if (info.getExtraInfo() != null) {
5542 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5543 }
5544 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005545 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005546 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005547 if (newDefaultAgent != null) {
5548 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5549 newDefaultAgent.networkInfo);
5550 } else {
5551 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5552 }
5553 }
5554 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5555 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005556 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005557 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005558 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005559 }
5560 }
5561 }
5562
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005563 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005564 if (VDBG) {
5565 String notification = ConnectivityManager.getCallbackName(notifyType);
5566 log("notifyType " + notification + " for " + networkAgent.name());
5567 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005568 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5569 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005570 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5571 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005572 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5573 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005574 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005575 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005576 } else {
5577 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5578 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005579 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005580 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005581
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005582 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5583 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5584 }
5585
Jeff Sharkey69736342014-12-08 14:50:12 -08005586 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005587 * Returns the list of all interfaces that could be used by network traffic that does not
5588 * explicitly specify a network. This includes the default network, but also all VPNs that are
5589 * currently connected.
5590 *
5591 * Must be called on the handler thread.
5592 */
5593 private Network[] getDefaultNetworks() {
5594 ArrayList<Network> defaultNetworks = new ArrayList<>();
5595 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5596 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5597 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5598 defaultNetworks.add(nai.network);
5599 }
5600 }
5601 return defaultNetworks.toArray(new Network[0]);
5602 }
5603
5604 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005605 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5606 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005607 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005608 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005609 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005610 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005611 } catch (Exception ignored) {
5612 }
5613 }
5614
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005615 @Override
5616 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005617 int user = UserHandle.getUserId(Binder.getCallingUid());
5618 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005619 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005620 return mVpns.get(user).addAddress(address, prefixLength);
5621 }
5622 }
5623
5624 @Override
5625 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005626 int user = UserHandle.getUserId(Binder.getCallingUid());
5627 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005628 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005629 return mVpns.get(user).removeAddress(address, prefixLength);
5630 }
5631 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005632
5633 @Override
5634 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005635 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005636 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005637 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005638 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005639 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005640 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005641 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005642 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005643 }
5644 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005645 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005646
5647 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005648 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005649 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005650 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005651 }
5652
5653 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005654 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5655 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5656 enforceKeepalivePermission();
5657 mKeepaliveTracker.startNattKeepalive(
5658 getNetworkAgentInfoForNetwork(network),
5659 intervalSeconds, messenger, binder,
5660 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5661 }
5662
5663 @Override
5664 public void stopKeepalive(Network network, int slot) {
5665 mHandler.sendMessage(mHandler.obtainMessage(
5666 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5667 }
5668
5669 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005670 public void factoryReset() {
5671 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005672
5673 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5674 return;
5675 }
5676
Robin Lee3b3dd942015-05-12 18:14:58 +01005677 final int userId = UserHandle.getCallingUserId();
5678
Stuart Scottf1fb3972015-04-02 18:00:02 -07005679 // Turn airplane mode off
5680 setAirplaneMode(false);
5681
Stuart Scotte3e314d2015-04-20 14:07:45 -07005682 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5683 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005684 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005685 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005686 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005687 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005688 }
5689
Stuart Scotte3e314d2015-04-20 14:07:45 -07005690 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005691 // Remove always-on package
5692 synchronized (mVpns) {
5693 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5694 if (alwaysOnPackage != null) {
5695 setAlwaysOnVpnPackage(userId, null, false);
5696 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5697 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005698
Hugo Benichi69744342017-11-27 10:57:16 +09005699 // Turn Always-on VPN off
5700 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5701 final long ident = Binder.clearCallingIdentity();
5702 try {
5703 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5704 mLockdownEnabled = false;
5705 setLockdownTracker(null);
5706 } finally {
5707 Binder.restoreCallingIdentity(ident);
5708 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005709 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005710
Hugo Benichi69744342017-11-27 10:57:16 +09005711 // Turn VPN off
5712 VpnConfig vpnConfig = getVpnConfig(userId);
5713 if (vpnConfig != null) {
5714 if (vpnConfig.legacy) {
5715 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5716 } else {
5717 // Prevent this app (packagename = vpnConfig.user) from initiating
5718 // VPN connections in the future without user intervention.
5719 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005720
Hugo Benichi69744342017-11-27 10:57:16 +09005721 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5722 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005723 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005724 }
5725 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005726
5727 Settings.Global.putString(mContext.getContentResolver(),
5728 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005729 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005730
5731 @VisibleForTesting
5732 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5733 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5734 return new NetworkMonitor(context, handler, nai, defaultRequest);
5735 }
Erik Kline48f12f22016-04-14 17:30:59 +09005736
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005737 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005738 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5739 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005740 }
5741
5742 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005743 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5744 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5745 }
5746
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005747 @VisibleForTesting
5748 public boolean hasService(String name) {
5749 return ServiceManager.checkService(name) != null;
5750 }
5751
Hugo Benichi64901e52017-10-19 14:42:40 +09005752 @VisibleForTesting
5753 protected IpConnectivityMetrics.Logger metricsLogger() {
5754 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5755 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005756 }
5757
5758 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005759 int[] transports = nai.networkCapabilities.getTransportTypes();
5760 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005761 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005762
5763 private static boolean toBool(int encodedBoolean) {
5764 return encodedBoolean != 0; // Only 0 means false.
5765 }
5766
5767 private static int encodeBool(boolean b) {
5768 return b ? 1 : 0;
5769 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005770}