blob: a05e1cc67351879dd9030ae293051aa1e32c0ac6 [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;
32import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Hugo Benichia0385682017-03-22 17:07:57 +090033import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080036import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090037import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070038import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070046import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080047import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090048import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070050import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070051import android.net.INetworkPolicyListener;
52import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070053import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080054import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070055import android.net.LinkProperties.CompareResult;
Hugo Benichib577d652017-06-27 15:13:20 +090056import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070057import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070058import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070059import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070060import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080061import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070062import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070063import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070064import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070065import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070066import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040070import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040073import android.net.Uri;
Hugo Benichicfddd682016-05-31 16:28:06 +090074import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090075import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090076import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080078import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070079import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040080import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070082import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070083import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070084import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Looper;
86import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070087import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070088import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090089import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070090import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070091import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070092import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080093import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090094import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +090095import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090096import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070097import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040098import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080099import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700100import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700101import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700102import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700103import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700104import android.util.LocalLog;
105import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600106import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800107import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700108import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500109import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700110import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700111import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800112
Wink Savilleab9321d2013-06-29 21:10:57 -0700113import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400114import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400115import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700116import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700117import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700118import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700119import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800120import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700121import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700122import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600123import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700124import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900125import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900126import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700127import com.android.internal.util.XmlUtils;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900128import com.android.server.LocalServices;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700129import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400130import com.android.server.connectivity.DataConnectionStats;
Hugo Benichi64901e52017-10-19 14:42:40 +0900131import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900132import com.android.server.connectivity.KeepaliveTracker;
Charles Hea0a87e82017-05-15 17:07:18 +0100133import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700134import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700135import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600136import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400137import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900138import com.android.server.connectivity.NetworkNotificationManager;
139import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400140import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700141import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800142import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700143import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900144import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700145import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700146import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900147import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600148
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700149import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700150
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700151import org.xmlpull.v1.XmlPullParser;
152import org.xmlpull.v1.XmlPullParserException;
153
154import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700156import java.io.FileNotFoundException;
157import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700158import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700160import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700161import java.net.InetAddress;
162import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700163import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700164import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700165import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700166import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700167import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700168import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700169import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700170import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700171import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600172import java.util.SortedSet;
173import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800174
175/**
176 * @hide
177 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800178public class ConnectivityService extends IConnectivityManager.Stub
179 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900180 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800181
Erik Kline7747fd42017-05-12 16:52:48 +0900182 public static final String DIAG_ARG = "--diag";
183 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900184 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900185
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900186 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700187 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800188
Jake Hamby786e71a2014-02-06 14:43:50 -0800189 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900190 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700191
Jeff Sharkey899223b2012-08-04 15:24:58 -0700192 // TODO: create better separation between radio types and network types
193
Robert Greenwalt42acef32009-08-12 16:08:25 -0700194 // how long to wait before switching back to a radio's default network
195 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
196 // system property that can override the above value
197 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
198 "android.telephony.apn-restore";
199
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900200 // How long to wait before putting up a "This network doesn't have an Internet connection,
201 // connect anyway?" dialog after the user selects a network that doesn't validate.
202 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
203
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900204 // Default to 30s linger time-out. Modifiable only for testing.
205 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
206 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
207 @VisibleForTesting
208 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
209
Jeremy Joslin79294842014-12-03 17:15:28 -0800210 // How long to delay to removal of a pending intent based request.
211 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
212 private final int mReleasePendingIntentDelayMs;
213
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900214 private MockableSystemProperties mSystemProperties;
215
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800216 private Tethering mTethering;
217
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700218 private final PermissionMonitor mPermissionMonitor;
219
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700220 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700221
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700222 @GuardedBy("mVpns")
223 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700224
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700225 private boolean mLockdownEnabled;
226 private LockdownVpnTracker mLockdownTracker;
227
Erik Klineda4bfa82015-04-30 12:58:40 +0900228 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700230 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700231 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800233 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800234
235 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700236 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800237
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700238 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800239 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700240 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900241 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700242
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700243 private String mCurrentTcpBufferSizes;
244
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700245 private static final int ENABLED = 1;
246 private static final int DISABLED = 0;
247
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900248 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900249 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
250 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900251
Paul Jensenb10e37f2014-11-25 12:33:08 -0500252 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400253 // Tear down networks that have no chance (e.g. even if validated) of becoming
254 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500255 // all networks have been rematched against all NetworkRequests.
256 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400257 // Don't reap networks. This should be passed when some networks have not yet been
258 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500259 DONT_REAP
260 };
261
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900262 private enum UnneededFor {
263 LINGER, // Determine whether this network is unneeded and should be lingered.
264 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
265 }
266
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700268 * used internally to change our mobile data enabled flag
269 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700270 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700271
272 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700273 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700274 * from one net to another. Clear happens when we get a new
275 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
276 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700277 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700278 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700279
Robert Greenwalt434203a2010-10-11 16:00:27 -0700280 /**
281 * used internally to reload global proxy settings
282 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700283 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700284
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700285 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400286 * PAC manager has received new port.
287 */
288 private static final int EVENT_PROXY_HAS_CHANGED = 16;
289
Robert Greenwalte049c232014-04-11 15:53:27 -0700290 /**
291 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700292 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700293 */
294 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
295
Robert Greenwalt7b816022014-04-18 15:25:25 -0700296 /**
297 * used internally when registering NetworkAgents
298 * obj = Messenger
299 */
300 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
301
Robert Greenwalt9258c642014-03-26 16:47:06 -0700302 /**
303 * used to add a network request
304 * includes a NetworkRequestInfo
305 */
306 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
307
308 /**
309 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900310 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700311 * cancel it.
312 * includes a NetworkRequestInfo
313 */
314 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
315
316 /**
317 * used to add a network listener - no request
318 * includes a NetworkRequestInfo
319 */
320 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
321
322 /**
323 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400324 * arg1 = UID of caller
325 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700326 */
327 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
328
Robert Greenwalta67be032014-05-16 15:49:14 -0700329 /**
330 * used internally when registering NetworkFactories
331 * obj = Messenger
332 */
333 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
334
Robert Greenwalt27711812014-06-25 16:45:57 -0700335 /**
336 * used internally to expire a wakelock when transitioning
337 * from one net to another. Expire happens when we fail to find
338 * a new network (typically after 1 minute) -
339 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
340 * a replacement network.
341 */
342 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
343
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700344 /**
345 * Used internally to indicate the system is ready.
346 */
347 private static final int EVENT_SYSTEM_READY = 25;
348
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800349 /**
350 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400351 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800352 */
353 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
354
355 /**
356 * used to remove a pending intent and its associated network request.
357 * arg1 = UID of caller
358 * obj = PendingIntent
359 */
360 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
361
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900362 /**
363 * used to specify whether a network should be used even if unvalidated.
364 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
365 * arg2 = whether to remember this choice in the future (1 or 0)
366 * obj = network
367 */
368 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
369
370 /**
371 * used to ask the user to confirm a connection to an unvalidated network.
372 * obj = network
373 */
374 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700375
Erik Klineda4bfa82015-04-30 12:58:40 +0900376 /**
377 * used internally to (re)configure mobile data always-on settings.
378 */
379 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
380
Paul Jensen694f2b82015-06-17 14:15:39 -0400381 /**
382 * used to add a network listener with a pending intent
383 * obj = NetworkRequestInfo
384 */
385 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
386
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900387 /**
388 * used to specify whether a network should not be penalized when it becomes unvalidated.
389 */
390 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
391
392 /**
393 * used to trigger revalidation of a network.
394 */
395 private static final int EVENT_REVALIDATE_NETWORK = 36;
396
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900397 private static String eventName(int what) {
398 return sMagicDecoderRing.get(what, Integer.toString(what));
399 }
400
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900401 /** Handler thread used for both of the handlers below. */
402 @VisibleForTesting
403 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700404 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700405 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700406 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700407 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700408
Mike Lockwood0f79b542009-08-14 14:18:49 -0400409 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800410 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400411
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700412 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700413 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800414 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700415
Robert Greenwalt434203a2010-10-11 16:00:27 -0700416 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400417 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700418 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700419 private boolean mDefaultProxyDisabled = false;
420
Robert Greenwalt434203a2010-10-11 16:00:27 -0700421 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400422 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700423
Jason Monk602b2322013-07-03 17:04:33 -0400424 private PacManager mPacManager = null;
425
Erik Klineda4bfa82015-04-30 12:58:40 +0900426 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700427
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400428 private UserManager mUserManager;
429
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700430 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700431 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700432
Robert Greenwalt50393202011-06-21 17:26:14 -0700433 // the set of network types that can only be enabled by system/sig apps
434 List mProtectedNetworks;
435
John Spurlockbf991a82013-06-24 14:20:23 -0400436 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700437
Wink Savilleab9321d2013-06-29 21:10:57 -0700438 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400439
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900440 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900441 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900442 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900443
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700444 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
445 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700446 private final static int MAX_NET_ID = 65535;
447 private int mNextNetId = MIN_NET_ID;
448
Robert Greenwalt34524f02014-05-18 16:22:10 -0700449 // sequence number of NetworkRequests
450 private int mNextNetworkRequestId = 1;
451
Erik Kline7523eb32015-07-09 18:24:03 +0900452 // NetworkRequest activity String log entries.
453 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
454 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
455
Hugo Benichic2ae2872016-07-11 11:05:12 +0900456 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900457 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900458 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
459
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900460 private static final int MAX_WAKELOCK_LOGS = 20;
461 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900462 private int mTotalWakelockAcquisitions = 0;
463 private int mTotalWakelockReleases = 0;
464 private long mTotalWakelockDurationMs = 0;
465 private long mMaxWakelockDurationMs = 0;
466 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900467
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700468 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
469 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400470 private static class ValidationLog {
471 final Network mNetwork;
472 final String mNetworkExtraInfo;
473 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700474
Paul Jensen0808eb82016-06-03 13:51:21 -0400475 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
476 mNetwork = network;
477 mNetworkExtraInfo = networkExtraInfo;
478 mLog = log;
479 }
480 }
481 private final ArrayDeque<ValidationLog> mValidationLogs =
482 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
483
484 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900485 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700486 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
487 mValidationLogs.removeLast();
488 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400489 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700490 }
491 }
492
Hugo Benichif9fdf872016-07-28 17:53:06 +0900493 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900494
Erik Kline065ab6e2016-10-02 18:02:14 +0900495 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900496 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900497
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700498 /**
499 * Implements support for the legacy "one network per network type" model.
500 *
501 * We used to have a static array of NetworkStateTrackers, one for each
502 * network type, but that doesn't work any more now that we can have,
503 * for example, more that one wifi network. This class stores all the
504 * NetworkAgentInfo objects that support a given type, but the legacy
505 * API will only see the first one.
506 *
507 * It serves two main purposes:
508 *
509 * 1. Provide information about "the network for a given type" (since this
510 * API only supports one).
511 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
512 * the first network for a given type changes, or if the default network
513 * changes.
514 */
515 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900517 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900518 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900519
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700520 /**
521 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
522 * Each list holds references to all NetworkAgentInfos that are used to
523 * satisfy requests for that network type.
524 *
525 * This array is built out at startup such that an unsupported network
526 * doesn't get an ArrayList instance, making this a tristate:
527 * unsupported, supported but not active and active.
528 *
529 * The actual lists are populated when we scan the network types that
530 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900531 *
532 * Threading model:
533 * - addSupportedType() is only called in the constructor
534 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
535 * They are therefore not thread-safe with respect to each other.
536 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
537 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
538 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700539 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900540 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700541
542 public LegacyTypeTracker() {
543 mTypeLists = (ArrayList<NetworkAgentInfo>[])
544 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
545 }
546
547 public void addSupportedType(int type) {
548 if (mTypeLists[type] != null) {
549 throw new IllegalStateException(
550 "legacy list for type " + type + "already initialized");
551 }
552 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
553 }
554
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700555 public boolean isTypeSupported(int type) {
556 return isNetworkTypeValid(type) && mTypeLists[type] != null;
557 }
558
559 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900560 synchronized (mTypeLists) {
561 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
562 return mTypeLists[type].get(0);
563 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900565 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700566 }
567
Robert Greenwalt8d482522015-06-24 13:23:42 -0700568 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900569 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900570 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700571 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900572 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900573 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900574 }
575 }
576
577 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700578 public void add(int type, NetworkAgentInfo nai) {
579 if (!isTypeSupported(type)) {
580 return; // Invalid network type.
581 }
582 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
583
584 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
585 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700586 return;
587 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900588 synchronized (mTypeLists) {
589 list.add(nai);
590 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900591
592 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900593 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900594 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700595 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
596 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 }
599
Lorenzo Colittia793a672014-07-31 23:20:17 +0900600 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900601 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900602 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
603 if (list == null || list.isEmpty()) {
604 return;
605 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900606 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607
Hugo Benichi78caa2582016-06-21 09:48:07 +0900608 synchronized (mTypeLists) {
609 if (!list.remove(nai)) {
610 return;
611 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900612 }
613
Robert Greenwalt8d482522015-06-24 13:23:42 -0700614 final DetailedState state = DetailedState.DISCONNECTED;
615
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900616 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700617 maybeLogBroadcast(nai, state, type, wasDefault);
618 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900619 }
620
621 if (!list.isEmpty() && wasFirstNetwork) {
622 if (DBG) log("Other network available for type " + type +
623 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900624 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700625 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
626 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900627 }
628 }
629
630 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900631 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
632 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700633 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900634 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700635 }
636 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700637
Robert Greenwalt8d482522015-06-24 13:23:42 -0700638 // send out another legacy broadcast - currently only used for suspend/unsuspend
639 // toggle
640 public void update(NetworkAgentInfo nai) {
641 final boolean isDefault = isDefaultNetwork(nai);
642 final DetailedState state = nai.networkInfo.getDetailedState();
643 for (int type = 0; type < mTypeLists.length; type++) {
644 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700645 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900646 final boolean isFirst = contains && (nai == list.get(0));
647 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700648 maybeLogBroadcast(nai, state, type, isDefault);
649 sendLegacyNetworkBroadcast(nai, state, type);
650 }
651 }
652 }
653
Lorenzo Colittia793a672014-07-31 23:20:17 +0900654 private String naiToString(NetworkAgentInfo nai) {
655 String name = (nai != null) ? nai.name() : "null";
656 String state = (nai.networkInfo != null) ?
657 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
658 "???/???";
659 return name + " " + state;
660 }
661
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700662 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900663 pw.println("mLegacyTypeTracker:");
664 pw.increaseIndent();
665 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700666 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900667 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700668 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900669 pw.println();
670 pw.println("Current state:");
671 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900672 synchronized (mTypeLists) {
673 for (int type = 0; type < mTypeLists.length; type++) {
674 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
675 for (NetworkAgentInfo nai : mTypeLists[type]) {
676 pw.println(type + " " + naiToString(nai));
677 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900678 }
679 }
680 pw.decreaseIndent();
681 pw.decreaseIndent();
682 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700683 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700684 }
685 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
686
Jeff Sharkey899223b2012-08-04 15:24:58 -0700687 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700688 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900689 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
690 }
691
692 @VisibleForTesting
693 protected ConnectivityService(Context context, INetworkManagementService netManager,
694 INetworkStatsService statsService, INetworkPolicyManager policyManager,
695 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800696 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800697
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900698 mSystemProperties = getSystemProperties();
699
Hugo Benichif9fdf872016-07-28 17:53:06 +0900700 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900701 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900702 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900703 mNetworkRequests.put(mDefaultRequest, defaultNRI);
704 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900705
706 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900707 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700708
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900709 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900710 mHandlerThread.start();
711 mHandler = new InternalHandler(mHandlerThread.getLooper());
712 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700713
Jeremy Joslin79294842014-12-03 17:15:28 -0800714 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
715 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
716
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900717 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900718
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700719 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700720 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800721 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700722 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900723 mPolicyManagerInternal = checkNotNull(
724 LocalServices.getService(NetworkPolicyManagerInternal.class),
725 "missing NetworkPolicyManagerInternal");
726
Jeff Sharkey82f85212012-08-24 11:17:25 -0700727 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700728 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700729
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700730 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900731 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700732 } catch (RemoteException e) {
733 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700734 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700735 }
736
737 final PowerManager powerManager = (PowerManager) context.getSystemService(
738 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700739 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
740 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
741 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800742 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700743
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700744 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700745
Wink Saville51f456f2013-04-23 14:26:51 -0700746 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900747 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700748 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700749 String[] naStrings = context.getResources().getStringArray(
750 com.android.internal.R.array.networkAttributes);
751 for (String naString : naStrings) {
752 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700753 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700754 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700755 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800756 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700757 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700758 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700759 }
Wink Saville51f456f2013-04-23 14:26:51 -0700760 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
761 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
762 n.type);
763 continue;
764 }
Wink Saville975c8482011-04-07 14:23:45 -0700765 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800766 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700767 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700768 continue;
769 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700770 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700771
Wink Saville975c8482011-04-07 14:23:45 -0700772 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700773 mNetworksDefined++;
774 } catch(Exception e) {
775 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700776 }
777 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700778
779 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
780 if (mNetConfigs[TYPE_VPN] == null) {
781 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
782 // don't need to add TYPE_VPN to mNetConfigs.
783 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
784 mNetworksDefined++; // used only in the log() statement below.
785 }
786
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900787 // Do the same for Ethernet, since it's often not specified in the configs, although many
788 // devices can use it via USB host adapters.
789 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
790 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
791 mNetworksDefined++;
792 }
793
Wink Saville5e56bc52013-07-29 15:00:57 -0700794 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700795
Robert Greenwalt50393202011-06-21 17:26:14 -0700796 mProtectedNetworks = new ArrayList<Integer>();
797 int[] protectedNetworks = context.getResources().getIntArray(
798 com.android.internal.R.array.config_protectedNetworks);
799 for (int p : protectedNetworks) {
800 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
801 mProtectedNetworks.add(p);
802 } else {
803 if (DBG) loge("Ignoring protectedNetwork " + p);
804 }
805 }
806
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900807 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
808 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700809
Erik Kline47222fc2017-04-30 19:36:15 +0900810 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800811
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700812 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
813
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700814 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700815 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100816 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700817 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700818 intentFilter.addAction(Intent.ACTION_USER_ADDED);
819 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000820 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700821 mContext.registerReceiverAsUser(
822 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000823 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
824 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900825
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700826 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700827 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700828 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700829 } catch (RemoteException e) {
830 loge("Error registering observer :" + e);
831 }
832
Erik Klineda4bfa82015-04-30 12:58:40 +0900833 mSettingsObserver = new SettingsObserver(mContext, mHandler);
834 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800835
John Spurlockbf991a82013-06-24 14:20:23 -0400836 mDataConnectionStats = new DataConnectionStats(mContext);
837 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400838
Jason Monkdecd2952013-10-10 14:02:51 -0400839 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700840
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400841 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900842
843 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900844 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
845 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900846
847 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
848 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
849 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
850 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
851 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
852 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
853 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900854
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900855 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900856 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900857 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800858 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700859
Erik Kline47222fc2017-04-30 19:36:15 +0900860 private Tethering makeTethering() {
861 // TODO: Move other elements into @Overridden getters.
862 final TetheringDependencies deps = new TetheringDependencies();
863 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
864 IoThread.get().getLooper(), new MockableSystemProperties(),
865 deps);
866 }
867
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900868 private NetworkRequest createInternetRequestForTransport(
869 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900870 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900871 netCap.addCapability(NET_CAPABILITY_INTERNET);
872 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900873 if (transportType > -1) {
874 netCap.addTransportType(transportType);
875 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900876 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900877 }
878
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900879 // Used only for testing.
880 // TODO: Delete this and either:
881 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
882 // changing ContentResolver to make registerContentObserver non-final).
883 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
884 // by subclassing SettingsObserver.
885 @VisibleForTesting
886 void updateMobileDataAlwaysOn() {
887 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
888 }
889
Erik Klineda4bfa82015-04-30 12:58:40 +0900890 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900891 final boolean enable = toBool(Settings.Global.getInt(
892 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900893 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
894 if (enable == isEnabled) {
895 return; // Nothing to do.
896 }
897
898 if (enable) {
899 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900900 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900901 } else {
902 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
903 }
904 }
905
906 private void registerSettingsCallbacks() {
907 // Watch for global HTTP proxy changes.
908 mSettingsObserver.observe(
909 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
910 EVENT_APPLY_GLOBAL_HTTP_PROXY);
911
912 // Watch for whether or not to keep mobile data always on.
913 mSettingsObserver.observe(
914 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
915 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
916 }
917
Robert Greenwalt34524f02014-05-18 16:22:10 -0700918 private synchronized int nextNetworkRequestId() {
919 return mNextNetworkRequestId++;
920 }
921
Paul Jensen67b0b072015-06-10 11:22:17 -0400922 @VisibleForTesting
923 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400924 synchronized (mNetworkForNetId) {
925 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
926 int netId = mNextNetId;
927 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
928 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500929 if (!mNetIdInUse.get(netId)) {
930 mNetIdInUse.put(netId, true);
931 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400932 }
933 }
934 }
935 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700936 }
937
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600938 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600940 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
941 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800942 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600943 state = nai.getNetworkState();
944 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800945 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600946 final NetworkInfo info = new NetworkInfo(networkType, 0,
947 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
949 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600950 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
951 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800952 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600953 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600954 return state;
955 } else {
956 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800957 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400958 }
959
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800960 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
961 if (network == null) {
962 return null;
963 }
964 synchronized (mNetworkForNetId) {
965 return mNetworkForNetId.get(network.netId);
966 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600967 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800968
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900969 private Network[] getVpnUnderlyingNetworks(int uid) {
970 if (!mLockdownEnabled) {
971 int user = UserHandle.getUserId(uid);
972 synchronized (mVpns) {
973 Vpn vpn = mVpns.get(user);
974 if (vpn != null && vpn.appliesToUid(uid)) {
975 return vpn.getUnderlyingNetworks();
976 }
977 }
978 }
979 return null;
980 }
981
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800982 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400983 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800984
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900985 final Network[] networks = getVpnUnderlyingNetworks(uid);
986 if (networks != null) {
987 // getUnderlyingNetworks() returns:
988 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
989 // empty array => the VPN explicitly said "no default network".
990 // non-empty array => the VPN specified one or more default networks; we use the
991 // first one.
992 if (networks.length > 0) {
993 nai = getNetworkAgentInfoForNetwork(networks[0]);
994 } else {
995 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800996 }
997 }
998
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800999 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001000 return nai.getNetworkState();
1001 } else {
1002 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001003 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001004 }
1005
1006 /**
1007 * Check if UID should be blocked from using the network with the given LinkProperties.
1008 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001009 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1010 boolean ignoreBlocked) {
1011 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001012 if (ignoreBlocked) {
1013 return false;
1014 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001015 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001016 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1017 if (isSystem(uid)) {
1018 return false;
1019 }
Robin Lee17e61832016-05-09 13:46:28 +01001020 synchronized (mVpns) {
1021 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1022 if (vpn != null && vpn.isBlockingUid(uid)) {
1023 return true;
1024 }
1025 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001026 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001027 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001028 }
1029
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001030 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001031 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1032 return;
1033 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001034 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001035 synchronized (mBlockedAppUids) {
1036 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001037 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001038 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001039 blocked = false;
1040 } else {
1041 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001042 }
1043 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001044 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1045 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1046 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001047 }
1048
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001049 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001050 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1051 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1052 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1053 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001055 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001056 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1057
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001058 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001059 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001061 if (mLockdownTracker != null) {
1062 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001063 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001064
1065 // TODO: apply metered state closer to NetworkAgentInfo
1066 final long token = Binder.clearCallingIdentity();
1067 try {
1068 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1069 } catch (RemoteException e) {
1070 } finally {
1071 Binder.restoreCallingIdentity(token);
1072 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001073 }
1074
1075 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001076 * Return NetworkInfo for the active (i.e., connected) network interface.
1077 * It is assumed that at most one network is active at a time. If more
1078 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001079 * @return the info for the active network, or {@code null} if none is
1080 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001082 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001083 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001084 enforceAccessPermission();
1085 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001086 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001087 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001088 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1089 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001090 }
1091
Paul Jensen31a94f42015-02-13 14:18:39 -05001092 @Override
1093 public Network getActiveNetwork() {
1094 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001095 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001096 }
1097
1098 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001099 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001100 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001101 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001102 }
1103
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001104 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001105 final int user = UserHandle.getUserId(uid);
1106 int vpnNetId = NETID_UNSET;
1107 synchronized (mVpns) {
1108 final Vpn vpn = mVpns.get(user);
1109 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1110 }
1111 NetworkAgentInfo nai;
1112 if (vpnNetId != NETID_UNSET) {
1113 synchronized (mNetworkForNetId) {
1114 nai = mNetworkForNetId.get(vpnNetId);
1115 }
1116 if (nai != null) return nai.network;
1117 }
1118 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001119 if (nai != null
1120 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1121 nai = null;
1122 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001123 return nai != null ? nai.network : null;
1124 }
1125
Lorenzo Colitti18660282016-07-04 12:55:44 +09001126 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001127 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1128 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001129 final int uid = Binder.getCallingUid();
1130 NetworkState state = getUnfilteredActiveNetworkState(uid);
1131 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001132 }
1133
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001134 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001135 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001136 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001137 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001139 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001140 }
1141
1142 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001143 public NetworkInfo getNetworkInfo(int networkType) {
1144 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001145 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001146 if (getVpnUnderlyingNetworks(uid) != null) {
1147 // A VPN is active, so we may need to return one of its underlying networks. This
1148 // information is not available in LegacyTypeTracker, so we have to get it from
1149 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001150 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001151 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001152 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001153 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001154 }
1155 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001156 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001157 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001158 }
1159
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001160 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001161 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001162 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001163 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001164 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001165 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001166 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001167 return state.networkInfo;
1168 } else {
1169 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001170 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001171 }
1172
1173 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 public NetworkInfo[] getAllNetworkInfo() {
1175 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001176 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001177 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1178 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 NetworkInfo info = getNetworkInfo(networkType);
1180 if (info != null) {
1181 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001182 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001183 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001184 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001185 }
1186
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001187 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001188 public Network getNetworkForType(int networkType) {
1189 enforceAccessPermission();
1190 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001191 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1192 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001193 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001194 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001195 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001196 }
1197
1198 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001199 public Network[] getAllNetworks() {
1200 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001201 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001202 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001203 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001204 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001205 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001206 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001207 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001208 }
1209
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001210 @Override
1211 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1212 // The basic principle is: if an app's traffic could possibly go over a
1213 // network, without the app doing anything multinetwork-specific,
1214 // (hence, by "default"), then include that network's capabilities in
1215 // the array.
1216 //
1217 // In the normal case, app traffic only goes over the system's default
1218 // network connection, so that's the only network returned.
1219 //
1220 // With a VPN in force, some app traffic may go into the VPN, and thus
1221 // over whatever underlying networks the VPN specifies, while other app
1222 // traffic may go over the system default network (e.g.: a split-tunnel
1223 // VPN, or an app disallowed by the VPN), so the set of networks
1224 // returned includes the VPN's underlying networks and the system
1225 // default.
1226 enforceAccessPermission();
1227
1228 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1229
1230 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001231 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001232 if (nc != null) {
1233 result.put(nai.network, nc);
1234 }
1235
1236 if (!mLockdownEnabled) {
1237 synchronized (mVpns) {
1238 Vpn vpn = mVpns.get(userId);
1239 if (vpn != null) {
1240 Network[] networks = vpn.getUnderlyingNetworks();
1241 if (networks != null) {
1242 for (Network network : networks) {
1243 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001244 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001245 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001246 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001247 }
1248 }
1249 }
1250 }
1251 }
1252 }
1253
1254 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1255 out = result.values().toArray(out);
1256 return out;
1257 }
1258
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001259 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001260 public boolean isNetworkSupported(int networkType) {
1261 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001262 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001263 }
1264
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001265 /**
1266 * Return LinkProperties for the active (i.e., connected) default
1267 * network interface. It is assumed that at most one default network
1268 * is active at a time. If more than one is active, it is indeterminate
1269 * which will be returned.
1270 * @return the ip properties for the active network, or {@code null} if
1271 * none is active
1272 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001273 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001274 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001275 enforceAccessPermission();
1276 final int uid = Binder.getCallingUid();
1277 NetworkState state = getUnfilteredActiveNetworkState(uid);
1278 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001279 }
1280
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001281 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001282 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001283 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001284 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1285 if (nai != null) {
1286 synchronized (nai) {
1287 return new LinkProperties(nai.linkProperties);
1288 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001289 }
1290 return null;
1291 }
1292
Robert Greenwalt12e67352014-05-13 21:41:06 -07001293 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001294 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001295 public LinkProperties getLinkProperties(Network network) {
1296 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001297 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1298 }
1299
1300 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1301 if (nai == null) {
1302 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001303 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001304 synchronized (nai) {
1305 return new LinkProperties(nai.linkProperties);
1306 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001307 }
1308
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001309 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001310 if (nai != null) {
1311 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001312 if (nai.networkCapabilities != null) {
1313 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001314 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001315 }
1316 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001317 return null;
1318 }
1319
1320 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001321 public NetworkCapabilities getNetworkCapabilities(Network network) {
1322 enforceAccessPermission();
1323 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1324 }
1325
1326 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001327 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001328 // Require internal since we're handing out IMSI details
1329 enforceConnectivityInternalPermission();
1330
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001331 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001332 for (Network network : getAllNetworks()) {
1333 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1334 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001335 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001336 }
1337 }
1338 return result.toArray(new NetworkState[result.size()]);
1339 }
1340
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001341 @Override
1342 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1343 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001344 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001345 final long token = Binder.clearCallingIdentity();
1346 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001347 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1348 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001349 try {
1350 return mPolicyManager.getNetworkQuotaInfo(state);
1351 } catch (RemoteException e) {
1352 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001353 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001354 return null;
1355 } finally {
1356 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001357 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001358 }
1359
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001360 @Override
1361 public boolean isActiveNetworkMetered() {
1362 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001363
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001364 final NetworkInfo info = getActiveNetworkInfo();
1365 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001366 }
1367
Jeff Sharkey216c1812012-08-05 14:29:23 -07001368 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1369 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001370 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001371 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001372 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001373 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001374 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001375
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001376 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001377 * Ensure that a network route exists to deliver traffic to the specified
1378 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001379 * @param networkType the type of the network over which traffic to the
1380 * specified host is to be routed
1381 * @param hostAddress the IP address of the host to which the route is
1382 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001383 * @return {@code true} on success, {@code false} on failure
1384 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001385 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001386 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001388 if (mProtectedNetworks.contains(networkType)) {
1389 enforceConnectivityInternalPermission();
1390 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001391
Chad Brubakerc0234532014-02-14 13:24:29 -08001392 InetAddress addr;
1393 try {
1394 addr = InetAddress.getByAddress(hostAddress);
1395 } catch (UnknownHostException e) {
1396 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1397 return false;
1398 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001399
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001401 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001402 return false;
1403 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001404
1405 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1406 if (nai == null) {
1407 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1408 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1409 } else {
1410 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1411 }
1412 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001413 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001414
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001415 DetailedState netState;
1416 synchronized (nai) {
1417 netState = nai.networkInfo.getDetailedState();
1418 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001419
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001420 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001421 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001422 log("requestRouteToHostAddress on down network "
1423 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001424 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001425 }
1426 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001428
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001429 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001430 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001431 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001432 LinkProperties lp;
1433 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001434 synchronized (nai) {
1435 lp = nai.linkProperties;
1436 netId = nai.network.netId;
1437 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001438 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001439 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1440 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001441 } finally {
1442 Binder.restoreCallingIdentity(token);
1443 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001444 }
1445
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001446 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001447 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001448 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001449 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001450 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001451 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001452 if (bestRoute.getGateway().equals(addr)) {
1453 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001454 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001455 } else {
1456 // if we will connect to this through another route, add a direct route
1457 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001458 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001459 }
1460 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001461 if (DBG) log("Adding legacy route " + bestRoute +
1462 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001463 try {
1464 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1465 } catch (Exception e) {
1466 // never crash - catch them all
1467 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001468 return false;
1469 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001470 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001471 }
1472
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001473 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001474 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001475 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001476 // TODO: notify UID when it has requested targeted updates
1477 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001478 @Override
1479 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001480 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001481 @Override
1482 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001483 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001484 if (restrictBackground) {
1485 log("onRestrictBackgroundChanged(true): disabling tethering");
1486 mTethering.untetherAll();
1487 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001488 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001489 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001490 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001491 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001492 };
1493
Robin Lee3b3dd942015-05-12 18:14:58 +01001494 /**
1495 * Require that the caller is either in the same user or has appropriate permission to interact
1496 * across users.
1497 *
1498 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1499 */
1500 private void enforceCrossUserPermission(int userId) {
1501 if (userId == UserHandle.getCallingUserId()) {
1502 // Not a cross-user call.
1503 return;
1504 }
1505 mContext.enforceCallingOrSelfPermission(
1506 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1507 "ConnectivityService");
1508 }
1509
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001510 private void enforceInternetPermission() {
1511 mContext.enforceCallingOrSelfPermission(
1512 android.Manifest.permission.INTERNET,
1513 "ConnectivityService");
1514 }
1515
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001517 mContext.enforceCallingOrSelfPermission(
1518 android.Manifest.permission.ACCESS_NETWORK_STATE,
1519 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001520 }
1521
1522 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001523 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001524 }
1525
Charles Hea0a87e82017-05-15 17:07:18 +01001526 private void enforceSettingsPermission() {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.NETWORK_SETTINGS,
1529 "ConnectivityService");
1530 }
1531
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001532 private void enforceTetherAccessPermission() {
1533 mContext.enforceCallingOrSelfPermission(
1534 android.Manifest.permission.ACCESS_NETWORK_STATE,
1535 "ConnectivityService");
1536 }
1537
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001538 private void enforceConnectivityInternalPermission() {
1539 mContext.enforceCallingOrSelfPermission(
1540 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1541 "ConnectivityService");
1542 }
1543
Hugo Benichi514da602016-07-19 15:59:27 +09001544 private void enforceConnectivityRestrictedNetworksPermission() {
1545 try {
1546 mContext.enforceCallingOrSelfPermission(
1547 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1548 "ConnectivityService");
1549 return;
1550 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1551 enforceConnectivityInternalPermission();
1552 }
1553
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001554 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001555 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001556 }
1557
Lorenzo Colitti18660282016-07-04 12:55:44 +09001558 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001559 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001560 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001561 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001562 }
1563
1564 private void sendInetConditionBroadcast(NetworkInfo info) {
1565 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1566 }
1567
Wink Saville628b0852011-08-04 15:01:58 -07001568 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001569 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001570 info = new NetworkInfo(info);
1571 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001572 }
1573
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001574 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001575 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001576 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001577 if (info.isFailover()) {
1578 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1579 info.setFailover(false);
1580 }
1581 if (info.getReason() != null) {
1582 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1583 }
1584 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001585 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1586 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001587 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001588 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001589 return intent;
1590 }
1591
1592 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1593 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1594 }
1595
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001596 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001597 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1598 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1599 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001600 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001601 final long ident = Binder.clearCallingIdentity();
1602 try {
1603 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1604 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1605 } finally {
1606 Binder.restoreCallingIdentity(ident);
1607 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001608 }
1609
Mike Lockwood0f79b542009-08-14 14:18:49 -04001610 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001611 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001612 if (!mSystemReady) {
1613 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001614 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001615 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001616 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001617 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001618 }
1619
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001620 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001621 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001622 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001623 final NetworkInfo ni = intent.getParcelableExtra(
1624 ConnectivityManager.EXTRA_NETWORK_INFO);
1625 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1626 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1627 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001628 } else {
1629 BroadcastOptions opts = BroadcastOptions.makeBasic();
1630 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1631 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001632 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001633 final IBatteryStats bs = BatteryStatsService.getService();
1634 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001635 bs.noteConnectivityChanged(intent.getIntExtra(
1636 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1637 ni != null ? ni.getState().toString() : "?");
1638 } catch (RemoteException e) {
1639 }
1640 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001641 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001642 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001643 } finally {
1644 Binder.restoreCallingIdentity(ident);
1645 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001646 }
1647 }
1648
1649 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001650 loadGlobalProxy();
1651
Hugo Benichi20035e02017-04-26 14:53:28 +09001652 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001653 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001654 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001655 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001656 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001657 }
1658 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001659 // load the global proxy at startup
1660 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001661
Robin Lee244ce8e2016-01-05 18:03:46 +00001662 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1663 // for user to unlock device too.
1664 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001665
Erik Klineda4bfa82015-04-30 12:58:40 +09001666 // Configure whether mobile data is always on.
1667 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1668
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001669 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001670
1671 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
1673
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001675 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001676 *
1677 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001678 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001679 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001680 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1681 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001682
1683 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001684 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001685
Robert Greenwalt7b816022014-04-18 15:25:25 -07001686 if (networkAgent.networkCapabilities.hasTransport(
1687 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001688 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1689 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001690 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001691 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001692 } else if (networkAgent.networkCapabilities.hasTransport(
1693 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001694 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1695 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001696 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001697 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001698 } else {
1699 // do not track any other networks
1700 timeout = 0;
1701 }
1702
Robert Greenwalt7b816022014-04-18 15:25:25 -07001703 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001704 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001705 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001706 } catch (Exception e) {
1707 // You shall not crash!
1708 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001709 }
1710 }
1711 }
1712
1713 /**
1714 * Remove data activity tracking when network disconnects.
1715 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001716 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1717 final String iface = networkAgent.linkProperties.getInterfaceName();
1718 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001719
Robert Greenwalt7b816022014-04-18 15:25:25 -07001720 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1721 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001722 try {
1723 // the call fails silently if no idletimer setup for this interface
1724 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001725 } catch (Exception e) {
1726 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001727 }
1728 }
1729 }
1730
1731 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001732 * Reads the network specific MTU size from reources.
1733 * and set it on it's iface.
1734 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001735 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1736 final String iface = newLp.getInterfaceName();
1737 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001738 if (oldLp == null && mtu == 0) {
1739 // Silently ignore unset MTU value.
1740 return;
1741 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001742 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1743 if (VDBG) log("identical MTU - not setting");
1744 return;
1745 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001746 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001747 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001748 return;
1749 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001750
w1997615afd812014-08-05 15:18:11 -07001751 // Cannot set MTU without interface name
1752 if (TextUtils.isEmpty(iface)) {
1753 loge("Setting MTU size with null iface.");
1754 return;
1755 }
1756
Robert Greenwalt7b816022014-04-18 15:25:25 -07001757 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001758 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001759 mNetd.setMtu(iface, mtu);
1760 } catch (Exception e) {
1761 Slog.e(TAG, "exception in setMtu()" + e);
1762 }
1763 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001764
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001765 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001766 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1767
1768 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001769 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001770 protected MockableSystemProperties getSystemProperties() {
1771 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001772 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001773
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001774 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1775 if (isDefaultNetwork(nai) == false) {
1776 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001777 }
1778
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001779 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1780 String[] values = null;
1781 if (tcpBufferSizes != null) {
1782 values = tcpBufferSizes.split(",");
1783 }
1784
1785 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001786 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001787 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1788 values = tcpBufferSizes.split(",");
1789 }
1790
1791 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1792
1793 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001794 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001795
1796 final String prefix = "/sys/kernel/ipv4/tcp_";
1797 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1798 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1799 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1800 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1801 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1802 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1803 mCurrentTcpBufferSizes = tcpBufferSizes;
1804 } catch (IOException e) {
1805 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001806 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001807
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001808 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001809 Settings.Global.TCP_DEFAULT_INIT_RWND,
1810 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001811 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1812 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001813 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001814 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001815 }
1816
Mattias Falk8b47b362011-08-23 14:15:13 +02001817 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001818 /*
1819 * Tell the VMs to toss their DNS caches
1820 */
1821 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1822 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001823 /*
1824 * Connectivity events can happen before boot has completed ...
1825 */
1826 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001827 final long ident = Binder.clearCallingIdentity();
1828 try {
1829 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1830 } finally {
1831 Binder.restoreCallingIdentity(ident);
1832 }
Robert Greenwalt42acef32009-08-12 16:08:25 -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 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002066 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002067 try {
2068 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002069 } catch (Exception e) {
2070 // Never crash!
2071 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002072 }
2073 break;
2074 }
2075 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002076 try {
2077 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002078 } catch (Exception e) {
2079 // Never crash!
2080 loge("Exception in removeVpnUidRanges: " + e);
2081 }
2082 break;
2083 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002084 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002085 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2086 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002087 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002088 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002089 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002090 break;
2091 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002092 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002093 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2094 break;
2095 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002096 }
2097 }
2098
2099 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2100 switch (msg.what) {
2101 default:
2102 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002103 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002104 final NetworkAgentInfo nai;
2105 synchronized (mNetworkForNetId) {
2106 nai = mNetworkForNetId.get(msg.arg2);
2107 }
2108 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002109 final boolean valid =
2110 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002111 final boolean wasValidated = nai.lastValidated;
Hugo Benichi380a0632017-10-20 09:25:29 +09002112 final boolean wasDefault = isDefaultNetwork(nai);
Paul Jensen232437312016-04-06 09:51:26 -04002113 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2114 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002115 if (valid != nai.lastValidated) {
Hugo Benichi380a0632017-10-20 09:25:29 +09002116 if (wasDefault) {
2117 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2118 SystemClock.elapsedRealtime(), valid);
2119 }
Paul Jensen1c7ba022015-06-16 14:27:36 -04002120 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002121 nai.lastValidated = valid;
2122 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002123 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002124 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2125 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002126 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002127 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002128 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002129 Bundle redirectUrlBundle = new Bundle();
2130 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002131 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002132 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002133 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002134 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002135 if (wasValidated && !nai.lastValidated) {
2136 handleNetworkUnvalidated(nai);
2137 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002138 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 break;
2140 }
Paul Jensen869868be2014-05-15 10:33:05 -04002141 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002142 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002143 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002144 final NetworkAgentInfo nai;
2145 synchronized (mNetworkForNetId) {
2146 nai = mNetworkForNetId.get(netId);
2147 }
Calvin Onbe96da12016-10-11 15:10:46 -07002148 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002149 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002150 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002151 nai.lastCaptivePortalDetected = visible;
2152 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002153 if (nai.lastCaptivePortalDetected &&
2154 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2155 if (DBG) log("Avoiding captive portal network: " + nai.name());
2156 nai.asyncChannel.sendMessage(
2157 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2158 teardownUnneededNetwork(nai);
2159 break;
2160 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002161 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002162 }
2163 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002164 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002165 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002166 if (nai == null) {
2167 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2168 break;
2169 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002170 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002171 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002172 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002173 }
Paul Jensen869868be2014-05-15 10:33:05 -04002174 }
Paul Jensen869868be2014-05-15 10:33:05 -04002175 break;
2176 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002177 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002178 return true;
2179 }
2180
Calvin Onbe96da12016-10-11 15:10:46 -07002181 private int getCaptivePortalMode() {
2182 return Settings.Global.getInt(mContext.getContentResolver(),
2183 Settings.Global.CAPTIVE_PORTAL_MODE,
2184 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2185 }
2186
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002187 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2188 switch (msg.what) {
2189 default:
2190 return false;
2191 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2192 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2193 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2194 handleLingerComplete(nai);
2195 }
2196 break;
2197 }
2198 }
2199 return true;
2200 }
2201
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002202 @Override
2203 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002204 if (!maybeHandleAsyncChannelMessage(msg) &&
2205 !maybeHandleNetworkMonitorMessage(msg) &&
2206 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002207 maybeHandleNetworkAgentMessage(msg);
2208 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002209 }
2210 }
2211
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002212 private void updateLingerState(NetworkAgentInfo nai, long now) {
2213 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2214 // 2. If the network was lingering and there are now requests, unlinger it.
2215 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2216 // one lingered request, start lingering.
2217 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002218 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002219 if (DBG) log("Unlingering " + nai.name());
2220 nai.unlinger();
2221 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002222 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002223 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002224 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002225 nai.linger();
2226 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2227 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2228 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002229 }
2230
Robert Greenwalt7b816022014-04-18 15:25:25 -07002231 private void handleAsyncChannelHalfConnect(Message msg) {
2232 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002233 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002234 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2235 if (VDBG) log("NetworkFactory connected");
2236 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002237 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002238 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002239 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002240 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002241 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002242 }
2243 } else {
2244 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002245 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002246 }
2247 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2248 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2249 if (VDBG) log("NetworkAgent connected");
2250 // A network agent has requested a connection. Establish the connection.
2251 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2252 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2253 } else {
2254 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002255 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002256 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002257 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002258 synchronized (mNetworkForNetId) {
2259 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002260 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002261 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002262 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002263 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002264 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002265 }
2266 }
2267 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002268
Robert Greenwalt7b816022014-04-18 15:25:25 -07002269 private void handleAsyncChannelDisconnected(Message msg) {
2270 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2271 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002272 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002273 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002274 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002275 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002276 // TODO - if we move the logic to the network agent (have them disconnect
2277 // because they lost all their requests or because their score isn't good)
2278 // then they would disconnect organically, report their new state and then
2279 // disconnect the channel.
2280 if (nai.networkInfo.isConnected()) {
2281 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2282 null, null);
2283 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002284 final boolean wasDefault = isDefaultNetwork(nai);
2285 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002286 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002287 // Log default network disconnection before required book-keeping.
2288 // Let rematchAllNetworksAndRequests() below record a new default network event
2289 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2290 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002291 long now = SystemClock.elapsedRealtime();
2292 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002293 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002294 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002295 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2296 // by other networks that are already connected. Perhaps that can be done by
2297 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2298 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002299 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002300 mKeepaliveTracker.handleStopAllKeepalives(nai,
2301 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002302 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2303 // Disable wakeup packet monitoring for each interface.
2304 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2305 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002306 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002307 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002308 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002309 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002310 // Remove the NetworkAgent, but don't mark the netId as
2311 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002312 mNetworkForNetId.remove(nai.network.netId);
2313 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002314 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002315 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2316 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002317 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002318 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002319 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002320 sendUpdatedScoreToFactories(request, 0);
2321 }
2322 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002323 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002324 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002325 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002326 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002327 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002328 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002329 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002330 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002331 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002332 if (nai.created) {
2333 // Tell netd to clean up the configuration for this network
2334 // (routing rules, DNS, etc).
2335 // This may be slow as it requires a lot of netd shelling out to ip and
2336 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2337 // after we've rematched networks with requests which should make a potential
2338 // fallback network the default or requested a new network from the
2339 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2340 // long time.
2341 try {
2342 mNetd.removeNetwork(nai.network.netId);
2343 } catch (Exception e) {
2344 loge("Exception removing network: " + e);
2345 }
2346 }
2347 synchronized (mNetworkForNetId) {
2348 mNetIdInUse.delete(nai.network.netId);
2349 }
2350 } else {
2351 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2352 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 }
2354 }
2355
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002356 // If this method proves to be too slow then we can maintain a separate
2357 // pendingIntent => NetworkRequestInfo map.
2358 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2359 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2360 Intent intent = pendingIntent.getIntent();
2361 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2362 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2363 if (existingPendingIntent != null &&
2364 existingPendingIntent.getIntent().filterEquals(intent)) {
2365 return entry.getValue();
2366 }
2367 }
2368 return null;
2369 }
2370
2371 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2372 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2373
2374 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2375 if (existingRequest != null) { // remove the existing request.
2376 if (DBG) log("Replacing " + existingRequest.request + " with "
2377 + nri.request + " because their intents matched.");
2378 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2379 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002380 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002381 }
2382
Erik Klineda4bfa82015-04-30 12:58:40 +09002383 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002384 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002385 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002386 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002387 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002388 if (nri.request.networkCapabilities.hasSignalStrength() &&
2389 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2390 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002391 }
2392 }
2393 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002394 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002395 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002396 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002397 }
2398 }
2399
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002400 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2401 int callingUid) {
2402 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2403 if (nri != null) {
2404 handleReleaseNetworkRequest(nri.request, callingUid);
2405 }
2406 }
2407
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002408 // Determines whether the network is the best (or could become the best, if it validated), for
2409 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2410 // on the value of reason:
2411 //
2412 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2413 // then it should be torn down.
2414 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2415 // then it should be lingered.
2416 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2417 final int numRequests;
2418 switch (reason) {
2419 case TEARDOWN:
2420 numRequests = nai.numRequestNetworkRequests();
2421 break;
2422 case LINGER:
2423 numRequests = nai.numForegroundNetworkRequests();
2424 break;
2425 default:
2426 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2427 return true;
2428 }
2429
2430 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002431 return false;
2432 }
Paul Jensene0988542015-06-25 15:30:08 -04002433 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002434 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2435 // Background requests don't affect lingering.
2436 continue;
2437 }
2438
Paul Jensene0988542015-06-25 15:30:08 -04002439 // If this Network is already the highest scoring Network for a request, or if
2440 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002441 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002442 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002443 // Note that this catches two important cases:
2444 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2445 // is currently satisfying the request. This is desirable when
2446 // cellular ends up validating but WiFi does not.
2447 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002448 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002449 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002450 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002451 nai.getCurrentScoreAsValidated())) {
2452 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002453 }
2454 }
Paul Jensene0988542015-06-25 15:30:08 -04002455 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002456 }
2457
Erik Klineacdd6392016-07-07 16:50:58 +09002458 private NetworkRequestInfo getNriForAppRequest(
2459 NetworkRequest request, int callingUid, String requestedOperation) {
2460 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2461
Robert Greenwalt9258c642014-03-26 16:47:06 -07002462 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002463 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002464 log(String.format("UID %d attempted to %s for unowned request %s",
2465 callingUid, requestedOperation, nri));
2466 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002467 }
Erik Klineacdd6392016-07-07 16:50:58 +09002468 }
2469
2470 return nri;
2471 }
2472
Erik Kline57faba92015-11-25 12:49:38 +09002473 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002474 if (mNetworkRequests.get(nri.request) == null) {
2475 return;
Erik Kline57faba92015-11-25 12:49:38 +09002476 }
Hugo Benichicd952782017-09-20 11:20:14 +09002477 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002478 return;
2479 }
2480 if (VDBG || (DBG && nri.request.isRequest())) {
2481 log("releasing " + nri.request + " (timeout)");
2482 }
2483 handleRemoveNetworkRequest(nri);
2484 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002485 }
2486
Erik Klineacdd6392016-07-07 16:50:58 +09002487 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002488 final NetworkRequestInfo nri =
2489 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2490 if (nri == null) {
2491 return;
Erik Kline57faba92015-11-25 12:49:38 +09002492 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002493 if (VDBG || (DBG && nri.request.isRequest())) {
2494 log("releasing " + nri.request + " (release request)");
2495 }
2496 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002497 }
Erik Klineacdd6392016-07-07 16:50:58 +09002498
Hugo Benichidba33db2017-03-23 22:40:44 +09002499 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002500 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002501 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002502 synchronized (mUidToNetworkRequestCount) {
2503 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2504 if (requests < 1) {
2505 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2506 nri.mUid);
2507 } else if (requests == 1) {
2508 mUidToNetworkRequestCount.removeAt(
2509 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2510 } else {
2511 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2512 }
2513 }
2514 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2515 if (nri.request.isRequest()) {
2516 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002517 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002518 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002519 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002520 nai.removeRequest(nri.request.requestId);
2521 if (VDBG) {
2522 log(" Removing from current network " + nai.name() +
2523 ", leaving " + nai.numNetworkRequests() + " requests.");
2524 }
2525 // If there are still lingered requests on this network, don't tear it down,
2526 // but resume lingering instead.
2527 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002528 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002529 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2530 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002531 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002532 wasKept = true;
2533 }
Hugo Benichicd952782017-09-20 11:20:14 +09002534 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002535 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2536 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002537 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002538 }
Erik Klineacdd6392016-07-07 16:50:58 +09002539 }
2540
2541 // TODO: remove this code once we know that the Slog.wtf is never hit.
2542 //
2543 // Find all networks that are satisfying this request and remove the request
2544 // from their request lists.
2545 // TODO - it's my understanding that for a request there is only a single
2546 // network satisfying it, so this loop is wasteful
2547 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2548 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2549 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2550 otherNai.name() + ", but mNetworkAgentInfos says " +
2551 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002552 }
2553 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002554
Erik Klineacdd6392016-07-07 16:50:58 +09002555 // Maintain the illusion. When this request arrived, we might have pretended
2556 // that a network connected to serve it, even though the network was already
2557 // connected. Now that this request has gone away, we might have to pretend
2558 // that the network disconnected. LegacyTypeTracker will generate that
2559 // phantom disconnect for this type.
2560 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2561 boolean doRemove = true;
2562 if (wasKept) {
2563 // check if any of the remaining requests for this network are for the
2564 // same legacy type - if so, don't remove the nai
2565 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2566 NetworkRequest otherRequest = nai.requestAt(i);
2567 if (otherRequest.legacyType == nri.request.legacyType &&
2568 otherRequest.isRequest()) {
2569 if (DBG) log(" still have other legacy request - leaving");
2570 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002571 }
2572 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002573 }
2574
Erik Klineacdd6392016-07-07 16:50:58 +09002575 if (doRemove) {
2576 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002577 }
2578 }
Erik Klineacdd6392016-07-07 16:50:58 +09002579
2580 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2581 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2582 nri.request);
2583 }
2584 } else {
2585 // listens don't have a singular affectedNetwork. Check all networks to see
2586 // if this listen request applies and remove it.
2587 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2588 nai.removeRequest(nri.request.requestId);
2589 if (nri.request.networkCapabilities.hasSignalStrength() &&
2590 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2591 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2592 }
2593 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002594 }
2595 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002596
Lorenzo Colitti18660282016-07-04 12:55:44 +09002597 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002598 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2599 enforceConnectivityInternalPermission();
2600 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002601 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002602 }
2603
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002604 @Override
2605 public void setAvoidUnvalidated(Network network) {
2606 enforceConnectivityInternalPermission();
2607 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2608 }
2609
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002610 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2611 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2612 " accept=" + accept + " always=" + always);
2613
2614 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2615 if (nai == null) {
2616 // Nothing to do.
2617 return;
2618 }
2619
2620 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002621 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002622 return;
2623 }
2624
2625 if (!nai.networkMisc.explicitlySelected) {
2626 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2627 }
2628
2629 if (accept != nai.networkMisc.acceptUnvalidated) {
2630 int oldScore = nai.getCurrentScore();
2631 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002632 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002633 sendUpdatedScoreToFactories(nai);
2634 }
2635
2636 if (always) {
2637 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002638 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002639 }
2640
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002641 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002642 // Tell the NetworkAgent to not automatically reconnect to the network.
2643 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2644 // Teardown the nework.
2645 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002646 }
2647
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002648 }
2649
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002650 private void handleSetAvoidUnvalidated(Network network) {
2651 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2652 if (nai == null || nai.lastValidated) {
2653 // Nothing to do. The network either disconnected or revalidated.
2654 return;
2655 }
2656 if (!nai.avoidUnvalidated) {
2657 int oldScore = nai.getCurrentScore();
2658 nai.avoidUnvalidated = true;
2659 rematchAllNetworksAndRequests(nai, oldScore);
2660 sendUpdatedScoreToFactories(nai);
2661 }
2662 }
2663
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002664 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002665 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002666 mHandler.sendMessageDelayed(
2667 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2668 PROMPT_UNVALIDATED_DELAY_MS);
2669 }
2670
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002671 @Override
2672 public void startCaptivePortalApp(Network network) {
2673 enforceConnectivityInternalPermission();
2674 mHandler.post(() -> {
2675 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2676 if (nai == null) return;
2677 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2678 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2679 });
2680 }
2681
Hugo Benichic8e9e122016-09-14 23:23:08 +00002682 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002683 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002684 }
2685
Erik Kline065ab6e2016-10-02 18:02:14 +09002686 private void rematchForAvoidBadWifiUpdate() {
2687 rematchAllNetworksAndRequests(null, 0);
2688 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2689 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2690 sendUpdatedScoreToFactories(nai);
2691 }
2692 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002693 }
2694
Erik Kline065ab6e2016-10-02 18:02:14 +09002695 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002696 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002697 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002698 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002699 if (!configRestrict) {
2700 pw.println("Bad Wi-Fi avoidance: unrestricted");
2701 return;
2702 }
2703
2704 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2705 pw.increaseIndent();
2706 pw.println("Config restrict: " + configRestrict);
2707
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002708 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002709 String description;
2710 // Can't use a switch statement because strings are legal case labels, but null is not.
2711 if ("0".equals(value)) {
2712 description = "get stuck";
2713 } else if (value == null) {
2714 description = "prompt";
2715 } else if ("1".equals(value)) {
2716 description = "avoid";
2717 } else {
2718 description = value + " (?)";
2719 }
2720 pw.println("User setting: " + description);
2721 pw.println("Network overrides:");
2722 pw.increaseIndent();
2723 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2724 if (nai.avoidUnvalidated) {
2725 pw.println(nai.name());
2726 }
2727 }
2728 pw.decreaseIndent();
2729 pw.decreaseIndent();
2730 }
2731
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002732 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2733 final String action;
2734 switch (type) {
2735 case NO_INTERNET:
2736 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2737 break;
2738 case LOST_INTERNET:
2739 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2740 break;
2741 default:
2742 Slog.wtf(TAG, "Unknown notification type " + type);
2743 return;
2744 }
2745
2746 Intent intent = new Intent(action);
2747 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2748 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2749 intent.setClassName("com.android.settings",
2750 "com.android.settings.wifi.WifiNoInternetDialog");
2751
2752 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2753 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2754 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2755 }
2756
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002757 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002758 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002759 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2760
2761 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2762 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002763 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002764 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002765 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2766 return;
2767 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002768 showValidationNotification(nai, NotificationType.NO_INTERNET);
2769 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002770
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002771 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2772 NetworkCapabilities nc = nai.networkCapabilities;
2773 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002774
Erik Kline065ab6e2016-10-02 18:02:14 +09002775 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002776 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002777 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2778 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002779 }
2780
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002781 @Override
2782 public int getMultipathPreference(Network network) {
2783 enforceAccessPermission();
2784
2785 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2786 if (nai != null && !nai.networkInfo.isMetered()) {
2787 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2788 }
2789
2790 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2791 }
2792
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002793 private class InternalHandler extends Handler {
2794 public InternalHandler(Looper looper) {
2795 super(looper);
2796 }
2797
2798 @Override
2799 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002800 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002801 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002802 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002803 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002804 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002805 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002806 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002807 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002808 break;
2809 }
Jason Monkdecd2952013-10-10 14:02:51 -04002810 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002811 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002812 break;
2813 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002814 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002815 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2816 break;
2817 }
2818 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2819 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002820 break;
2821 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002822 case EVENT_REGISTER_NETWORK_AGENT: {
2823 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2824 break;
2825 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002826 case EVENT_REGISTER_NETWORK_REQUEST:
2827 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002828 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002829 break;
2830 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002831 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2832 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002833 handleRegisterNetworkRequestWithIntent(msg);
2834 break;
2835 }
Erik Kline57faba92015-11-25 12:49:38 +09002836 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2837 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2838 handleTimedOutNetworkRequest(nri);
2839 break;
2840 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002841 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2842 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2843 break;
2844 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002845 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002846 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002847 break;
2848 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002849 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002850 Network network = (Network) msg.obj;
2851 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002852 break;
2853 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002854 case EVENT_SET_AVOID_UNVALIDATED: {
2855 handleSetAvoidUnvalidated((Network) msg.obj);
2856 break;
2857 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002858 case EVENT_PROMPT_UNVALIDATED: {
2859 handlePromptUnvalidated((Network) msg.obj);
2860 break;
2861 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002862 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2863 handleMobileDataAlwaysOn();
2864 break;
2865 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002866 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2867 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2868 mKeepaliveTracker.handleStartKeepalive(msg);
2869 break;
2870 }
2871 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2872 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2873 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2874 int slot = msg.arg1;
2875 int reason = msg.arg2;
2876 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2877 break;
2878 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002879 case EVENT_SYSTEM_READY: {
2880 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2881 nai.networkMonitor.systemReady = true;
2882 }
2883 break;
2884 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002885 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002886 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002887 break;
2888 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002889 }
2890 }
2891 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002892
2893 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002894 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002895 public int tether(String iface, String callerPkg) {
2896 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002897 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002898 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002899 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002900 } else {
2901 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2902 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002903 }
2904
2905 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002906 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002907 public int untether(String iface, String callerPkg) {
2908 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002909
2910 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002911 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002912 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002913 } else {
2914 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2915 }
2916 }
2917
2918 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002919 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002920 public int getLastTetherError(String iface) {
2921 enforceTetherAccessPermission();
2922
2923 if (isTetheringSupported()) {
2924 return mTethering.getLastTetherError(iface);
2925 } else {
2926 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2927 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002928 }
2929
2930 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002931 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002932 public String[] getTetherableUsbRegexs() {
2933 enforceTetherAccessPermission();
2934 if (isTetheringSupported()) {
2935 return mTethering.getTetherableUsbRegexs();
2936 } else {
2937 return new String[0];
2938 }
2939 }
2940
Lorenzo Colitti18660282016-07-04 12:55:44 +09002941 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002942 public String[] getTetherableWifiRegexs() {
2943 enforceTetherAccessPermission();
2944 if (isTetheringSupported()) {
2945 return mTethering.getTetherableWifiRegexs();
2946 } else {
2947 return new String[0];
2948 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002949 }
2950
Lorenzo Colitti18660282016-07-04 12:55:44 +09002951 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002952 public String[] getTetherableBluetoothRegexs() {
2953 enforceTetherAccessPermission();
2954 if (isTetheringSupported()) {
2955 return mTethering.getTetherableBluetoothRegexs();
2956 } else {
2957 return new String[0];
2958 }
2959 }
2960
Lorenzo Colitti18660282016-07-04 12:55:44 +09002961 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002962 public int setUsbTethering(boolean enable, String callerPkg) {
2963 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002964 if (isTetheringSupported()) {
2965 return mTethering.setUsbTethering(enable);
2966 } else {
2967 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2968 }
2969 }
2970
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002971 // TODO - move iface listing, queries, etc to new module
2972 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002973 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002974 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002975 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002976 return mTethering.getTetherableIfaces();
2977 }
2978
Lorenzo Colitti18660282016-07-04 12:55:44 +09002979 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002980 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002981 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002982 return mTethering.getTetheredIfaces();
2983 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002984
Lorenzo Colitti18660282016-07-04 12:55:44 +09002985 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002986 public String[] getTetheringErroredIfaces() {
2987 enforceTetherAccessPermission();
2988 return mTethering.getErroredIfaces();
2989 }
2990
Lorenzo Colitti18660282016-07-04 12:55:44 +09002991 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002992 public String[] getTetheredDhcpRanges() {
2993 enforceConnectivityInternalPermission();
2994 return mTethering.getTetheredDhcpRanges();
2995 }
2996
Udam Sainic3b640c2017-06-07 12:06:28 -07002997 @Override
2998 public boolean isTetheringSupported(String callerPkg) {
2999 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3000 return isTetheringSupported();
3001 }
3002
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003003 // if ro.tether.denied = true we default to no tethering
3004 // gservices could set the secure setting to 1 though to enable it on a build where it
3005 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003006 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003007 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3008 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3009 Settings.Global.TETHER_SUPPORTED, defaultVal));
3010 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003011 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003012
3013 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3014 boolean adminUser = false;
3015 final long token = Binder.clearCallingIdentity();
3016 try {
3017 adminUser = mUserManager.isAdminUser();
3018 } finally {
3019 Binder.restoreCallingIdentity(token);
3020 }
3021
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003022 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003023 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003024
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003025 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003026 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3027 String callerPkg) {
3028 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003029 if (!isTetheringSupported()) {
3030 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3031 return;
3032 }
3033 mTethering.startTethering(type, receiver, showProvisioningUi);
3034 }
3035
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003036 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003037 public void stopTethering(int type, String callerPkg) {
3038 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003039 mTethering.stopTethering(type);
3040 }
3041
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003042 // Called when we lose the default network and have no replacement yet.
3043 // This will automatically be cleared after X seconds or a new default network
3044 // becomes CONNECTED, whichever happens first. The timer is started by the
3045 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003046 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003047 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003048 if (mNetTransitionWakeLock.isHeld()) {
3049 return;
3050 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003051 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003052 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3053 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003054 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003055 mWakelockLogs.log("ACQUIRE for " + forWhom);
3056 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3057 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003058 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003059
Hugo Benichi4c31b342017-03-30 23:18:10 +09003060 // Called when we gain a new default network to release the network transition wakelock in a
3061 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3062 // message is cancelled.
3063 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003064 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003065 if (!mNetTransitionWakeLock.isHeld()) {
3066 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003067 }
3068 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003069 // Cancel self timeout on wakelock hold.
3070 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3071 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3072 mHandler.sendMessageDelayed(msg, 1000);
3073 }
3074
3075 // Called when either message of ensureNetworkTransitionWakelock or
3076 // scheduleReleaseNetworkTransitionWakelock is processed.
3077 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3078 String event = eventName(eventId);
3079 synchronized (this) {
3080 if (!mNetTransitionWakeLock.isHeld()) {
3081 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3082 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3083 return;
3084 }
3085 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003086 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3087 mTotalWakelockDurationMs += lockDuration;
3088 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3089 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003090 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003091 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003092 }
3093
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003094 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003095 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003096 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003097 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003098 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003099 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003100 }
3101
Lorenzo Colitti18660282016-07-04 12:55:44 +09003102 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003103 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003104 enforceAccessPermission();
3105 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003106 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003107 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003108 mHandler.sendMessage(
3109 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3110 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003111
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003112 private void handleReportNetworkConnectivity(
3113 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003114 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003115 if (network == null) {
3116 nai = getDefaultNetwork();
3117 } else {
3118 nai = getNetworkAgentInfoForNetwork(network);
3119 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003120 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3121 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3122 return;
3123 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003124 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003125 if (hasConnectivity == nai.lastValidated) {
3126 return;
3127 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003128 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003129 int netid = nai.network.netId;
3130 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003131 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003132 // Validating a network that has not yet connected could result in a call to
3133 // rematchNetworkAndRequests() which is not meant to work on such networks.
3134 if (!nai.everConnected) {
3135 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003136 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003137 LinkProperties lp = getLinkProperties(nai);
3138 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3139 return;
3140 }
3141 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003142 }
3143
Paul Jensencee9b512015-05-06 07:32:40 -04003144 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003145 // this information is already available as a world read/writable jvm property
3146 // so this API change wouldn't have a benifit. It also breaks the passing
3147 // of proxy info to all the JVMs.
3148 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003149 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003150 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003151 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3152 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003153 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003154 }
3155
Lorenzo Colitti18660282016-07-04 12:55:44 +09003156 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003157 public ProxyInfo getProxyForNetwork(Network network) {
3158 if (network == null) return getDefaultProxy();
3159 final ProxyInfo globalProxy = getGlobalProxy();
3160 if (globalProxy != null) return globalProxy;
3161 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3162 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3163 // caller may not have.
3164 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3165 if (nai == null) return null;
3166 synchronized (nai) {
3167 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3168 if (proxyInfo == null) return null;
3169 return new ProxyInfo(proxyInfo);
3170 }
3171 }
3172
Paul Jensene0bef712014-12-10 15:12:18 -05003173 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3174 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3175 // proxy is null then there is no proxy in place).
3176 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3177 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3178 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3179 proxy = null;
3180 }
3181 return proxy;
3182 }
3183
3184 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3185 // better for determining if a new proxy broadcast is necessary:
3186 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3187 // avoid unnecessary broadcasts.
3188 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3189 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3190 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3191 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3192 // all set.
3193 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3194 a = canonicalizeProxyInfo(a);
3195 b = canonicalizeProxyInfo(b);
3196 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3197 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3198 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3199 }
3200
Jason Monk207900c2014-04-25 15:00:09 -04003201 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003202 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003203
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003204 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003205 if (proxyProperties == mGlobalProxy) return;
3206 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3207 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3208
3209 String host = "";
3210 int port = 0;
3211 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003212 String pacFileUrl = "";
3213 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003214 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003215 if (!proxyProperties.isValid()) {
3216 if (DBG)
3217 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3218 return;
3219 }
Jason Monk207900c2014-04-25 15:00:09 -04003220 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003221 host = mGlobalProxy.getHost();
3222 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003223 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003224 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003225 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003226 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003227 } else {
3228 mGlobalProxy = null;
3229 }
3230 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003231 final long token = Binder.clearCallingIdentity();
3232 try {
3233 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3234 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3235 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3236 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003237 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003238 } finally {
3239 Binder.restoreCallingIdentity(token);
3240 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003241
Jason Monkcf0f97a2014-10-02 15:39:38 -04003242 if (mGlobalProxy == null) {
3243 proxyProperties = mDefaultProxy;
3244 }
3245 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003246 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003247 }
3248
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003249 private void loadGlobalProxy() {
3250 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003251 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3252 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3253 String exclList = Settings.Global.getString(res,
3254 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003255 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3256 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003257 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003258 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003259 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003260 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003261 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003262 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003263 if (!proxyProperties.isValid()) {
3264 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3265 return;
3266 }
3267
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003268 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003269 mGlobalProxy = proxyProperties;
3270 }
3271 }
3272 }
3273
Jason Monk207900c2014-04-25 15:00:09 -04003274 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003275 // this information is already available as a world read/writable jvm property
3276 // so this API change wouldn't have a benifit. It also breaks the passing
3277 // of proxy info to all the JVMs.
3278 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003279 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003280 return mGlobalProxy;
3281 }
3282 }
3283
Jason Monk207900c2014-04-25 15:00:09 -04003284 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003285 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003286 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003287 proxy = null;
3288 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003289 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003290 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003291 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003292 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003293 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3294 return;
3295 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003296
3297 // This call could be coming from the PacManager, containing the port of the local
3298 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3299 // global (to get the correct local port), and send a broadcast.
3300 // TODO: Switch PacManager to have its own message to send back rather than
3301 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003302 if ((mGlobalProxy != null) && (proxy != null)
3303 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003304 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3305 mGlobalProxy = proxy;
3306 sendProxyBroadcast(mGlobalProxy);
3307 return;
3308 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003309 mDefaultProxy = proxy;
3310
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003311 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003312 if (!mDefaultProxyDisabled) {
3313 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003314 }
3315 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003316 }
3317
Paul Jensene0bef712014-12-10 15:12:18 -05003318 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3319 // This method gets called when any network changes proxy, but the broadcast only ever contains
3320 // the default proxy (even if it hasn't changed).
3321 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3322 // world where an app might be bound to a non-default network.
3323 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3324 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3325 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3326
3327 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3328 sendProxyBroadcast(getDefaultProxy());
3329 }
3330 }
3331
Robert Greenwalt434203a2010-10-11 16:00:27 -07003332 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003333 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3334 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003335 if (!TextUtils.isEmpty(proxy)) {
3336 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003337 if (data.length == 0) {
3338 return;
3339 }
3340
Robert Greenwalt434203a2010-10-11 16:00:27 -07003341 String proxyHost = data[0];
3342 int proxyPort = 8080;
3343 if (data.length > 1) {
3344 try {
3345 proxyPort = Integer.parseInt(data[1]);
3346 } catch (NumberFormatException e) {
3347 return;
3348 }
3349 }
Jason Monk207900c2014-04-25 15:00:09 -04003350 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003351 setGlobalProxy(p);
3352 }
3353 }
3354
Jason Monk207900c2014-04-25 15:00:09 -04003355 private void sendProxyBroadcast(ProxyInfo proxy) {
3356 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003357 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003358 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003359 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003360 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3361 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003362 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003363 final long ident = Binder.clearCallingIdentity();
3364 try {
3365 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3366 } finally {
3367 Binder.restoreCallingIdentity(ident);
3368 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003369 }
3370
3371 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003372 final private HashMap<Uri, Integer> mUriEventMap;
3373 final private Context mContext;
3374 final private Handler mHandler;
3375
3376 SettingsObserver(Context context, Handler handler) {
3377 super(null);
3378 mUriEventMap = new HashMap<Uri, Integer>();
3379 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003380 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003381 }
3382
Erik Klineda4bfa82015-04-30 12:58:40 +09003383 void observe(Uri uri, int what) {
3384 mUriEventMap.put(uri, what);
3385 final ContentResolver resolver = mContext.getContentResolver();
3386 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003387 }
3388
3389 @Override
3390 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003391 Slog.wtf(TAG, "Should never be reached.");
3392 }
3393
3394 @Override
3395 public void onChange(boolean selfChange, Uri uri) {
3396 final Integer what = mUriEventMap.get(uri);
3397 if (what != null) {
3398 mHandler.obtainMessage(what.intValue()).sendToTarget();
3399 } else {
3400 loge("No matching event to send for URI=" + uri);
3401 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003402 }
3403 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003404
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003405 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003406 Slog.d(TAG, s);
3407 }
3408
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003409 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003410 Slog.e(TAG, s);
3411 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003412
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003413 private static void loge(String s, Throwable t) {
3414 Slog.e(TAG, s, t);
3415 }
3416
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003417 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003418 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003419 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3420 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3421 *
3422 * @param oldPackage Package name of the application which currently controls VPN, which will
3423 * be replaced. If there is no such application, this should should either be
3424 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3425 * @param newPackage Package name of the application which should gain control of VPN, or
3426 * {@code null} to disable.
3427 * @param userId User for whom to prepare the new VPN.
3428 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003429 * @hide
3430 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003431 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003432 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3433 int userId) {
3434 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003435 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003436
Hugo Benichi20035e02017-04-26 14:53:28 +09003437 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003438 Vpn vpn = mVpns.get(userId);
3439 if (vpn != null) {
3440 return vpn.prepare(oldPackage, newPackage);
3441 } else {
3442 return false;
3443 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003444 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003445 }
3446
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003447 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003448 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3449 * This method is used by system-privileged apps.
3450 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3451 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3452 *
3453 * @param packageName The package for which authorization state should change.
3454 * @param userId User for whom {@code packageName} is installed.
3455 * @param authorized {@code true} if this app should be able to start a VPN connection without
3456 * explicit user approval, {@code false} if not.
3457 *
Jeff Davidson05542602014-08-11 14:07:27 -07003458 * @hide
3459 */
3460 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003461 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3462 enforceCrossUserPermission(userId);
3463
Hugo Benichi20035e02017-04-26 14:53:28 +09003464 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003465 Vpn vpn = mVpns.get(userId);
3466 if (vpn != null) {
3467 vpn.setPackageAuthorization(packageName, authorized);
3468 }
Jeff Davidson05542602014-08-11 14:07:27 -07003469 }
3470 }
3471
3472 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003473 * Configure a TUN interface and return its file descriptor. Parameters
3474 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003475 * and not available in ConnectivityManager. Permissions are checked in
3476 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003477 * @hide
3478 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003479 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003480 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003481 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003482 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003483 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003484 return mVpns.get(user).establish(config);
3485 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003486 }
3487
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003488 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003489 * Start legacy VPN, controlling native daemons as needed. Creates a
3490 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003491 */
3492 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003493 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003494 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003495 final LinkProperties egress = getActiveLinkProperties();
3496 if (egress == null) {
3497 throw new IllegalStateException("Missing active network connection");
3498 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003499 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003500 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003501 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3502 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003503 }
3504
3505 /**
3506 * Return the information of the ongoing legacy VPN. This method is used
3507 * by VpnSettings and not available in ConnectivityManager. Permissions
3508 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003509 */
3510 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003511 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3512 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003513
Hugo Benichi20035e02017-04-26 14:53:28 +09003514 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003515 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003516 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003517 }
3518
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003519 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003520 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3521 * and not available in ConnectivityManager.
3522 */
3523 @Override
3524 public VpnInfo[] getAllVpnInfo() {
3525 enforceConnectivityInternalPermission();
3526 if (mLockdownEnabled) {
3527 return new VpnInfo[0];
3528 }
3529
Hugo Benichi20035e02017-04-26 14:53:28 +09003530 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003531 List<VpnInfo> infoList = new ArrayList<>();
3532 for (int i = 0; i < mVpns.size(); i++) {
3533 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3534 if (info != null) {
3535 infoList.add(info);
3536 }
3537 }
3538 return infoList.toArray(new VpnInfo[infoList.size()]);
3539 }
3540 }
3541
3542 /**
3543 * @return VPN information for accounting, or null if we can't retrieve all required
3544 * information, e.g primary underlying iface.
3545 */
3546 @Nullable
3547 private VpnInfo createVpnInfo(Vpn vpn) {
3548 VpnInfo info = vpn.getVpnInfo();
3549 if (info == null) {
3550 return null;
3551 }
3552 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3553 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3554 // the underlyingNetworks list.
3555 if (underlyingNetworks == null) {
3556 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3557 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3558 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3559 }
3560 } else if (underlyingNetworks.length > 0) {
3561 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3562 if (linkProperties != null) {
3563 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3564 }
3565 }
3566 return info.primaryUnderlyingIface == null ? null : info;
3567 }
3568
3569 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003570 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3571 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003572 * Permissions are checked in Vpn class.
3573 * @hide
3574 */
3575 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003576 public VpnConfig getVpnConfig(int userId) {
3577 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003578 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003579 Vpn vpn = mVpns.get(userId);
3580 if (vpn != null) {
3581 return vpn.getVpnConfig();
3582 } else {
3583 return null;
3584 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003585 }
3586 }
3587
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003588 @Override
3589 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003590 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3591 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3592 return false;
3593 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003594
3595 // Tear down existing lockdown if profile was removed
3596 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3597 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003598 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3599 if (profileTag == null) {
3600 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3601 return false;
3602 }
3603 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003604 final VpnProfile profile = VpnProfile.decode(
3605 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003606 if (profile == null) {
3607 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3608 setLockdownTracker(null);
3609 return true;
3610 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003611 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003612 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003613 Vpn vpn = mVpns.get(user);
3614 if (vpn == null) {
3615 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3616 return false;
3617 }
3618 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003619 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003620 } else {
3621 setLockdownTracker(null);
3622 }
3623
3624 return true;
3625 }
3626
3627 /**
3628 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3629 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3630 */
3631 private void setLockdownTracker(LockdownVpnTracker tracker) {
3632 // Shutdown any existing tracker
3633 final LockdownVpnTracker existing = mLockdownTracker;
3634 mLockdownTracker = null;
3635 if (existing != null) {
3636 existing.shutdown();
3637 }
3638
Robin Leec3736bc2017-03-10 16:19:54 +00003639 if (tracker != null) {
3640 mLockdownTracker = tracker;
3641 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003642 }
3643 }
3644
3645 private void throwIfLockdownEnabled() {
3646 if (mLockdownEnabled) {
3647 throw new IllegalStateException("Unavailable in lockdown mode");
3648 }
3649 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003650
Robin Lee244ce8e2016-01-05 18:03:46 +00003651 /**
Robin Lee17e61832016-05-09 13:46:28 +01003652 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3653 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003654 *
Robin Lee17e61832016-05-09 13:46:28 +01003655 * @return {@code true} if the service was started, the service was already connected, or there
3656 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003657 */
Robin Lee17e61832016-05-09 13:46:28 +01003658 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003659 synchronized (mVpns) {
3660 Vpn vpn = mVpns.get(userId);
3661 if (vpn == null) {
3662 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3663 // exists already.
3664 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3665 return false;
3666 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003667
Robin Lee812800c2016-05-13 15:38:08 +01003668 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003669 }
3670 }
3671
3672 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003673 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3674 enforceSettingsPermission();
3675 enforceCrossUserPermission(userId);
3676
3677 synchronized (mVpns) {
3678 Vpn vpn = mVpns.get(userId);
3679 if (vpn == null) {
3680 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3681 return false;
3682 }
3683 return vpn.isAlwaysOnPackageSupported(packageName);
3684 }
3685 }
3686
3687 @Override
Robin Leedc679712016-05-03 13:23:03 +01003688 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003689 enforceConnectivityInternalPermission();
3690 enforceCrossUserPermission(userId);
3691
3692 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3693 if (LockdownVpnTracker.isEnabled()) {
3694 return false;
3695 }
3696
Robin Lee244ce8e2016-01-05 18:03:46 +00003697 synchronized (mVpns) {
3698 Vpn vpn = mVpns.get(userId);
3699 if (vpn == null) {
3700 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3701 return false;
3702 }
Robin Lee17e61832016-05-09 13:46:28 +01003703 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003704 return false;
3705 }
Robin Lee17e61832016-05-09 13:46:28 +01003706 if (!startAlwaysOnVpn(userId)) {
3707 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003708 return false;
3709 }
3710 }
3711 return true;
3712 }
3713
3714 @Override
3715 public String getAlwaysOnVpnPackage(int userId) {
3716 enforceConnectivityInternalPermission();
3717 enforceCrossUserPermission(userId);
3718
3719 synchronized (mVpns) {
3720 Vpn vpn = mVpns.get(userId);
3721 if (vpn == null) {
3722 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3723 return null;
3724 }
3725 return vpn.getAlwaysOnPackage();
3726 }
3727 }
3728
Wink Savilleab9321d2013-06-29 21:10:57 -07003729 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003730 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003731 // TODO: Remove? Any reason to trigger a provisioning check?
3732 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003733 }
3734
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003735 /** Location to an updatable file listing carrier provisioning urls.
3736 * An example:
3737 *
3738 * <?xml version="1.0" encoding="utf-8"?>
3739 * <provisioningUrls>
3740 * <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 -07003741 * </provisioningUrls>
3742 */
3743 private static final String PROVISIONING_URL_PATH =
3744 "/data/misc/radio/provisioning_urls.xml";
3745 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003746
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003747 /** XML tag for root element. */
3748 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3749 /** XML tag for individual url */
3750 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003751 /** XML attribute for mcc */
3752 private static final String ATTR_MCC = "mcc";
3753 /** XML attribute for mnc */
3754 private static final String ATTR_MNC = "mnc";
3755
Paul Jensen434dde82015-06-11 09:43:30 -04003756 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003757 FileReader fileReader = null;
3758 XmlPullParser parser = null;
3759 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003760
3761 try {
3762 fileReader = new FileReader(mProvisioningUrlFile);
3763 parser = Xml.newPullParser();
3764 parser.setInput(fileReader);
3765 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3766
3767 while (true) {
3768 XmlUtils.nextElement(parser);
3769
3770 String element = parser.getName();
3771 if (element == null) break;
3772
Paul Jensen434dde82015-06-11 09:43:30 -04003773 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003774 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3775 try {
3776 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3777 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3778 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3779 parser.next();
3780 if (parser.getEventType() == XmlPullParser.TEXT) {
3781 return parser.getText();
3782 }
3783 }
3784 }
3785 } catch (NumberFormatException e) {
3786 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3787 }
3788 }
3789 }
3790 return null;
3791 } catch (FileNotFoundException e) {
3792 loge("Carrier Provisioning Urls file not found");
3793 } catch (XmlPullParserException e) {
3794 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3795 } catch (IOException e) {
3796 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3797 } finally {
3798 if (fileReader != null) {
3799 try {
3800 fileReader.close();
3801 } catch (IOException e) {}
3802 }
3803 }
3804 return null;
3805 }
3806
Wink Saville42d4f082013-07-20 20:31:59 -07003807 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003808 public String getMobileProvisioningUrl() {
3809 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003810 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003811 if (TextUtils.isEmpty(url)) {
3812 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003813 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003814 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003815 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003816 }
Wink Saville8cf35602013-07-10 23:00:07 -07003817 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003818 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003819 String phoneNumber = mTelephonyManager.getLine1Number();
3820 if (TextUtils.isEmpty(phoneNumber)) {
3821 phoneNumber = "0000000000";
3822 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003823 url = String.format(url,
3824 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3825 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003826 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003827 }
3828
Wink Savilleab9321d2013-06-29 21:10:57 -07003829 return url;
3830 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003831
Wink Saville948282b2013-08-29 08:55:16 -07003832 @Override
3833 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003834 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003835 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003836 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3837 return;
3838 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003839 final long ident = Binder.clearCallingIdentity();
3840 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003841 // Concatenate the range of types onto the range of NetIDs.
3842 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3843 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003844 } finally {
3845 Binder.restoreCallingIdentity(ident);
3846 }
Wink Saville948282b2013-08-29 08:55:16 -07003847 }
Wink Saville7788c612013-08-29 14:57:08 -07003848
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003849 @Override
3850 public void setAirplaneMode(boolean enable) {
3851 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003852 final long ident = Binder.clearCallingIdentity();
3853 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003854 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003855 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003856 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3857 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003858 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003859 } finally {
3860 Binder.restoreCallingIdentity(ident);
3861 }
3862 }
3863
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003864 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003865 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003866 Vpn userVpn = mVpns.get(userId);
3867 if (userVpn != null) {
3868 loge("Starting user already has a VPN");
3869 return;
3870 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003871 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003872 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003873 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003874 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3875 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003876 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003877 }
3878
3879 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003880 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003881 Vpn userVpn = mVpns.get(userId);
3882 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003883 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003884 return;
3885 }
Robin Lee17e61832016-05-09 13:46:28 +01003886 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003887 mVpns.delete(userId);
3888 }
3889 }
3890
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003891 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003892 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003893 final int vpnsSize = mVpns.size();
3894 for (int i = 0; i < vpnsSize; i++) {
3895 Vpn vpn = mVpns.valueAt(i);
3896 vpn.onUserAdded(userId);
3897 }
3898 }
3899 }
3900
3901 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003902 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003903 final int vpnsSize = mVpns.size();
3904 for (int i = 0; i < vpnsSize; i++) {
3905 Vpn vpn = mVpns.valueAt(i);
3906 vpn.onUserRemoved(userId);
3907 }
3908 }
3909 }
3910
Robin Lee89e7a692016-02-29 14:38:17 +00003911 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003912 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3913 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3914 updateLockdownVpn();
3915 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003916 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003917 }
3918 }
3919
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003920 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3921 @Override
3922 public void onReceive(Context context, Intent intent) {
3923 final String action = intent.getAction();
3924 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3925 if (userId == UserHandle.USER_NULL) return;
3926
Robin Lee323f29d2016-05-04 16:38:06 +01003927 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003928 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003929 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003930 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003931 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3932 onUserAdded(userId);
3933 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3934 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003935 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3936 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003937 }
3938 }
3939 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003940
Robin Lee95204e02017-01-27 11:59:22 +00003941 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3942 @Override
3943 public void onReceive(Context context, Intent intent) {
3944 // Try creating lockdown tracker, since user present usually means
3945 // unlocked keystore.
3946 updateLockdownVpn();
3947 mContext.unregisterReceiver(this);
3948 }
3949 };
3950
Robert Greenwalta67be032014-05-16 15:49:14 -07003951 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3952 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003953 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3954 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003955
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003956 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3957 // Map from UID to number of NetworkRequests that UID has filed.
3958 @GuardedBy("mUidToNetworkRequestCount")
3959 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3960
Robert Greenwalta67be032014-05-16 15:49:14 -07003961 private static class NetworkFactoryInfo {
3962 public final String name;
3963 public final Messenger messenger;
3964 public final AsyncChannel asyncChannel;
3965
3966 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3967 this.name = name;
3968 this.messenger = messenger;
3969 this.asyncChannel = asyncChannel;
3970 }
3971 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003972
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003973 private void ensureNetworkRequestHasType(NetworkRequest request) {
3974 if (request.type == NetworkRequest.Type.NONE) {
3975 throw new IllegalArgumentException(
3976 "All NetworkRequests in ConnectivityService must have a type");
3977 }
3978 }
3979
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003980 /**
3981 * Tracks info about the requester.
3982 * Also used to notice when the calling process dies so we can self-expire
3983 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003984 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003985 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003986 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003987 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003988 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003989 final int mPid;
3990 final int mUid;
3991 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003992
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003993 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003994 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003995 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003996 mPendingIntent = pi;
3997 messenger = null;
3998 mBinder = null;
3999 mPid = getCallingPid();
4000 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004001 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004002 }
4003
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004004 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004005 super();
4006 messenger = m;
4007 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004008 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004009 mBinder = binder;
4010 mPid = getCallingPid();
4011 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004012 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004013 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004014
4015 try {
4016 mBinder.linkToDeath(this, 0);
4017 } catch (RemoteException e) {
4018 binderDied();
4019 }
4020 }
4021
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004022 private void enforceRequestCountLimit() {
4023 synchronized (mUidToNetworkRequestCount) {
4024 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4025 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004026 throw new ServiceSpecificException(
4027 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004028 }
4029 mUidToNetworkRequestCount.put(mUid, networkRequests);
4030 }
4031 }
4032
Robert Greenwalt9258c642014-03-26 16:47:06 -07004033 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004034 if (mBinder != null) {
4035 mBinder.unlinkToDeath(this, 0);
4036 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004037 }
4038
4039 public void binderDied() {
4040 log("ConnectivityService NetworkRequestInfo binderDied(" +
4041 request + ", " + mBinder + ")");
4042 releaseNetworkRequest(request);
4043 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004044
4045 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004046 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004047 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004048 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004049 }
4050
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004051 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4052 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4053 if (badCapability != null) {
4054 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004055 }
4056 }
4057
Erik Kline9d598e12015-07-13 16:37:51 +09004058 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004059 final SortedSet<Integer> thresholds = new TreeSet();
4060 synchronized (nai) {
4061 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4062 if (nri.request.networkCapabilities.hasSignalStrength() &&
4063 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4064 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4065 }
4066 }
4067 }
Erik Kline9d598e12015-07-13 16:37:51 +09004068 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004069 }
4070
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004071 private void updateSignalStrengthThresholds(
4072 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4073 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004074 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004075 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4076
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004077 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004078 String detail;
4079 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4080 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4081 } else {
4082 detail = reason;
4083 }
4084 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4085 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4086 }
4087
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004088 nai.asyncChannel.sendMessage(
4089 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004090 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004091 }
4092
Etan Cohen859748f2017-04-03 17:42:34 -07004093 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4094 if (nc == null) {
4095 return;
4096 }
4097 NetworkSpecifier ns = nc.getNetworkSpecifier();
4098 if (ns == null) {
4099 return;
4100 }
4101 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4102 ns.assertValidFromUid(Binder.getCallingUid());
4103 }
4104
Robert Greenwalt9258c642014-03-26 16:47:06 -07004105 @Override
4106 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004107 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004108 final NetworkRequest.Type type = (networkCapabilities == null)
4109 ? NetworkRequest.Type.TRACK_DEFAULT
4110 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004111 // If the requested networkCapabilities is null, take them instead from
4112 // the default network request. This allows callers to keep track of
4113 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004114 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004115 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4116 enforceAccessPermission();
4117 } else {
4118 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4119 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004120 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4121 // of the app when the request is filed, but we never change the request if the app
4122 // changes network state. http://b/29964605
4123 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004124 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004125 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004126
Etan Cohenba07c8c2017-02-05 10:42:27 -08004127 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004128 throw new IllegalArgumentException("Bad timeout specified");
4129 }
Etan Cohen859748f2017-04-03 17:42:34 -07004130 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004131
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004132 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004133 nextNetworkRequestId(), type);
4134 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004135 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004136
4137 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004138 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004139 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004140 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004141 }
4142 return networkRequest;
4143 }
4144
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004145 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004146 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004147 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004148 } else {
4149 enforceChangePermission();
4150 }
4151 }
4152
fenglub15e72b2015-03-20 11:29:56 -07004153 @Override
fengludb571472015-04-21 17:12:05 -07004154 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004155 enforceAccessPermission();
4156 NetworkAgentInfo nai = null;
4157 if (network == null) {
4158 return false;
4159 }
4160 synchronized (mNetworkForNetId) {
4161 nai = mNetworkForNetId.get(network.netId);
4162 }
4163 if (nai != null) {
4164 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4165 return true;
4166 }
4167 return false;
4168 }
4169
Felipe Lemeee27cab2016-06-20 16:36:29 -07004170 private boolean isSystem(int uid) {
4171 return uid < Process.FIRST_APPLICATION_UID;
4172 }
fenglub15e72b2015-03-20 11:29:56 -07004173
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004174 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004175 final int uid = Binder.getCallingUid();
4176 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004177 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004178 return;
4179 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004180 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4181 // Policy already enforced.
4182 return;
4183 }
4184 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4185 // If UID is restricted, don't allow them to bring up metered APNs.
4186 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004187 }
4188 }
4189
Robert Greenwalt9258c642014-03-26 16:47:06 -07004190 @Override
4191 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4192 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004193 checkNotNull(operation, "PendingIntent cannot be null.");
4194 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4195 enforceNetworkRequestPermissions(networkCapabilities);
4196 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004197 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004198 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004199
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004200 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004201 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4202 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004203 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004204 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4205 nri));
4206 return networkRequest;
4207 }
4208
Jeremy Joslin79294842014-12-03 17:15:28 -08004209 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4210 mHandler.sendMessageDelayed(
4211 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4212 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4213 }
4214
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004215 @Override
4216 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004217 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004218 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4219 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004220 }
4221
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004222 // In order to implement the compatibility measure for pre-M apps that call
4223 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4224 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4225 // This ensures it has permission to do so.
4226 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4227 if (nc == null) {
4228 return false;
4229 }
4230 int[] transportTypes = nc.getTransportTypes();
4231 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4232 return false;
4233 }
4234 try {
4235 mContext.enforceCallingOrSelfPermission(
4236 android.Manifest.permission.ACCESS_WIFI_STATE,
4237 "ConnectivityService");
4238 } catch (SecurityException e) {
4239 return false;
4240 }
4241 return true;
4242 }
4243
Robert Greenwalt9258c642014-03-26 16:47:06 -07004244 @Override
4245 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4246 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004247 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4248 enforceAccessPermission();
4249 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004250
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004251 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4252 if (!ConnectivityManager.checkChangePermission(mContext)) {
4253 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4254 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4255 // onLost and onAvailable callbacks when networks move in and out of the background.
4256 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4257 // can't request networks.
4258 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4259 }
Etan Cohen859748f2017-04-03 17:42:34 -07004260 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004261
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004262 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004263 NetworkRequest.Type.LISTEN);
4264 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004265 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004266
4267 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4268 return networkRequest;
4269 }
4270
4271 @Override
4272 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4273 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004274 checkNotNull(operation, "PendingIntent cannot be null.");
4275 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4276 enforceAccessPermission();
4277 }
Etan Cohen859748f2017-04-03 17:42:34 -07004278 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004279
Erik Kline7523eb32015-07-09 18:24:03 +09004280 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004281 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4282 NetworkRequest.Type.LISTEN);
4283 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004284 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004285
4286 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004287 }
4288
Erik Klineacdd6392016-07-07 16:50:58 +09004289 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004290 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004291 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004292 mHandler.sendMessage(mHandler.obtainMessage(
4293 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004294 }
4295
4296 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004297 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004298 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004299 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4300 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004301 }
4302
Robert Greenwalta67be032014-05-16 15:49:14 -07004303 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004304 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004305 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4306 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4307 }
4308
4309 @Override
4310 public void unregisterNetworkFactory(Messenger messenger) {
4311 enforceConnectivityInternalPermission();
4312 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4313 }
4314
4315 private void handleUnregisterNetworkFactory(Messenger messenger) {
4316 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4317 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004318 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004319 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004320 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004321 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004322 }
4323
Robert Greenwalt7b816022014-04-18 15:25:25 -07004324 /**
4325 * NetworkAgentInfo supporting a request by requestId.
4326 * These have already been vetted (their Capabilities satisfy the request)
4327 * and the are the highest scored network available.
4328 * the are keyed off the Requests requestId.
4329 */
Hugo Benichicd952782017-09-20 11:20:14 +09004330 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4331 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004332 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4333 new SparseArray<NetworkAgentInfo>();
4334
Paul Jensen31a94f42015-02-13 14:18:39 -05004335 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4336 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004337 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4338 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004339 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4340 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4341 // there may not be a strict 1:1 correlation between the two.
4342 @GuardedBy("mNetworkForNetId")
4343 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004344
Robert Greenwalt7b816022014-04-18 15:25:25 -07004345 // NetworkAgentInfo keyed off its connecting messenger
4346 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004347 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004348 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4349 new HashMap<Messenger, NetworkAgentInfo>();
4350
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004351 @GuardedBy("mBlockedAppUids")
4352 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4353
Paul Jensen2c311d62014-11-17 12:34:51 -05004354 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004355 private final NetworkRequest mDefaultRequest;
4356
Erik Klineda4bfa82015-04-30 12:58:40 +09004357 // Request used to optionally keep mobile data active even when higher
4358 // priority networks like Wi-Fi are active.
4359 private final NetworkRequest mDefaultMobileDataRequest;
4360
Hugo Benichicd952782017-09-20 11:20:14 +09004361 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4362 synchronized (mNetworkForRequestId) {
4363 return mNetworkForRequestId.get(requestId);
4364 }
4365 }
4366
4367 private void clearNetworkForRequest(int requestId) {
4368 synchronized (mNetworkForRequestId) {
4369 mNetworkForRequestId.remove(requestId);
4370 }
4371 }
4372
4373 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4374 synchronized (mNetworkForRequestId) {
4375 mNetworkForRequestId.put(requestId, nai);
4376 }
4377 }
4378
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004379 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004380 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004381 }
4382
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004383 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004384 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004385 }
4386
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004387 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4388 return nri.request.requestId == mDefaultRequest.requestId;
4389 }
4390
Paul Jensen31a94f42015-02-13 14:18:39 -05004391 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004392 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004393 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394 enforceConnectivityInternalPermission();
4395
Rubin Xu1bb5c082017-09-05 18:40:49 +01004396 LinkProperties lp = new LinkProperties(linkProperties);
4397 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004398 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4399 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004400 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004401 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4402 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004403 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004404 synchronized (this) {
4405 nai.networkMonitor.systemReady = mSystemReady;
4406 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004407 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4408 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004409 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004410 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004411 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004412 }
4413
4414 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4415 if (VDBG) log("Got NetworkAgent Messenger");
4416 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004417 synchronized (mNetworkForNetId) {
4418 mNetworkForNetId.put(na.network.netId, na);
4419 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004420 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4421 NetworkInfo networkInfo = na.networkInfo;
4422 na.networkInfo = null;
4423 updateNetworkInfo(na, networkInfo);
4424 }
4425
4426 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4427 LinkProperties newLp = networkAgent.linkProperties;
4428 int netId = networkAgent.network.netId;
4429
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004430 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4431 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004432 if (networkAgent.clatd != null) {
4433 networkAgent.clatd.fixupLinkProperties(oldLp);
4434 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004435
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004436 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004437 updateMtu(newLp, oldLp);
4438 // TODO - figure out what to do for clat
4439// for (LinkProperties lp : newLp.getStackedLinks()) {
4440// updateMtu(lp, null);
4441// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004442 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004443
Erik Kline94887872016-04-05 13:30:49 +09004444 updateRoutes(newLp, oldLp, netId);
4445 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004446
Hugo Benichib577d652017-06-27 15:13:20 +09004447 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004448 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004449 if (isDefaultNetwork(networkAgent)) {
4450 handleApplyDefaultProxy(newLp.getHttpProxy());
4451 } else {
4452 updateProxy(newLp, oldLp, networkAgent);
4453 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004454 // TODO - move this check to cover the whole function
4455 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004456 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004457 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4458 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004459
4460 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004461 }
4462
Joel Scherpelz668370b2017-06-08 15:35:21 +09004463 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004464 // Marks are only available on WiFi interaces. Checking for
4465 // marks on unsupported interfaces is harmless.
4466 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4467 return;
4468 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004469
Joel Scherpelz668370b2017-06-08 15:35:21 +09004470 int mark = mContext.getResources().getInteger(
4471 com.android.internal.R.integer.config_networkWakeupPacketMark);
4472 int mask = mContext.getResources().getInteger(
4473 com.android.internal.R.integer.config_networkWakeupPacketMask);
4474
4475 // Mask/mark of zero will not detect anything interesting.
4476 // Don't install rules unless both values are nonzero.
4477 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004478 return;
4479 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004480
4481 final String prefix = "iface:" + iface;
4482 try {
4483 if (add) {
4484 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4485 } else {
4486 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4487 }
4488 } catch (Exception e) {
4489 loge("Exception modifying wakeup packet monitoring: " + e);
4490 }
4491
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004492 }
4493
4494 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4495 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004496 CompareResult<String> interfaceDiff = new CompareResult<String>(
4497 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4498 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004499 for (String iface : interfaceDiff.added) {
4500 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004501 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004502 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004503 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004504 } catch (Exception e) {
4505 loge("Exception adding interface: " + e);
4506 }
4507 }
4508 for (String iface : interfaceDiff.removed) {
4509 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004510 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004511 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004512 mNetd.removeInterfaceFromNetwork(iface, netId);
4513 } catch (Exception e) {
4514 loge("Exception removing interface: " + e);
4515 }
4516 }
4517 }
4518
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004519 /**
4520 * Have netd update routes from oldLp to newLp.
4521 * @return true if routes changed between oldLp and newLp
4522 */
4523 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004524 // Compare the route diff to determine which routes should be added and removed.
4525 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4526 oldLp != null ? oldLp.getAllRoutes() : null,
4527 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004528
4529 // add routes before removing old in case it helps with continuous connectivity
4530
4531 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4532 for (RouteInfo route : routeDiff.added) {
4533 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004534 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004535 try {
4536 mNetd.addRoute(netId, route);
4537 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004538 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4539 loge("Exception in addRoute for non-gateway: " + e);
4540 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004541 }
4542 }
4543 for (RouteInfo route : routeDiff.added) {
4544 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004545 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004546 try {
4547 mNetd.addRoute(netId, route);
4548 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004549 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4550 loge("Exception in addRoute for gateway: " + e);
4551 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004552 }
4553 }
4554
4555 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004556 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004557 try {
4558 mNetd.removeRoute(netId, route);
4559 } catch (Exception e) {
4560 loge("Exception in removeRoute: " + e);
4561 }
4562 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004563 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004564 }
Erik Kline41368502015-06-17 13:19:54 +09004565
Erik Kline94887872016-04-05 13:30:49 +09004566 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4567 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4568 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 }
Erik Kline94887872016-04-05 13:30:49 +09004570
4571 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004572 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004573 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004574 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004575 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4576 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004577 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004578 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004579 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4580 if (defaultNai != null && defaultNai.network.netId == netId) {
4581 setDefaultDnsSystemProperties(dnses);
4582 }
Erik Kline94887872016-04-05 13:30:49 +09004583 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004584 }
4585
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004586 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4587 int last = 0;
4588 for (InetAddress dns : dnses) {
4589 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004590 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004591 }
4592 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004593 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004594 }
4595 mNumDnsEntries = last;
4596 }
4597
Erik Kline4edba012017-04-07 15:29:29 +09004598 private void setNetDnsProperty(int which, String value) {
4599 final String key = "net.dns" + which;
4600 // Log and forget errors setting unsupported properties.
4601 try {
4602 mSystemProperties.set(key, value);
4603 } catch (Exception e) {
4604 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4605 }
4606 }
4607
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004608 private String getNetworkPermission(NetworkCapabilities nc) {
4609 // TODO: make these permission strings AIDL constants instead.
4610 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4611 return NetworkManagementService.PERMISSION_SYSTEM;
4612 }
4613 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4614 return NetworkManagementService.PERMISSION_NETWORK;
4615 }
4616 return null;
4617 }
4618
Paul Jensen3d194ea2015-06-16 14:27:36 -04004619 /**
4620 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4621 * augmented with any stateful capabilities implied from {@code networkAgent}
4622 * (e.g., validated status and captive portal status).
4623 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004624 * @param oldScore score of the network before any of the changes that prompted us
4625 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004626 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004627 * @param networkCapabilities the new network capabilities.
4628 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004629 private void updateCapabilities(
4630 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004631 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Hugo Benichia60c6ea2017-08-18 14:41:22 +09004632 if (nai.everConnected && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
4633 networkCapabilities)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004634 // TODO: consider not complaining when a network agent degrade its capabilities if this
4635 // does not cause any request (that is not a listen) currently matching that agent to
4636 // stop being matched by the updated agent.
Hugo Benichieae7a222017-07-25 11:40:56 +09004637 String diff = nai.networkCapabilities.describeImmutableDifferences(networkCapabilities);
4638 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004639 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004640 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004641 }
4642
Paul Jensen3d194ea2015-06-16 14:27:36 -04004643 // Don't modify caller's NetworkCapabilities.
4644 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004645 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004646 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4647 } else {
4648 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4649 }
Paul Jensene0988542015-06-25 15:30:08 -04004650 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004651 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4652 } else {
4653 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4654 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004655 if (nai.isBackgroundNetwork()) {
4656 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4657 } else {
4658 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4659 }
4660
4661 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4662
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004663 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4664 final String newPermission = getNetworkPermission(networkCapabilities);
4665 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004666 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004667 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004668 } catch (RemoteException e) {
4669 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004670 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004671 }
4672
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004673 final NetworkCapabilities prevNc = nai.networkCapabilities;
4674 synchronized (nai) {
4675 nai.networkCapabilities = networkCapabilities;
4676 }
4677 if (nai.getCurrentScore() == oldScore &&
4678 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4679 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4680 // the change we're processing can't affect any requests, it can only affect the listens
4681 // on this network. We might have been called by rematchNetworkAndRequests when a
4682 // network changed foreground state.
4683 processListenRequests(nai, true);
4684 } else {
4685 // If the requestable capabilities have changed or the score changed, we can't have been
4686 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004687 rematchAllNetworksAndRequests(nai, oldScore);
4688 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004689 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004690 }
4691
Hugo Benichief502882017-09-01 01:23:32 +00004692 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4693 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4694 // Ignore updates for disconnected networks
4695 return;
4696 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004697 // newLp is already a defensive copy.
4698 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004699 if (VDBG) {
4700 log("Update of LinkProperties for " + nai.name() +
4701 "; created=" + nai.created +
4702 "; everConnected=" + nai.everConnected);
4703 }
4704 LinkProperties oldLp = nai.linkProperties;
4705 synchronized (nai) {
4706 nai.linkProperties = newLp;
4707 }
4708 if (nai.everConnected) {
4709 updateLinkProperties(nai, oldLp);
4710 }
4711 }
4712
Paul Jensenc8b9a742014-09-30 15:37:41 -04004713 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004714 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4715 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004716 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004717 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004718 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4719 }
4720 }
4721
Robert Greenwalt7b816022014-04-18 15:25:25 -07004722 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4723 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004724 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004725 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4726 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004727 }
4728 }
4729
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004730 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4731 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004732 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004733 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004734 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4735 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004736 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004737 sendIntent(nri.mPendingIntent, intent);
4738 }
4739 // else not handled
4740 }
4741
4742 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4743 mPendingIntentWakeLock.acquire();
4744 try {
4745 if (DBG) log("Sending " + pendingIntent);
4746 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4747 } catch (PendingIntent.CanceledException e) {
4748 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4749 mPendingIntentWakeLock.release();
4750 releasePendingNetworkRequest(pendingIntent);
4751 }
4752 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4753 }
4754
4755 @Override
4756 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4757 String resultData, Bundle resultExtras) {
4758 if (DBG) log("Finished sending " + pendingIntent);
4759 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004760 // Release with a delay so the receiving client has an opportunity to put in its
4761 // own request.
4762 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004763 }
4764
Hugo Benichidba33db2017-03-23 22:40:44 +09004765 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004766 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004767 if (nri.messenger == null) {
4768 return; // Default request has no msgr
4769 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004770 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004771 // TODO: check if defensive copies of data is needed.
4772 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004773 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004774 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4775 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004776 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004777 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004778 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004779 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004780 break;
4781 }
4782 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004783 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004784 break;
4785 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004786 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004787 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004788 break;
4789 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004790 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004791 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004792 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004793 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004794 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004795 String notification = ConnectivityManager.getCallbackName(notificationType);
4796 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004797 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004798 nri.messenger.send(msg);
4799 } catch (RemoteException e) {
4800 // may occur naturally in the race of binder death.
4801 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4802 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004803 }
4804
Hugo Benichidba33db2017-03-23 22:40:44 +09004805 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4806 bundle.putParcelable(t.getClass().getSimpleName(), t);
4807 }
4808
Paul Jensenc8b9a742014-09-30 15:37:41 -04004809 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004810 if (nai.numRequestNetworkRequests() != 0) {
4811 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4812 NetworkRequest nr = nai.requestAt(i);
4813 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004814 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004815 loge("Dead network still had at least " + nr);
4816 break;
4817 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004818 }
4819 nai.asyncChannel.disconnect();
4820 }
4821
Robert Greenwalt7b816022014-04-18 15:25:25 -07004822 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4823 if (oldNetwork == null) {
4824 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4825 return;
4826 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004827 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004828
4829 // If we get here it means that the last linger timeout for this network expired. So there
4830 // must be no other active linger timers, and we must stop lingering.
4831 oldNetwork.clearLingerState();
4832
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004833 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004834 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004835 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004836 } else {
4837 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004838 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4839 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004840 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004841 }
4842
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004843 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004844 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004845 setupDataActivityTracking(newNetwork);
4846 try {
4847 mNetd.setDefaultNetId(newNetwork.network.netId);
4848 } catch (Exception e) {
4849 loge("Exception setting default network :" + e);
4850 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004851 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004852 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004853 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004854 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004855 }
4856
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004857 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004858 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4859 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4860 NetworkRequest nr = nri.request;
4861 if (!nr.isListen()) continue;
4862 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4863 nai.removeRequest(nri.request.requestId);
4864 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4865 }
4866 }
4867
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004868 if (capabilitiesChanged) {
4869 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4870 }
4871
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004872 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4873 NetworkRequest nr = nri.request;
4874 if (!nr.isListen()) continue;
4875 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4876 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004877 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004878 }
4879 }
4880 }
4881
Paul Jensen2161a8e2014-09-11 11:00:39 -04004882 // Handles a network appearing or improving its score.
4883 //
4884 // - Evaluates all current NetworkRequests that can be
4885 // satisfied by newNetwork, and reassigns to newNetwork
4886 // any such requests for which newNetwork is the best.
4887 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004888 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004889 // needed. A network is needed if it is the best network for
4890 // one or more NetworkRequests, or if it is a VPN.
4891 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004892 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004893 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004894 //
4895 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4896 // networks that have no chance (i.e. even if validated)
4897 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004898 //
4899 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4900 // it does not remove NetworkRequests that other Networks could better satisfy.
4901 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4902 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4903 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004904 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004905 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004906 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4907 // performed to tear down unvalidated networks that have no chance (i.e. even if
4908 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004909 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004910 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004911 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004912 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004913 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004914 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004915
4916 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4917 final int score = newNetwork.getCurrentScore();
4918
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004919 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004920
Paul Jensen2161a8e2014-09-11 11:00:39 -04004921 // Find and migrate to this Network any NetworkRequests for
4922 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004923 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004924 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004925 NetworkCapabilities nc = newNetwork.networkCapabilities;
4926 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004927 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004928 // Process requests in the first pass and listens in the second pass. This allows us to
4929 // change a network's capabilities depending on which requests it has. This is only
4930 // correct if the change in capabilities doesn't affect whether the network satisfies
4931 // requests or not, and doesn't affect the network's score.
4932 if (nri.request.isListen()) continue;
4933
Hugo Benichicd952782017-09-20 11:20:14 +09004934 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004935 final boolean satisfies = newNetwork.satisfies(nri.request);
4936 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004937 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004938 log("Network " + newNetwork.name() + " was already satisfying" +
4939 " request " + nri.request.requestId + ". No change.");
4940 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004941 keep = true;
4942 continue;
4943 }
4944
4945 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004946 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004947 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004948 // next check if it's better than any current network we're using for
4949 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004950 if (VDBG) {
4951 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004952 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004953 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004954 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004955 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004956 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004957 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004958 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004959 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004960 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004961 affectedNetworks.add(currentNetwork);
4962 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004963 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004964 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004965 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09004966 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004967 if (!newNetwork.addRequest(nri.request)) {
4968 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4969 }
4970 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004971 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004972 // Tell NetworkFactories about the new score, so they can stop
4973 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004974 // TODO - this could get expensive if we have alot of requests for this
4975 // network. Think about if there is a way to reduce this. Push
4976 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004977 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004978 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004979 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004980 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004981 if (currentNetwork != null) {
4982 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4983 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004984 }
4985 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004986 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004987 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4988 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004989 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004990 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4991 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4992 // This means this code doesn't have to handle the case where "currentNetwork" no
4993 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4994 if (DBG) {
4995 log("Network " + newNetwork.name() + " stopped satisfying" +
4996 " request " + nri.request.requestId);
4997 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004998 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004999 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005000 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005001 sendUpdatedScoreToFactories(nri.request, 0);
5002 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005003 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5004 newNetwork.name() +
5005 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005006 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005007 // TODO: Technically, sending CALLBACK_LOST here is
5008 // incorrect if there is a replacement network currently
5009 // connected that can satisfy nri, which is a request
5010 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005011 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5012 // so this code is only incorrect for a network that loses
5013 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005014 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005015 }
5016 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005017 if (isNewDefault) {
5018 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005019 makeDefault(newNetwork);
5020 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005021 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005022 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005023 // Have a new default network, release the transition wakelock in
5024 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005025 }
5026
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005027 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5028 Slog.wtf(TAG, String.format(
5029 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005030 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005031 }
5032 if (newNetwork.getCurrentScore() != score) {
5033 Slog.wtf(TAG, String.format(
5034 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005035 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005036 }
5037
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005038 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005039 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5040 // If the network went from background to foreground or vice versa, we need to update
5041 // its foreground state. It is safe to do this after rematching the requests because
5042 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5043 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005044 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005045 } else {
5046 processListenRequests(newNetwork, false);
5047 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005048
Paul Jensencf4c2c62015-07-01 14:16:32 -04005049 // do this after the default net is switched, but
5050 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005051 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005052
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005053 // Linger any networks that are no longer needed. This should be done after sending the
5054 // available callback for newNetwork.
5055 for (NetworkAgentInfo nai : affectedNetworks) {
5056 updateLingerState(nai, now);
5057 }
5058 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5059 // does not need to be done in any particular order.
5060 updateLingerState(newNetwork, now);
5061
Paul Jensencf4c2c62015-07-01 14:16:32 -04005062 if (isNewDefault) {
5063 // Maintain the illusion: since the legacy API only
5064 // understands one network at a time, we must pretend
5065 // that the current default network disconnected before
5066 // the new one connected.
5067 if (oldDefaultNetwork != null) {
5068 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5069 oldDefaultNetwork, true);
5070 }
5071 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5072 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5073 notifyLockdownVpn(newNetwork);
5074 }
5075
Robert Greenwalt7b816022014-04-18 15:25:25 -07005076 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005077 // Notify battery stats service about this network, both the normal
5078 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005079 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005080 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005081 final IBatteryStats bs = BatteryStatsService.getService();
5082 final int type = newNetwork.networkInfo.getType();
5083
5084 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5085 bs.noteNetworkInterfaceType(baseIface, type);
5086 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5087 final String stackedIface = stacked.getInterfaceName();
5088 bs.noteNetworkInterfaceType(stackedIface, type);
5089 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5090 }
5091 } catch (RemoteException ignored) {
5092 }
5093
Robert Greenwalt152ed372014-12-17 17:19:53 -08005094 // This has to happen after the notifyNetworkCallbacks as that tickles each
5095 // ConnectivityManager instance so that legacy requests correctly bind dns
5096 // requests to this network. The legacy users are listening for this bcast
5097 // and will generally do a dns request so they can ensureRouteToHost and if
5098 // they do that before the callbacks happen they'll use the default network.
5099 //
5100 // TODO: Is there still a race here? We send the broadcast
5101 // after sending the callback, but if the app can receive the
5102 // broadcast before the callback, it might still break.
5103 //
5104 // This *does* introduce a race where if the user uses the new api
5105 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5106 // they may get old info. Reverse this after the old startUsing api is removed.
5107 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005108 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5109 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005110 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005111 // legacy type tracker filters out repeat adds
5112 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5113 }
5114 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005115
5116 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5117 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5118 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5119 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5120 if (newNetwork.isVPN()) {
5121 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5122 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005123 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005124 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5125 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005126 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005127 if (nai.getLingerExpiry() > 0) {
5128 // This network has active linger timers and no requests, but is not
5129 // lingering. Linger it.
5130 //
5131 // One way (the only way?) this can happen if this network is unvalidated
5132 // and became unneeded due to another network improving its score to the
5133 // point where this network will no longer be able to satisfy any requests
5134 // even if it validates.
5135 updateLingerState(nai, now);
5136 } else {
5137 if (DBG) log("Reaping " + nai.name());
5138 teardownUnneededNetwork(nai);
5139 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005140 }
5141 }
5142 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005143 }
5144
Paul Jensen1c7ba022015-06-16 14:27:36 -04005145 /**
5146 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5147 * being disconnected.
5148 * @param changed If only one Network's score or capabilities have been modified since the last
5149 * time this function was called, pass this Network in this argument, otherwise pass
5150 * null.
5151 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5152 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5153 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5154 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5155 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005156 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005157 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005158 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5159 // to avoid the slowness. It is not simply enough to process just "changed", for
5160 // example in the case where "changed"'s score decreases and another network should begin
5161 // satifying a NetworkRequest that "changed" currently satisfies.
5162
5163 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5164 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5165 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005166 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005167 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005168 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005169 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005170 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5171 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5172 // Rematch higher scoring networks first to prevent requests first matching a lower
5173 // scoring network and then a higher scoring network, which could produce multiple
5174 // callbacks and inadvertently unlinger networks.
5175 Arrays.sort(nais);
5176 for (NetworkAgentInfo nai : nais) {
5177 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005178 // Only reap the last time through the loop. Reaping before all rematching
5179 // is complete could incorrectly teardown a network that hasn't yet been
5180 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005181 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005182 : ReapUnvalidatedNetworks.REAP,
5183 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005184 }
5185 }
5186 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005187
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005188 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005189 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005190 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005191 // For now only update icons for default connection.
5192 // TODO: Update WiFi and cellular icons separately. b/17237507
5193 if (!isDefaultNetwork(nai)) return;
5194
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005195 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005196 // Don't repeat publish.
5197 if (newInetCondition == mDefaultInetConditionPublished) return;
5198
5199 mDefaultInetConditionPublished = newInetCondition;
5200 sendInetConditionBroadcast(nai.networkInfo);
5201 }
5202
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005203 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5204 if (mLockdownTracker != null) {
5205 if (nai != null && nai.isVPN()) {
5206 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5207 } else {
5208 mLockdownTracker.onNetworkInfoChanged();
5209 }
5210 }
5211 }
5212
Robert Greenwalt7b816022014-04-18 15:25:25 -07005213 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005214 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005215 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005216 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005217 synchronized (networkAgent) {
5218 oldInfo = networkAgent.networkInfo;
5219 networkAgent.networkInfo = newInfo;
5220 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005221 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005222
5223 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005224 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5225 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5226 notifyIfacesChangedForNetworkStats();
5227 } else if (VDBG) log("ignoring duplicate network state non-change");
5228 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005229 return;
5230 }
5231 if (DBG) {
5232 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5233 (oldInfo == null ? "null" : oldInfo.getState()) +
5234 " to " + state);
5235 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005236
Robin Lee585e2482016-05-01 23:00:00 +01005237 if (!networkAgent.created
5238 && (state == NetworkInfo.State.CONNECTED
5239 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005240
5241 // A network that has just connected has zero requests and is thus a foreground network.
5242 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5243
Robert Greenwalt7b816022014-04-18 15:25:25 -07005244 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005245 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005246 if (networkAgent.isVPN()) {
5247 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005248 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5249 (networkAgent.networkMisc == null ||
5250 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005251 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005252 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005253 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005254 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005255 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005256 loge("Error creating network " + networkAgent.network.netId + ": "
5257 + e.getMessage());
5258 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005259 }
Paul Jenseneec75412014-08-04 12:21:19 -04005260 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005261 }
5262
5263 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5264 networkAgent.everConnected = true;
5265
Robert Greenwalt7b816022014-04-18 15:25:25 -07005266 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005267 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005268
Paul Jensenca8f16a2014-05-09 12:47:55 -04005269 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005270 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005271
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005272 if (networkAgent.isVPN()) {
5273 // Temporarily disable the default proxy (not global).
5274 synchronized (mProxyLock) {
5275 if (!mDefaultProxyDisabled) {
5276 mDefaultProxyDisabled = true;
5277 if (mGlobalProxy == null && mDefaultProxy != null) {
5278 sendProxyBroadcast(null);
5279 }
5280 }
5281 }
5282 // TODO: support proxy per network.
5283 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005284
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005285 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5286 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5287 // capabilities, so it only needs to be done once on initial connect, not every time the
5288 // network's capabilities change. Note that we do this before rematching the network,
5289 // so we could decide to tear it down immediately afterwards. That's fine though - on
5290 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5291 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005292 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005293
Paul Jensen2161a8e2014-09-11 11:00:39 -04005294 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005295 final long now = SystemClock.elapsedRealtime();
5296 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005297
5298 // This has to happen after matching the requests, because callbacks are just requests.
5299 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005300 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005301 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005302 if (networkAgent.isVPN()) {
5303 synchronized (mProxyLock) {
5304 if (mDefaultProxyDisabled) {
5305 mDefaultProxyDisabled = false;
5306 if (mGlobalProxy == null && mDefaultProxy != null) {
5307 sendProxyBroadcast(mDefaultProxy);
5308 }
5309 }
5310 }
5311 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005312 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5313 state == NetworkInfo.State.SUSPENDED) {
5314 // going into or coming out of SUSPEND: rescore and notify
5315 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005316 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005317 }
5318 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5319 ConnectivityManager.CALLBACK_SUSPENDED :
5320 ConnectivityManager.CALLBACK_RESUMED));
5321 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005322 }
5323 }
5324
Robert Greenwaltac96c522014-06-03 16:43:57 -07005325 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005326 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005327 if (score < 0) {
5328 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5329 "). Bumping score to min of 0");
5330 score = 0;
5331 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005332
Paul Jensen2161a8e2014-09-11 11:00:39 -04005333 final int oldScore = nai.getCurrentScore();
5334 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005335
Paul Jensen85cf78e2015-06-25 13:25:07 -04005336 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005337
Paul Jensenc8b9a742014-09-30 15:37:41 -04005338 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005339 }
5340
Erik Klinec75d4fa2017-02-15 19:59:17 +09005341 // Notify only this one new request of the current state. Transfer all the
5342 // current state by calling NetworkCapabilities and LinkProperties callbacks
5343 // so that callers can be guaranteed to have as close to atomicity in state
5344 // transfer as can be supported by this current API.
5345 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005346 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005347 if (nri.mPendingIntent != null) {
5348 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5349 // Attempt no subsequent state pushes where intents are involved.
5350 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005351 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005352
5353 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5354 // Whether a network is currently suspended is also an important
5355 // element of state to be transferred (it would not otherwise be
5356 // delivered by any currently available mechanism).
5357 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5358 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5359 }
5360 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5361 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005362 }
5363
Robert Greenwalt8d482522015-06-24 13:23:42 -07005364 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005365 // The NetworkInfo we actually send out has no bearing on the real
5366 // state of affairs. For example, if the default connection is mobile,
5367 // and a request for HIPRI has just gone away, we need to pretend that
5368 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5369 // the state to DISCONNECTED, even though the network is of type MOBILE
5370 // and is still connected.
5371 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5372 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005373 if (state != DetailedState.DISCONNECTED) {
5374 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005375 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005376 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005377 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005378 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5379 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5380 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5381 if (info.isFailover()) {
5382 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5383 nai.networkInfo.setFailover(false);
5384 }
5385 if (info.getReason() != null) {
5386 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5387 }
5388 if (info.getExtraInfo() != null) {
5389 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5390 }
5391 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005392 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005393 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005394 if (newDefaultAgent != null) {
5395 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5396 newDefaultAgent.networkInfo);
5397 } else {
5398 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5399 }
5400 }
5401 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5402 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005403 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005404 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005405 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005406 }
5407 }
5408 }
5409
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005410 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005411 if (VDBG) {
5412 String notification = ConnectivityManager.getCallbackName(notifyType);
5413 log("notifyType " + notification + " for " + networkAgent.name());
5414 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005415 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5416 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005417 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5418 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005419 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5420 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005421 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005422 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005423 } else {
5424 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5425 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005426 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005427 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005428
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005429 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5430 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5431 }
5432
Jeff Sharkey69736342014-12-08 14:50:12 -08005433 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005434 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5435 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005436 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005437 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005438 try {
5439 mStatsService.forceUpdateIfaces();
5440 } catch (Exception ignored) {
5441 }
5442 }
5443
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005444 @Override
5445 public boolean addVpnAddress(String address, int prefixLength) {
5446 throwIfLockdownEnabled();
5447 int user = UserHandle.getUserId(Binder.getCallingUid());
5448 synchronized (mVpns) {
5449 return mVpns.get(user).addAddress(address, prefixLength);
5450 }
5451 }
5452
5453 @Override
5454 public boolean removeVpnAddress(String address, int prefixLength) {
5455 throwIfLockdownEnabled();
5456 int user = UserHandle.getUserId(Binder.getCallingUid());
5457 synchronized (mVpns) {
5458 return mVpns.get(user).removeAddress(address, prefixLength);
5459 }
5460 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005461
5462 @Override
5463 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5464 throwIfLockdownEnabled();
5465 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005466 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005467 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005468 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005469 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005470 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005471 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005472 }
5473 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005474 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005475
5476 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005477 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005478 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005479 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005480 }
5481
5482 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005483 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5484 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5485 enforceKeepalivePermission();
5486 mKeepaliveTracker.startNattKeepalive(
5487 getNetworkAgentInfoForNetwork(network),
5488 intervalSeconds, messenger, binder,
5489 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5490 }
5491
5492 @Override
5493 public void stopKeepalive(Network network, int slot) {
5494 mHandler.sendMessage(mHandler.obtainMessage(
5495 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5496 }
5497
5498 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005499 public void factoryReset() {
5500 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005501
5502 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5503 return;
5504 }
5505
Robin Lee3b3dd942015-05-12 18:14:58 +01005506 final int userId = UserHandle.getCallingUserId();
5507
Stuart Scottf1fb3972015-04-02 18:00:02 -07005508 // Turn airplane mode off
5509 setAirplaneMode(false);
5510
Stuart Scotte3e314d2015-04-20 14:07:45 -07005511 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5512 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005513 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005514 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005515 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005516 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005517 }
5518
Stuart Scotte3e314d2015-04-20 14:07:45 -07005519 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005520 // Remove always-on package
5521 synchronized (mVpns) {
5522 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5523 if (alwaysOnPackage != null) {
5524 setAlwaysOnVpnPackage(userId, null, false);
5525 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5526 }
5527 }
5528
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005529 // Turn Always-on VPN off
5530 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5531 final long ident = Binder.clearCallingIdentity();
5532 try {
5533 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5534 mLockdownEnabled = false;
5535 setLockdownTracker(null);
5536 } finally {
5537 Binder.restoreCallingIdentity(ident);
5538 }
5539 }
5540
Stuart Scotte3e314d2015-04-20 14:07:45 -07005541 // Turn VPN off
5542 VpnConfig vpnConfig = getVpnConfig(userId);
5543 if (vpnConfig != null) {
5544 if (vpnConfig.legacy) {
5545 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5546 } else {
5547 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5548 // in the future without user intervention.
5549 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005550
Victor Changb04a5ea2016-05-30 20:36:30 +01005551 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005552 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005553 }
5554 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005555
5556 Settings.Global.putString(mContext.getContentResolver(),
5557 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005558 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005559
5560 @VisibleForTesting
5561 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5562 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5563 return new NetworkMonitor(context, handler, nai, defaultRequest);
5564 }
Erik Kline48f12f22016-04-14 17:30:59 +09005565
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005566 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005567 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5568 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005569 }
5570
5571 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005572 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5573 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5574 }
5575
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005576 @VisibleForTesting
5577 public boolean hasService(String name) {
5578 return ServiceManager.checkService(name) != null;
5579 }
5580
Hugo Benichi64901e52017-10-19 14:42:40 +09005581 @VisibleForTesting
5582 protected IpConnectivityMetrics.Logger metricsLogger() {
5583 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5584 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005585 }
5586
5587 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5588 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005589 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005590
5591 private static boolean toBool(int encodedBoolean) {
5592 return encodedBoolean != 0; // Only 0 means false.
5593 }
5594
5595 private static int encodeBool(boolean b) {
5596 return b ? 1 : 0;
5597 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005598}