blob: 3bfa31a80b9d47667ad5b2930587e1832738ee1c [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +090022import static android.net.ConnectivityManager.TYPE_ETHERNET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070023import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070024import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070025import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070026import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040027import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090029import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060032import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING;
Chalard Jeandda156a2018-01-10 21:19:32 +090033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060035import static android.net.NetworkCapabilities.TRANSPORT_VPN;
36
Hugo Benichia0385682017-03-22 17:07:57 +090037import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060038
Wenchao Tongf5ea3402015-03-04 13:26:38 -080039import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080040import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090041import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070042import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.ContentResolver;
45import android.content.Context;
46import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070047import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070048import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070049import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090051import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070053import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070054import android.net.INetworkPolicyListener;
55import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070056import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080057import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070058import android.net.LinkProperties.CompareResult;
Charles He36738632017-05-15 17:07:18 +010059import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070060import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070061import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070062import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070063import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080064import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070065import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070066import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090067import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070068import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070069import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070070import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070071import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070072import android.net.NetworkUtils;
Ricky Wai44dcbde2018-01-23 04:09:45 +000073import android.net.NetworkWatchlistManager;
Robert Greenwalt434203a2010-10-11 16:00:27 -070074import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040075import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070076import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040077import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040078import android.net.Uri;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060079import android.net.VpnService;
Hugo Benichicfddd682016-05-31 16:28:06 +090080import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090081import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090082import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080084import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070085import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040086import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070088import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070090import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.Looper;
92import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070093import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070094import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090095import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070096import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070097import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080099import android.os.ResultReceiver;
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900100import android.os.ServiceManager;
Hugo Benichicb883232017-05-11 13:16:17 +0900101import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900102import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -0700103import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400104import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700106import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700107import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700108import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700109import android.text.TextUtils;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900110import android.util.ArraySet;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700111import android.util.LocalLog;
112import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600113import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800114import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700115import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500116import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700117import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700118import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800119
Wink Savilleab9321d2013-06-29 21:10:57 -0700120import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400121import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400122import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700123import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700124import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700125import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700126import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800127import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700128import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700129import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600130import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700131import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900132import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900133import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700134import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700135import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400136import com.android.server.connectivity.DataConnectionStats;
Erik Kline1742fe12017-12-13 19:40:49 +0900137import com.android.server.connectivity.DnsManager;
Erik Klinea24d4592018-01-11 21:07:29 +0900138import com.android.server.connectivity.DnsManager.PrivateDnsConfig;
Hugo Benichi64901e52017-10-19 14:42:40 +0900139import com.android.server.connectivity.IpConnectivityMetrics;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900140import com.android.server.connectivity.KeepaliveTracker;
Charles He36738632017-05-15 17:07:18 +0100141import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700142import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900143import com.android.server.connectivity.MultipathPolicyTracker;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700144import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600145import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400146import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900147import com.android.server.connectivity.NetworkNotificationManager;
148import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400149import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700150import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800151import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700152import com.android.server.connectivity.Vpn;
Charles He36738632017-05-15 17:07:18 +0100153import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700154import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700155import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900156import com.android.server.net.NetworkPolicyManagerInternal;
Vishnu Nair5c010902017-10-26 10:08:50 -0700157import com.android.server.utils.PriorityDump;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600158
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700159import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700160
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700161import org.xmlpull.v1.XmlPullParser;
162import org.xmlpull.v1.XmlPullParserException;
163
164import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800165import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700166import java.io.FileNotFoundException;
167import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700168import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700170import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700171import java.net.InetAddress;
172import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700173import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700174import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700175import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700176import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700177import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700178import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700179import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700180import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700181import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900182import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600183import java.util.SortedSet;
184import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800185
186/**
187 * @hide
188 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800189public class ConnectivityService extends IConnectivityManager.Stub
190 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900191 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192
Erik Kline7747fd42017-05-12 16:52:48 +0900193 public static final String DIAG_ARG = "--diag";
194 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900195 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900196
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900197 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700198 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
Jake Hamby786e71a2014-02-06 14:43:50 -0800200 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900201 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700202
Jeff Sharkey899223b2012-08-04 15:24:58 -0700203 // TODO: create better separation between radio types and network types
204
Robert Greenwalt42acef32009-08-12 16:08:25 -0700205 // how long to wait before switching back to a radio's default network
206 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
207 // system property that can override the above value
208 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
209 "android.telephony.apn-restore";
210
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900211 // How long to wait before putting up a "This network doesn't have an Internet connection,
212 // connect anyway?" dialog after the user selects a network that doesn't validate.
213 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
214
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900215 // Default to 30s linger time-out. Modifiable only for testing.
216 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
217 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
218 @VisibleForTesting
219 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
220
Jeremy Joslin79294842014-12-03 17:15:28 -0800221 // How long to delay to removal of a pending intent based request.
222 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
223 private final int mReleasePendingIntentDelayMs;
224
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900225 private MockableSystemProperties mSystemProperties;
226
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800227 private Tethering mTethering;
228
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700229 private final PermissionMonitor mPermissionMonitor;
230
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700231 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700232
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700233 @GuardedBy("mVpns")
234 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700235
Hugo Benichi69744342017-11-27 10:57:16 +0900236 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
237 // a direct call to LockdownVpnTracker.isEnabled().
238 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700239 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900240 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700241 private LockdownVpnTracker mLockdownTracker;
242
Erik Klineda4bfa82015-04-30 12:58:40 +0900243 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800244 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700245 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700246 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800247
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700249 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800250
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700251 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800252 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700253 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900254 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700255
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700256 private String mCurrentTcpBufferSizes;
257
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700258 private static final int ENABLED = 1;
259 private static final int DISABLED = 0;
260
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900261 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900262 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
263 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900264
Paul Jensenb10e37f2014-11-25 12:33:08 -0500265 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400266 // Tear down networks that have no chance (e.g. even if validated) of becoming
267 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500268 // all networks have been rematched against all NetworkRequests.
269 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400270 // Don't reap networks. This should be passed when some networks have not yet been
271 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500272 DONT_REAP
273 };
274
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900275 private enum UnneededFor {
276 LINGER, // Determine whether this network is unneeded and should be lingered.
277 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
278 }
279
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700280 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700281 * used internally to change our mobile data enabled flag
282 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700283 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700284
285 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700286 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700287 * from one net to another. Clear happens when we get a new
288 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
289 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700290 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700291 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700292
Robert Greenwalt434203a2010-10-11 16:00:27 -0700293 /**
294 * used internally to reload global proxy settings
295 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700296 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700297
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700298 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400299 * PAC manager has received new port.
300 */
301 private static final int EVENT_PROXY_HAS_CHANGED = 16;
302
Robert Greenwalte049c232014-04-11 15:53:27 -0700303 /**
304 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700305 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700306 */
307 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
308
Robert Greenwalt7b816022014-04-18 15:25:25 -0700309 /**
310 * used internally when registering NetworkAgents
311 * obj = Messenger
312 */
313 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
314
Robert Greenwalt9258c642014-03-26 16:47:06 -0700315 /**
316 * used to add a network request
317 * includes a NetworkRequestInfo
318 */
319 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
320
321 /**
322 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900323 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700324 * cancel it.
325 * includes a NetworkRequestInfo
326 */
327 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
328
329 /**
330 * used to add a network listener - no request
331 * includes a NetworkRequestInfo
332 */
333 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
334
335 /**
336 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400337 * arg1 = UID of caller
338 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700339 */
340 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
341
Robert Greenwalta67be032014-05-16 15:49:14 -0700342 /**
343 * used internally when registering NetworkFactories
344 * obj = Messenger
345 */
346 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
347
Robert Greenwalt27711812014-06-25 16:45:57 -0700348 /**
349 * used internally to expire a wakelock when transitioning
350 * from one net to another. Expire happens when we fail to find
351 * a new network (typically after 1 minute) -
352 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
353 * a replacement network.
354 */
355 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
356
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700357 /**
358 * Used internally to indicate the system is ready.
359 */
360 private static final int EVENT_SYSTEM_READY = 25;
361
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800362 /**
363 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400364 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800365 */
366 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
367
368 /**
369 * used to remove a pending intent and its associated network request.
370 * arg1 = UID of caller
371 * obj = PendingIntent
372 */
373 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
374
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900375 /**
376 * used to specify whether a network should be used even if unvalidated.
377 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
378 * arg2 = whether to remember this choice in the future (1 or 0)
379 * obj = network
380 */
381 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
382
383 /**
384 * used to ask the user to confirm a connection to an unvalidated network.
385 * obj = network
386 */
387 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700388
Erik Klineda4bfa82015-04-30 12:58:40 +0900389 /**
390 * used internally to (re)configure mobile data always-on settings.
391 */
392 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
393
Paul Jensen694f2b82015-06-17 14:15:39 -0400394 /**
395 * used to add a network listener with a pending intent
396 * obj = NetworkRequestInfo
397 */
398 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
399
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900400 /**
401 * used to specify whether a network should not be penalized when it becomes unvalidated.
402 */
403 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
404
405 /**
406 * used to trigger revalidation of a network.
407 */
408 private static final int EVENT_REVALIDATE_NETWORK = 36;
409
Erik Klinea24d4592018-01-11 21:07:29 +0900410 // Handle changes in Private DNS settings.
411 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
412
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900413 private static String eventName(int what) {
414 return sMagicDecoderRing.get(what, Integer.toString(what));
415 }
416
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900417 /** Handler thread used for both of the handlers below. */
418 @VisibleForTesting
419 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700420 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700421 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700422 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700423 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900424 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700425
Mike Lockwood0f79b542009-08-14 14:18:49 -0400426 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800427 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400428
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700429 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700430 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800431 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700432
Robert Greenwalt434203a2010-10-11 16:00:27 -0700433 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400434 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700435 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700436 private boolean mDefaultProxyDisabled = false;
437
Robert Greenwalt434203a2010-10-11 16:00:27 -0700438 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400439 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700440
Jason Monk602b2322013-07-03 17:04:33 -0400441 private PacManager mPacManager = null;
442
Erik Klineda4bfa82015-04-30 12:58:40 +0900443 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700444
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400445 private UserManager mUserManager;
446
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700447 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700448 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700449
Robert Greenwalt50393202011-06-21 17:26:14 -0700450 // the set of network types that can only be enabled by system/sig apps
451 List mProtectedNetworks;
452
John Spurlockbf991a82013-06-24 14:20:23 -0400453 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700454
Wink Savilleab9321d2013-06-29 21:10:57 -0700455 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400456
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900457 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900458 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900459 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900460
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700461 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800462 private static final int MIN_NET_ID = 100; // some reserved marks
463 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700464 private int mNextNetId = MIN_NET_ID;
465
Robert Greenwalt34524f02014-05-18 16:22:10 -0700466 // sequence number of NetworkRequests
467 private int mNextNetworkRequestId = 1;
468
Erik Kline7523eb32015-07-09 18:24:03 +0900469 // NetworkRequest activity String log entries.
470 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
471 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
472
Hugo Benichic2ae2872016-07-11 11:05:12 +0900473 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900474 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900475 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
476
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900477 private static final int MAX_WAKELOCK_LOGS = 20;
478 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichi26bcfa12017-09-05 13:25:07 +0900479 private int mTotalWakelockAcquisitions = 0;
480 private int mTotalWakelockReleases = 0;
481 private long mTotalWakelockDurationMs = 0;
482 private long mMaxWakelockDurationMs = 0;
483 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900484
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700485 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
486 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400487 private static class ValidationLog {
488 final Network mNetwork;
489 final String mNetworkExtraInfo;
490 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700491
Paul Jensen0808eb82016-06-03 13:51:21 -0400492 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
493 mNetwork = network;
494 mNetworkExtraInfo = networkExtraInfo;
495 mLog = log;
496 }
497 }
498 private final ArrayDeque<ValidationLog> mValidationLogs =
499 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
500
501 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900502 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700503 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
504 mValidationLogs.removeLast();
505 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400506 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700507 }
508 }
509
Hugo Benichif9fdf872016-07-28 17:53:06 +0900510 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900511
Erik Kline065ab6e2016-10-02 18:02:14 +0900512 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900513 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900514
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900515 @VisibleForTesting
516 final MultipathPolicyTracker mMultipathPolicyTracker;
517
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700518 /**
519 * Implements support for the legacy "one network per network type" model.
520 *
521 * We used to have a static array of NetworkStateTrackers, one for each
522 * network type, but that doesn't work any more now that we can have,
523 * for example, more that one wifi network. This class stores all the
524 * NetworkAgentInfo objects that support a given type, but the legacy
525 * API will only see the first one.
526 *
527 * It serves two main purposes:
528 *
529 * 1. Provide information about "the network for a given type" (since this
530 * API only supports one).
531 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
532 * the first network for a given type changes, or if the default network
533 * changes.
534 */
535 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900537 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900538 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900539
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700540 /**
541 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
542 * Each list holds references to all NetworkAgentInfos that are used to
543 * satisfy requests for that network type.
544 *
545 * This array is built out at startup such that an unsupported network
546 * doesn't get an ArrayList instance, making this a tristate:
547 * unsupported, supported but not active and active.
548 *
549 * The actual lists are populated when we scan the network types that
550 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900551 *
552 * Threading model:
553 * - addSupportedType() is only called in the constructor
554 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
555 * They are therefore not thread-safe with respect to each other.
556 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
557 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
558 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900560 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561
562 public LegacyTypeTracker() {
563 mTypeLists = (ArrayList<NetworkAgentInfo>[])
564 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
565 }
566
567 public void addSupportedType(int type) {
568 if (mTypeLists[type] != null) {
569 throw new IllegalStateException(
570 "legacy list for type " + type + "already initialized");
571 }
572 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
573 }
574
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700575 public boolean isTypeSupported(int type) {
576 return isNetworkTypeValid(type) && mTypeLists[type] != null;
577 }
578
579 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900580 synchronized (mTypeLists) {
581 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
582 return mTypeLists[type].get(0);
583 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900585 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700586 }
587
Robert Greenwalt8d482522015-06-24 13:23:42 -0700588 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900589 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900590 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700591 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900593 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594 }
595 }
596
597 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 public void add(int type, NetworkAgentInfo nai) {
599 if (!isTypeSupported(type)) {
600 return; // Invalid network type.
601 }
602 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
603
604 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
605 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700606 return;
607 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900608 synchronized (mTypeLists) {
609 list.add(nai);
610 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900611
612 // 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 +0900613 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900614 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700615 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
616 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700617 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700618 }
619
Lorenzo Colittia793a672014-07-31 23:20:17 +0900620 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
623 if (list == null || list.isEmpty()) {
624 return;
625 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900626 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900627
Hugo Benichi78caa2582016-06-21 09:48:07 +0900628 synchronized (mTypeLists) {
629 if (!list.remove(nai)) {
630 return;
631 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900632 }
633
Robert Greenwalt8d482522015-06-24 13:23:42 -0700634 final DetailedState state = DetailedState.DISCONNECTED;
635
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900636 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700637 maybeLogBroadcast(nai, state, type, wasDefault);
638 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900639 }
640
641 if (!list.isEmpty() && wasFirstNetwork) {
642 if (DBG) log("Other network available for type " + type +
643 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900644 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700645 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
646 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900647 }
648 }
649
650 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900651 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
652 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700653 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900654 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700655 }
656 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700657
Robert Greenwalt8d482522015-06-24 13:23:42 -0700658 // send out another legacy broadcast - currently only used for suspend/unsuspend
659 // toggle
660 public void update(NetworkAgentInfo nai) {
661 final boolean isDefault = isDefaultNetwork(nai);
662 final DetailedState state = nai.networkInfo.getDetailedState();
663 for (int type = 0; type < mTypeLists.length; type++) {
664 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700665 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900666 final boolean isFirst = contains && (nai == list.get(0));
667 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700668 maybeLogBroadcast(nai, state, type, isDefault);
669 sendLegacyNetworkBroadcast(nai, state, type);
670 }
671 }
672 }
673
Lorenzo Colittia793a672014-07-31 23:20:17 +0900674 private String naiToString(NetworkAgentInfo nai) {
675 String name = (nai != null) ? nai.name() : "null";
676 String state = (nai.networkInfo != null) ?
677 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
678 "???/???";
679 return name + " " + state;
680 }
681
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700682 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900683 pw.println("mLegacyTypeTracker:");
684 pw.increaseIndent();
685 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700686 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900687 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700688 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900689 pw.println();
690 pw.println("Current state:");
691 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900692 synchronized (mTypeLists) {
693 for (int type = 0; type < mTypeLists.length; type++) {
694 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
695 for (NetworkAgentInfo nai : mTypeLists[type]) {
696 pw.println(type + " " + naiToString(nai));
697 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900698 }
699 }
700 pw.decreaseIndent();
701 pw.decreaseIndent();
702 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700703 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700704 }
705 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
706
Vishnu Nair5c010902017-10-26 10:08:50 -0700707 /**
708 * Helper class which parses out priority arguments and dumps sections according to their
709 * priority. If priority arguments are omitted, function calls the legacy dump command.
710 */
711 private final PriorityDump.PriorityDumper mPriorityDumper = new PriorityDump.PriorityDumper() {
712 @Override
713 public void dumpHigh(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
714 doDump(fd, pw, new String[] {DIAG_ARG}, asProto);
715 doDump(fd, pw, new String[] {SHORT_ARG}, asProto);
716 }
717
718 @Override
719 public void dumpNormal(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
720 doDump(fd, pw, args, asProto);
721 }
722
723 @Override
724 public void dump(FileDescriptor fd, PrintWriter pw, String[] args, boolean asProto) {
725 doDump(fd, pw, args, asProto);
726 }
727 };
728
Jeff Sharkey899223b2012-08-04 15:24:58 -0700729 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700730 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900731 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
732 }
733
734 @VisibleForTesting
735 protected ConnectivityService(Context context, INetworkManagementService netManager,
736 INetworkStatsService statsService, INetworkPolicyManager policyManager,
737 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800738 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800739
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900740 mSystemProperties = getSystemProperties();
741
Hugo Benichif9fdf872016-07-28 17:53:06 +0900742 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900743 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900744 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900745 mNetworkRequests.put(mDefaultRequest, defaultNRI);
746 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900747
Chalard Jeandda156a2018-01-10 21:19:32 +0900748 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900749 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700750
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900751 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900752 mHandlerThread.start();
753 mHandler = new InternalHandler(mHandlerThread.getLooper());
754 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700755
Jeremy Joslin79294842014-12-03 17:15:28 -0800756 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
757 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
758
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900759 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900760
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700761 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700762 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800763 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700764 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900765 mPolicyManagerInternal = checkNotNull(
766 LocalServices.getService(NetworkPolicyManagerInternal.class),
767 "missing NetworkPolicyManagerInternal");
768
Jeff Sharkey82f85212012-08-24 11:17:25 -0700769 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700770 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700771
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700772 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900773 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700774 } catch (RemoteException e) {
775 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700776 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700777 }
778
779 final PowerManager powerManager = (PowerManager) context.getSystemService(
780 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700781 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
782 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
783 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800784 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700785
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700786 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700787
Wink Saville51f456f2013-04-23 14:26:51 -0700788 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900789 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700790 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700791 String[] naStrings = context.getResources().getStringArray(
792 com.android.internal.R.array.networkAttributes);
793 for (String naString : naStrings) {
794 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700795 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700796 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700797 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800798 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700799 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700800 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700801 }
Wink Saville51f456f2013-04-23 14:26:51 -0700802 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
803 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
804 n.type);
805 continue;
806 }
Wink Saville975c8482011-04-07 14:23:45 -0700807 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800808 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700809 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700810 continue;
811 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700812 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700813
Wink Saville975c8482011-04-07 14:23:45 -0700814 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700815 mNetworksDefined++;
816 } catch(Exception e) {
817 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700818 }
819 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700820
821 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
822 if (mNetConfigs[TYPE_VPN] == null) {
823 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
824 // don't need to add TYPE_VPN to mNetConfigs.
825 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
826 mNetworksDefined++; // used only in the log() statement below.
827 }
828
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900829 // Do the same for Ethernet, since it's often not specified in the configs, although many
830 // devices can use it via USB host adapters.
831 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
832 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
833 mNetworksDefined++;
834 }
835
Wink Saville5e56bc52013-07-29 15:00:57 -0700836 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700837
Robert Greenwalt50393202011-06-21 17:26:14 -0700838 mProtectedNetworks = new ArrayList<Integer>();
839 int[] protectedNetworks = context.getResources().getIntArray(
840 com.android.internal.R.array.config_protectedNetworks);
841 for (int p : protectedNetworks) {
842 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
843 mProtectedNetworks.add(p);
844 } else {
845 if (DBG) loge("Ignoring protectedNetwork " + p);
846 }
847 }
848
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900849 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
850 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700851
Erik Kline47222fc2017-04-30 19:36:15 +0900852 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800853
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700854 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
855
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700856 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700857 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100858 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700859 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700860 intentFilter.addAction(Intent.ACTION_USER_ADDED);
861 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000862 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700863 mContext.registerReceiverAsUser(
864 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000865 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
866 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900867
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700868 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700869 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700870 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700871 } catch (RemoteException e) {
872 loge("Error registering observer :" + e);
873 }
874
Erik Klineda4bfa82015-04-30 12:58:40 +0900875 mSettingsObserver = new SettingsObserver(mContext, mHandler);
876 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800877
John Spurlockbf991a82013-06-24 14:20:23 -0400878 mDataConnectionStats = new DataConnectionStats(mContext);
879 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400880
Jason Monkdecd2952013-10-10 14:02:51 -0400881 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700882
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400883 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900884
885 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900886 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
887 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900888
889 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
890 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
891 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
892 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
893 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
894 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
895 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900896
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900897 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900898 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900899 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900900
Lorenzo Colittid260ef22018-01-24 17:35:07 +0900901 mMultipathPolicyTracker = new MultipathPolicyTracker(mContext, mHandler);
902
Erik Kline1742fe12017-12-13 19:40:49 +0900903 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900904 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800905 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700906
Erik Kline47222fc2017-04-30 19:36:15 +0900907 private Tethering makeTethering() {
908 // TODO: Move other elements into @Overridden getters.
909 final TetheringDependencies deps = new TetheringDependencies();
910 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
911 IoThread.get().getLooper(), new MockableSystemProperties(),
912 deps);
913 }
914
Chalard Jeandda156a2018-01-10 21:19:32 +0900915 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900916 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900917 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900918 netCap.addCapability(NET_CAPABILITY_INTERNET);
919 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900920 if (transportType > -1) {
921 netCap.addTransportType(transportType);
922 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900923 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900924 }
925
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900926 // Used only for testing.
927 // TODO: Delete this and either:
928 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
929 // changing ContentResolver to make registerContentObserver non-final).
930 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
931 // by subclassing SettingsObserver.
932 @VisibleForTesting
933 void updateMobileDataAlwaysOn() {
934 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
935 }
936
Erik Klineda4bfa82015-04-30 12:58:40 +0900937 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900938 final boolean enable = toBool(Settings.Global.getInt(
939 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900940 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
941 if (enable == isEnabled) {
942 return; // Nothing to do.
943 }
944
945 if (enable) {
946 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900947 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900948 } else {
949 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
950 }
951 }
952
953 private void registerSettingsCallbacks() {
954 // Watch for global HTTP proxy changes.
955 mSettingsObserver.observe(
956 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
957 EVENT_APPLY_GLOBAL_HTTP_PROXY);
958
959 // Watch for whether or not to keep mobile data always on.
960 mSettingsObserver.observe(
961 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
962 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
963 }
964
Erik Klinea24d4592018-01-11 21:07:29 +0900965 private void registerPrivateDnsSettingsCallbacks() {
966 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
967 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
968 }
969 }
970
Robert Greenwalt34524f02014-05-18 16:22:10 -0700971 private synchronized int nextNetworkRequestId() {
972 return mNextNetworkRequestId++;
973 }
974
Paul Jensen67b0b072015-06-10 11:22:17 -0400975 @VisibleForTesting
976 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400977 synchronized (mNetworkForNetId) {
978 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
979 int netId = mNextNetId;
980 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
981 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500982 if (!mNetIdInUse.get(netId)) {
983 mNetIdInUse.put(netId, true);
984 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400985 }
986 }
987 }
988 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700989 }
990
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600991 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800992 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600993 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
994 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800995 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600996 state = nai.getNetworkState();
997 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800998 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600999 final NetworkInfo info = new NetworkInfo(networkType, 0,
1000 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001001 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
1002 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -07001003 final NetworkCapabilities capabilities = new NetworkCapabilities();
1004 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
1005 !info.isRoaming());
1006 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001007 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001008 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001009 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001010 return state;
1011 } else {
1012 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001013 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001014 }
1015
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001016 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
1017 if (network == null) {
1018 return null;
1019 }
1020 synchronized (mNetworkForNetId) {
1021 return mNetworkForNetId.get(network.netId);
1022 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001023 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001024
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001025 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +09001026 synchronized (mVpns) {
1027 if (!mLockdownEnabled) {
1028 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001029 Vpn vpn = mVpns.get(user);
1030 if (vpn != null && vpn.appliesToUid(uid)) {
1031 return vpn.getUnderlyingNetworks();
1032 }
1033 }
1034 }
1035 return null;
1036 }
1037
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001038 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001039 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001040
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001041 final Network[] networks = getVpnUnderlyingNetworks(uid);
1042 if (networks != null) {
1043 // getUnderlyingNetworks() returns:
1044 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1045 // empty array => the VPN explicitly said "no default network".
1046 // non-empty array => the VPN specified one or more default networks; we use the
1047 // first one.
1048 if (networks.length > 0) {
1049 nai = getNetworkAgentInfoForNetwork(networks[0]);
1050 } else {
1051 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001052 }
1053 }
1054
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001055 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001056 return nai.getNetworkState();
1057 } else {
1058 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001059 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001060 }
1061
1062 /**
1063 * Check if UID should be blocked from using the network with the given LinkProperties.
1064 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001065 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1066 boolean ignoreBlocked) {
1067 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001068 if (ignoreBlocked) {
1069 return false;
1070 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001071 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001072 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1073 if (isSystem(uid)) {
1074 return false;
1075 }
Robin Lee17e61832016-05-09 13:46:28 +01001076 synchronized (mVpns) {
1077 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1078 if (vpn != null && vpn.isBlockingUid(uid)) {
1079 return true;
1080 }
1081 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001082 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001083 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001084 }
1085
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001086 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001087 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1088 return;
1089 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001090 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001091 synchronized (mBlockedAppUids) {
1092 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001093 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001094 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001095 blocked = false;
1096 } else {
1097 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001098 }
1099 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001100 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1101 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1102 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001103 }
1104
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001105 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001106 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1107 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001108 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001109 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001110 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001111 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1112
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001113 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001114 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001115 }
Hugo Benichi69744342017-11-27 10:57:16 +09001116 synchronized (mVpns) {
1117 if (mLockdownTracker != null) {
1118 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1119 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001120 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001121 }
1122
1123 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001124 * Return NetworkInfo for the active (i.e., connected) network interface.
1125 * It is assumed that at most one network is active at a time. If more
1126 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001127 * @return the info for the active network, or {@code null} if none is
1128 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001130 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001131 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 enforceAccessPermission();
1133 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001134 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001135 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001136 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1137 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001138 }
1139
Paul Jensen31a94f42015-02-13 14:18:39 -05001140 @Override
1141 public Network getActiveNetwork() {
1142 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001143 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001144 }
1145
1146 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001147 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001148 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001149 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001150 }
1151
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001152 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001153 final int user = UserHandle.getUserId(uid);
1154 int vpnNetId = NETID_UNSET;
1155 synchronized (mVpns) {
1156 final Vpn vpn = mVpns.get(user);
1157 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1158 }
1159 NetworkAgentInfo nai;
1160 if (vpnNetId != NETID_UNSET) {
1161 synchronized (mNetworkForNetId) {
1162 nai = mNetworkForNetId.get(vpnNetId);
1163 }
1164 if (nai != null) return nai.network;
1165 }
1166 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001167 if (nai != null
1168 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1169 nai = null;
1170 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001171 return nai != null ? nai.network : null;
1172 }
1173
Lorenzo Colitti18660282016-07-04 12:55:44 +09001174 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001175 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1176 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001177 final int uid = Binder.getCallingUid();
1178 NetworkState state = getUnfilteredActiveNetworkState(uid);
1179 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001180 }
1181
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001182 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001183 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001184 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001185 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001186 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001187 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001188 }
1189
1190 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001191 public NetworkInfo getNetworkInfo(int networkType) {
1192 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001193 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001194 if (getVpnUnderlyingNetworks(uid) != null) {
1195 // A VPN is active, so we may need to return one of its underlying networks. This
1196 // information is not available in LegacyTypeTracker, so we have to get it from
1197 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001198 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001199 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001200 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001201 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001202 }
1203 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001204 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001205 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001206 }
1207
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001208 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001209 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001211 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001213 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001214 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001215 return state.networkInfo;
1216 } else {
1217 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001218 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001219 }
1220
1221 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001222 public NetworkInfo[] getAllNetworkInfo() {
1223 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001224 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001225 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1226 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001227 NetworkInfo info = getNetworkInfo(networkType);
1228 if (info != null) {
1229 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001230 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001231 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001232 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 }
1234
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001235 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001236 public Network getNetworkForType(int networkType) {
1237 enforceAccessPermission();
1238 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001239 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1240 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001241 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001242 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001244 }
1245
1246 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001247 public Network[] getAllNetworks() {
1248 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001249 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001250 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001251 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001252 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001253 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001254 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001255 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001256 }
1257
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001258 @Override
1259 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1260 // The basic principle is: if an app's traffic could possibly go over a
1261 // network, without the app doing anything multinetwork-specific,
1262 // (hence, by "default"), then include that network's capabilities in
1263 // the array.
1264 //
1265 // In the normal case, app traffic only goes over the system's default
1266 // network connection, so that's the only network returned.
1267 //
1268 // With a VPN in force, some app traffic may go into the VPN, and thus
1269 // over whatever underlying networks the VPN specifies, while other app
1270 // traffic may go over the system default network (e.g.: a split-tunnel
1271 // VPN, or an app disallowed by the VPN), so the set of networks
1272 // returned includes the VPN's underlying networks and the system
1273 // default.
1274 enforceAccessPermission();
1275
1276 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1277
1278 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001279 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001280 if (nc != null) {
1281 result.put(nai.network, nc);
1282 }
1283
Hugo Benichi69744342017-11-27 10:57:16 +09001284 synchronized (mVpns) {
1285 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001286 Vpn vpn = mVpns.get(userId);
1287 if (vpn != null) {
1288 Network[] networks = vpn.getUnderlyingNetworks();
1289 if (networks != null) {
1290 for (Network network : networks) {
1291 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001292 nc = getNetworkCapabilitiesInternal(nai);
Chalard Jeandda156a2018-01-10 21:19:32 +09001293 // nc is a copy of the capabilities in nai, so it's fine to mutate it
1294 // TODO : don't remove the UIDs when communicating with processes
1295 // that have the NETWORK_SETTINGS permission.
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001296 if (nc != null) {
Chalard Jeandda156a2018-01-10 21:19:32 +09001297 nc.setSingleUid(userId);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001298 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001299 }
1300 }
1301 }
1302 }
1303 }
1304 }
1305
1306 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1307 out = result.values().toArray(out);
1308 return out;
1309 }
1310
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001311 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001312 public boolean isNetworkSupported(int networkType) {
1313 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001314 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001315 }
1316
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001317 /**
1318 * Return LinkProperties for the active (i.e., connected) default
1319 * network interface. It is assumed that at most one default network
1320 * is active at a time. If more than one is active, it is indeterminate
1321 * which will be returned.
1322 * @return the ip properties for the active network, or {@code null} if
1323 * none is active
1324 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001325 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001326 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001327 enforceAccessPermission();
1328 final int uid = Binder.getCallingUid();
1329 NetworkState state = getUnfilteredActiveNetworkState(uid);
1330 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001331 }
1332
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001333 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001334 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001335 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001336 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1337 if (nai != null) {
1338 synchronized (nai) {
1339 return new LinkProperties(nai.linkProperties);
1340 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001341 }
1342 return null;
1343 }
1344
Robert Greenwalt12e67352014-05-13 21:41:06 -07001345 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001346 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001347 public LinkProperties getLinkProperties(Network network) {
1348 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001349 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1350 }
1351
1352 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1353 if (nai == null) {
1354 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001355 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001356 synchronized (nai) {
1357 return new LinkProperties(nai.linkProperties);
1358 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001359 }
1360
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001361 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001362 if (nai != null) {
1363 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001364 if (nai.networkCapabilities != null) {
1365 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001366 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001367 }
1368 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001369 return null;
1370 }
1371
1372 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001373 public NetworkCapabilities getNetworkCapabilities(Network network) {
1374 enforceAccessPermission();
1375 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1376 }
1377
1378 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001379 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001380 // Require internal since we're handing out IMSI details
1381 enforceConnectivityInternalPermission();
1382
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001383 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001384 for (Network network : getAllNetworks()) {
1385 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1386 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001387 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001388 }
1389 }
1390 return result.toArray(new NetworkState[result.size()]);
1391 }
1392
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001393 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001394 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001395 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001396 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1397 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1398 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001399 }
1400
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001401 @Override
1402 public boolean isActiveNetworkMetered() {
1403 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001404
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001405 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1406 if (caps != null) {
1407 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1408 } else {
1409 // Always return the most conservative value
1410 return true;
1411 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001412 }
1413
Jeff Sharkey216c1812012-08-05 14:29:23 -07001414 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1415 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001416 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001417 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001418 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001419 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001420 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001421
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001422 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 * Ensure that a network route exists to deliver traffic to the specified
1424 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001425 * @param networkType the type of the network over which traffic to the
1426 * specified host is to be routed
1427 * @param hostAddress the IP address of the host to which the route is
1428 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 * @return {@code true} on success, {@code false} on failure
1430 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001431 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001432 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001433 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001434 if (mProtectedNetworks.contains(networkType)) {
1435 enforceConnectivityInternalPermission();
1436 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001437
Chad Brubakerc0234532014-02-14 13:24:29 -08001438 InetAddress addr;
1439 try {
1440 addr = InetAddress.getByAddress(hostAddress);
1441 } catch (UnknownHostException e) {
1442 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1443 return false;
1444 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001445
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001447 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001448 return false;
1449 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001450
1451 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1452 if (nai == null) {
1453 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1454 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1455 } else {
1456 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1457 }
1458 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001459 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001460
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001461 DetailedState netState;
1462 synchronized (nai) {
1463 netState = nai.networkInfo.getDetailedState();
1464 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001465
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001466 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001467 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001468 log("requestRouteToHostAddress on down network "
1469 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001470 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001471 }
1472 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001473 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001474
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001475 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001476 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001477 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001478 LinkProperties lp;
1479 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001480 synchronized (nai) {
1481 lp = nai.linkProperties;
1482 netId = nai.network.netId;
1483 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001484 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001485 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1486 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001487 } finally {
1488 Binder.restoreCallingIdentity(token);
1489 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001490 }
1491
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001492 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001493 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001494 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001495 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001496 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001497 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001498 if (bestRoute.getGateway().equals(addr)) {
1499 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001500 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001501 } else {
1502 // if we will connect to this through another route, add a direct route
1503 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001504 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001505 }
1506 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001507 if (DBG) log("Adding legacy route " + bestRoute +
1508 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001509 try {
1510 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1511 } catch (Exception e) {
1512 // never crash - catch them all
1513 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001514 return false;
1515 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001516 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001517 }
1518
Jeff Sharkey75d31892018-01-18 22:01:59 +09001519 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001520 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001521 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001522 // TODO: notify UID when it has requested targeted updates
1523 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001524 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001525 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001526 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001527 if (restrictBackground) {
1528 log("onRestrictBackgroundChanged(true): disabling tethering");
1529 mTethering.untetherAll();
1530 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001531 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001532 };
1533
Robin Lee3b3dd942015-05-12 18:14:58 +01001534 /**
1535 * Require that the caller is either in the same user or has appropriate permission to interact
1536 * across users.
1537 *
1538 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1539 */
1540 private void enforceCrossUserPermission(int userId) {
1541 if (userId == UserHandle.getCallingUserId()) {
1542 // Not a cross-user call.
1543 return;
1544 }
1545 mContext.enforceCallingOrSelfPermission(
1546 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1547 "ConnectivityService");
1548 }
1549
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001550 private void enforceInternetPermission() {
1551 mContext.enforceCallingOrSelfPermission(
1552 android.Manifest.permission.INTERNET,
1553 "ConnectivityService");
1554 }
1555
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001556 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001557 mContext.enforceCallingOrSelfPermission(
1558 android.Manifest.permission.ACCESS_NETWORK_STATE,
1559 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001560 }
1561
1562 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001563 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001564 }
1565
Charles He36738632017-05-15 17:07:18 +01001566 private void enforceSettingsPermission() {
1567 mContext.enforceCallingOrSelfPermission(
1568 android.Manifest.permission.NETWORK_SETTINGS,
1569 "ConnectivityService");
1570 }
1571
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001572 private void enforceTetherAccessPermission() {
1573 mContext.enforceCallingOrSelfPermission(
1574 android.Manifest.permission.ACCESS_NETWORK_STATE,
1575 "ConnectivityService");
1576 }
1577
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001578 private void enforceConnectivityInternalPermission() {
1579 mContext.enforceCallingOrSelfPermission(
1580 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1581 "ConnectivityService");
1582 }
1583
Hugo Benichi514da602016-07-19 15:59:27 +09001584 private void enforceConnectivityRestrictedNetworksPermission() {
1585 try {
1586 mContext.enforceCallingOrSelfPermission(
1587 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1588 "ConnectivityService");
1589 return;
1590 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1591 enforceConnectivityInternalPermission();
1592 }
1593
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001594 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001595 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001596 }
1597
Lorenzo Colitti18660282016-07-04 12:55:44 +09001598 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001599 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001600 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001601 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001602 }
1603
1604 private void sendInetConditionBroadcast(NetworkInfo info) {
1605 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1606 }
1607
Wink Saville628b0852011-08-04 15:01:58 -07001608 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001609 synchronized (mVpns) {
1610 if (mLockdownTracker != null) {
1611 info = new NetworkInfo(info);
1612 mLockdownTracker.augmentNetworkInfo(info);
1613 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001614 }
1615
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001616 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001617 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001618 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001619 if (info.isFailover()) {
1620 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1621 info.setFailover(false);
1622 }
1623 if (info.getReason() != null) {
1624 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1625 }
1626 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001627 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1628 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001630 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001631 return intent;
1632 }
1633
1634 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1635 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1636 }
1637
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001638 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001639 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1640 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1641 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001642 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001643 final long ident = Binder.clearCallingIdentity();
1644 try {
1645 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1646 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1647 } finally {
1648 Binder.restoreCallingIdentity(ident);
1649 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001650 }
1651
Mike Lockwood0f79b542009-08-14 14:18:49 -04001652 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001653 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001654 if (!mSystemReady) {
1655 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001656 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001657 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001658 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001659 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001660 }
1661
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001662 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001663 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001664 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001665 final NetworkInfo ni = intent.getParcelableExtra(
1666 ConnectivityManager.EXTRA_NETWORK_INFO);
1667 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1668 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1669 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001670 } else {
1671 BroadcastOptions opts = BroadcastOptions.makeBasic();
1672 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1673 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001674 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001675 final IBatteryStats bs = BatteryStatsService.getService();
1676 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001677 bs.noteConnectivityChanged(intent.getIntExtra(
1678 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1679 ni != null ? ni.getState().toString() : "?");
1680 } catch (RemoteException e) {
1681 }
1682 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001683 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001684 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001685 } finally {
1686 Binder.restoreCallingIdentity(ident);
1687 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001688 }
1689 }
1690
1691 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001692 loadGlobalProxy();
1693
Hugo Benichi20035e02017-04-26 14:53:28 +09001694 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001695 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001696 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001697 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001698 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001699 }
1700 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001701 // load the global proxy at startup
1702 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001703
Robin Lee244ce8e2016-01-05 18:03:46 +00001704 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1705 // for user to unlock device too.
1706 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001707
Erik Klineda4bfa82015-04-30 12:58:40 +09001708 // Configure whether mobile data is always on.
1709 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1710
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001711 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001712
1713 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001714 }
1715
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001716 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001717 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001718 *
1719 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001720 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001721 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001722 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1723 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001724
1725 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001726 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001727
Robert Greenwalt7b816022014-04-18 15:25:25 -07001728 if (networkAgent.networkCapabilities.hasTransport(
1729 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001730 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1731 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001732 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001733 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001734 } else if (networkAgent.networkCapabilities.hasTransport(
1735 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001736 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1737 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001738 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001739 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001740 } else {
1741 // do not track any other networks
1742 timeout = 0;
1743 }
1744
Robert Greenwalt7b816022014-04-18 15:25:25 -07001745 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001746 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001747 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001748 } catch (Exception e) {
1749 // You shall not crash!
1750 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001751 }
1752 }
1753 }
1754
1755 /**
1756 * Remove data activity tracking when network disconnects.
1757 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001758 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1759 final String iface = networkAgent.linkProperties.getInterfaceName();
1760 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001761
Robert Greenwalt7b816022014-04-18 15:25:25 -07001762 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1763 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001764 try {
1765 // the call fails silently if no idletimer setup for this interface
1766 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001767 } catch (Exception e) {
1768 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001769 }
1770 }
1771 }
1772
1773 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001774 * Reads the network specific MTU size from reources.
1775 * and set it on it's iface.
1776 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001777 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1778 final String iface = newLp.getInterfaceName();
1779 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001780 if (oldLp == null && mtu == 0) {
1781 // Silently ignore unset MTU value.
1782 return;
1783 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001784 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1785 if (VDBG) log("identical MTU - not setting");
1786 return;
1787 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001788 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001789 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001790 return;
1791 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001792
w1997615afd812014-08-05 15:18:11 -07001793 // Cannot set MTU without interface name
1794 if (TextUtils.isEmpty(iface)) {
1795 loge("Setting MTU size with null iface.");
1796 return;
1797 }
1798
Robert Greenwalt7b816022014-04-18 15:25:25 -07001799 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001800 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001801 mNetd.setMtu(iface, mtu);
1802 } catch (Exception e) {
1803 Slog.e(TAG, "exception in setMtu()" + e);
1804 }
1805 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001806
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001807 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001808 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1809
1810 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001811 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001812 protected MockableSystemProperties getSystemProperties() {
1813 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001814 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001815
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001816 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1817 if (isDefaultNetwork(nai) == false) {
1818 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001819 }
1820
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001821 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1822 String[] values = null;
1823 if (tcpBufferSizes != null) {
1824 values = tcpBufferSizes.split(",");
1825 }
1826
1827 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001828 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001829 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1830 values = tcpBufferSizes.split(",");
1831 }
1832
1833 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1834
1835 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001836 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001837
1838 final String prefix = "/sys/kernel/ipv4/tcp_";
1839 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1840 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1841 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1842 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1843 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1844 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1845 mCurrentTcpBufferSizes = tcpBufferSizes;
1846 } catch (IOException e) {
1847 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001848 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001849
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001850 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001851 Settings.Global.TCP_DEFAULT_INIT_RWND,
1852 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001853 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1854 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001855 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001856 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001857 }
1858
Robert Greenwalt562cc542014-05-15 18:07:26 -07001859 @Override
1860 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001861 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001862 NETWORK_RESTORE_DELAY_PROP_NAME);
1863 if(restoreDefaultNetworkDelayStr != null &&
1864 restoreDefaultNetworkDelayStr.length() != 0) {
1865 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001866 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001867 } catch (NumberFormatException e) {
1868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001869 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001870 // if the system property isn't set, use the value for the apn type
1871 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1872
1873 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1874 (mNetConfigs[networkType] != null)) {
1875 ret = mNetConfigs[networkType].restoreTime;
1876 }
1877 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001878 }
1879
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001880 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001881 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001882 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001883 }
1884 return false;
1885 }
1886
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001887 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1888 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1889 final long DIAG_TIME_MS = 5000;
1890 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1891 // Start gathering diagnostic information.
1892 netDiags.add(new NetworkDiagnostics(
1893 nai.network,
1894 new LinkProperties(nai.linkProperties), // Must be a copy.
1895 DIAG_TIME_MS));
1896 }
1897
1898 for (NetworkDiagnostics netDiag : netDiags) {
1899 pw.println();
1900 netDiag.waitForMeasurements();
1901 netDiag.dump(pw);
1902 }
1903 }
1904
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001905 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001906 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
Vishnu Nair5c010902017-10-26 10:08:50 -07001907 PriorityDump.dump(mPriorityDumper, fd, writer, args);
1908 }
1909
1910 private void doDump(FileDescriptor fd, PrintWriter writer, String[] args, boolean asProto) {
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001911 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001912 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Vishnu Nair5c010902017-10-26 10:08:50 -07001913 if (asProto) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001914
Erik Kline7747fd42017-05-12 16:52:48 +09001915 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001916 dumpNetworkDiagnostics(pw);
1917 return;
Erik Klineee363c42017-05-29 09:11:03 +09001918 } else if (argsContain(args, TETHERING_ARG)) {
1919 mTethering.dump(fd, pw, args);
1920 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001921 }
Erik Kline379747a2015-06-05 17:47:34 +09001922
Lorenzo Colittie3805462015-06-03 11:18:24 +09001923 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001924 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001925 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001926 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001927 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001928 pw.println();
1929
Paul Jensen85cf78e2015-06-25 13:25:07 -04001930 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001931 pw.print("Active default network: ");
1932 if (defaultNai == null) {
1933 pw.println("none");
1934 } else {
1935 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001936 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001937 pw.println();
1938
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001939 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001940 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001941 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1942 pw.println(nai.toString());
1943 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001944 pw.println(String.format(
1945 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1946 nai.numForegroundNetworkRequests(),
1947 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1948 nai.numBackgroundNetworkRequests(),
1949 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001950 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001951 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1952 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001953 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001954 pw.decreaseIndent();
1955 pw.println("Lingered:");
1956 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001957 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001958 pw.decreaseIndent();
1959 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001960 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001961 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001962 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001963
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001964 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001965 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001966 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1967 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001968 }
1969 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001970 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001971
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001972 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001973
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001974 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001975 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001976
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001977 pw.println();
1978 mKeepaliveTracker.dump(pw);
1979
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001980 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001981 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001982
Lorenzo Colittid260ef22018-01-24 17:35:07 +09001983 pw.println();
1984 mMultipathPolicyTracker.dump(pw);
1985
Erik Kline7747fd42017-05-12 16:52:48 +09001986 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001987 pw.println();
1988 synchronized (mValidationLogs) {
1989 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001990 for (ValidationLog p : mValidationLogs) {
1991 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001992 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001993 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001994 pw.decreaseIndent();
1995 }
1996 }
Erik Kline7523eb32015-07-09 18:24:03 +09001997
1998 pw.println();
1999 pw.println("mNetworkRequestInfoLogs (most recent first):");
2000 pw.increaseIndent();
2001 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
2002 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09002003
2004 pw.println();
2005 pw.println("mNetworkInfoBlockingLogs (most recent first):");
2006 pw.increaseIndent();
2007 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
2008 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002009
2010 pw.println();
2011 pw.println("NetTransition WakeLock activity (most recent first):");
2012 pw.increaseIndent();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09002013 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
2014 pw.println("total releases: " + mTotalWakelockReleases);
2015 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
2016 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
2017 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
2018 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
2019 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
2020 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002021 mWakelockLogs.reverseDump(fd, pw, args);
2022 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07002023 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002024 }
2025
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002026 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04002027 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002028 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002029 if (officialNai != null && officialNai.equals(nai)) return true;
2030 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002031 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002032 " - " + nai);
2033 }
2034 return false;
2035 }
2036
Robert Greenwalt42acef32009-08-12 16:08:25 -07002037 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002038 private class NetworkStateTrackerHandler extends Handler {
2039 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002040 super(looper);
2041 }
2042
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002043 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002044 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002045 default:
2046 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002047 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002048 handleAsyncChannelHalfConnect(msg);
2049 break;
2050 }
2051 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2052 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2053 if (nai != null) nai.asyncChannel.disconnect();
2054 break;
2055 }
2056 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2057 handleAsyncChannelDisconnected(msg);
2058 break;
2059 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002060 }
2061 return true;
2062 }
2063
2064 private void maybeHandleNetworkAgentMessage(Message msg) {
2065 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2066 if (nai == null) {
2067 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002068 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002069 }
2070 return;
2071 }
2072
2073 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002074 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002075 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2076 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002077 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2078 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002079 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002080 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002081 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002082 break;
2083 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002084 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002085 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002086 break;
2087 }
2088 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002089 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002090 updateNetworkInfo(nai, info);
2091 break;
2092 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002093 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002094 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002095 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002096 break;
2097 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002098 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002099 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2100 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002101 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002102 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002103 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002104 break;
2105 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002106 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002107 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2108 break;
2109 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002110 }
2111 }
2112
2113 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2114 switch (msg.what) {
2115 default:
2116 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002117 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002118 final NetworkAgentInfo nai;
2119 synchronized (mNetworkForNetId) {
2120 nai = mNetworkForNetId.get(msg.arg2);
2121 }
Erik Klinea24d4592018-01-11 21:07:29 +09002122 if (nai == null) break;
2123
2124 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2125 final boolean wasValidated = nai.lastValidated;
2126 final boolean wasDefault = isDefaultNetwork(nai);
2127
2128 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2129 ? (PrivateDnsConfig) msg.obj : null;
2130 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2131
2132 final boolean reevaluationRequired;
2133 final String logMsg;
2134 if (valid) {
2135 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2136 logMsg = (DBG && (privateDnsCfg != null))
2137 ? " with " + privateDnsCfg.toString() : "";
2138 } else {
2139 reevaluationRequired = false;
2140 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2141 ? " with redirect to " + redirectUrl : "";
2142 }
2143 if (DBG) {
2144 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2145 }
2146 // If there is a change in Private DNS configuration,
2147 // trigger reevaluation of the network to test it.
2148 if (reevaluationRequired) {
2149 nai.networkMonitor.sendMessage(
2150 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2151 break;
2152 }
2153 if (valid != nai.lastValidated) {
2154 if (wasDefault) {
2155 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2156 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002157 }
Erik Klinea24d4592018-01-11 21:07:29 +09002158 final int oldScore = nai.getCurrentScore();
2159 nai.lastValidated = valid;
2160 nai.everValidated |= valid;
2161 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2162 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2163 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2164 }
2165 updateInetCondition(nai);
2166 // Let the NetworkAgent know the state of its network
2167 Bundle redirectUrlBundle = new Bundle();
2168 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2169 nai.asyncChannel.sendMessage(
2170 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2171 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2172 0, redirectUrlBundle);
2173 if (wasValidated && !nai.lastValidated) {
2174 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002175 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002176 break;
2177 }
Paul Jensen869868be2014-05-15 10:33:05 -04002178 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002179 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002180 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002181 final NetworkAgentInfo nai;
2182 synchronized (mNetworkForNetId) {
2183 nai = mNetworkForNetId.get(netId);
2184 }
Calvin Onbe96da12016-10-11 15:10:46 -07002185 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002186 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002187 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002188 nai.lastCaptivePortalDetected = visible;
2189 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002190 if (nai.lastCaptivePortalDetected &&
2191 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2192 if (DBG) log("Avoiding captive portal network: " + nai.name());
2193 nai.asyncChannel.sendMessage(
2194 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2195 teardownUnneededNetwork(nai);
2196 break;
2197 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002198 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002199 }
2200 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002201 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002202 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002203 if (nai == null) {
2204 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2205 break;
2206 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002207 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002208 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002209 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002210 }
Paul Jensen869868be2014-05-15 10:33:05 -04002211 }
Paul Jensen869868be2014-05-15 10:33:05 -04002212 break;
2213 }
Erik Klinea24d4592018-01-11 21:07:29 +09002214 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2215 final NetworkAgentInfo nai;
2216 synchronized (mNetworkForNetId) {
2217 nai = mNetworkForNetId.get(msg.arg2);
2218 }
2219 if (nai == null) break;
2220
2221 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2222 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2223 if (nai.lastValidated && reevaluationRequired) {
2224 nai.networkMonitor.sendMessage(
2225 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2226 }
2227 break;
2228 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002229 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002230 return true;
2231 }
2232
Calvin Onbe96da12016-10-11 15:10:46 -07002233 private int getCaptivePortalMode() {
2234 return Settings.Global.getInt(mContext.getContentResolver(),
2235 Settings.Global.CAPTIVE_PORTAL_MODE,
2236 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2237 }
2238
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002239 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2240 switch (msg.what) {
2241 default:
2242 return false;
2243 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2244 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2245 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2246 handleLingerComplete(nai);
2247 }
2248 break;
2249 }
2250 }
2251 return true;
2252 }
2253
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002254 @Override
2255 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002256 if (!maybeHandleAsyncChannelMessage(msg) &&
2257 !maybeHandleNetworkMonitorMessage(msg) &&
2258 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002259 maybeHandleNetworkAgentMessage(msg);
2260 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002261 }
2262 }
2263
Erik Klinea24d4592018-01-11 21:07:29 +09002264 private void handlePrivateDnsSettingsChanged() {
2265 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2266
2267 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2268 // Private DNS only ever applies to networks that might provide
2269 // Internet access and therefore also require validation.
2270 if (!NetworkMonitor.isValidationRequired(
2271 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2272 continue;
2273 }
2274
2275 // Notify the NetworkMonitor thread in case it needs to cancel or
2276 // schedule DNS resolutions. If a DNS resolution is required the
2277 // result will be sent back to us.
2278 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2279
2280 if (!cfg.inStrictMode()) {
2281 // No strict mode hostname DNS resolution needed, so just update
2282 // DNS settings directly. In opportunistic and "off" modes this
2283 // just reprograms netd with the network-supplied DNS servers
2284 // (and of course the boolean of whether or not to attempt TLS).
2285 //
2286 // TODO: Consider code flow parity with strict mode, i.e. having
2287 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2288 // performing this call at that time.
2289 updatePrivateDns(nai, cfg);
2290 }
2291 }
2292 }
2293
2294 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2295 final boolean reevaluationRequired = true;
2296 final boolean dontReevaluate = false;
2297
2298 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2299 updateDnses(nai.linkProperties, null, nai.network.netId);
2300
2301 if (newCfg == null) {
2302 if (oldCfg == null) return dontReevaluate;
2303 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2304 }
2305
2306 if (oldCfg == null) {
2307 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2308 }
2309
2310 if (oldCfg.useTls != newCfg.useTls) {
2311 return reevaluationRequired;
2312 }
2313
2314 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2315 return reevaluationRequired;
2316 }
2317
2318 return dontReevaluate;
2319 }
2320
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002321 private void updateLingerState(NetworkAgentInfo nai, long now) {
2322 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2323 // 2. If the network was lingering and there are now requests, unlinger it.
2324 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2325 // one lingered request, start lingering.
2326 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002327 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002328 if (DBG) log("Unlingering " + nai.name());
2329 nai.unlinger();
2330 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002331 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002332 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002333 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002334 nai.linger();
2335 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2336 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2337 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002338 }
2339
Robert Greenwalt7b816022014-04-18 15:25:25 -07002340 private void handleAsyncChannelHalfConnect(Message msg) {
2341 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002342 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002343 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2344 if (VDBG) log("NetworkFactory connected");
2345 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002346 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002347 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002348 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002349 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002350 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002351 }
2352 } else {
2353 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002354 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002355 }
2356 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2357 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2358 if (VDBG) log("NetworkAgent connected");
2359 // A network agent has requested a connection. Establish the connection.
2360 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2361 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2362 } else {
2363 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002364 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002365 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002366 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002367 synchronized (mNetworkForNetId) {
2368 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002369 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002370 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002371 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002372 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002373 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002374 }
2375 }
2376 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002377
Robert Greenwalt7b816022014-04-18 15:25:25 -07002378 private void handleAsyncChannelDisconnected(Message msg) {
2379 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2380 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002381 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002382 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002383 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002384 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002385 // TODO - if we move the logic to the network agent (have them disconnect
2386 // because they lost all their requests or because their score isn't good)
2387 // then they would disconnect organically, report their new state and then
2388 // disconnect the channel.
2389 if (nai.networkInfo.isConnected()) {
2390 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2391 null, null);
2392 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002393 final boolean wasDefault = isDefaultNetwork(nai);
2394 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002395 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002396 // Log default network disconnection before required book-keeping.
2397 // Let rematchAllNetworksAndRequests() below record a new default network event
2398 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2399 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002400 long now = SystemClock.elapsedRealtime();
2401 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002402 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002403 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002404 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2405 // by other networks that are already connected. Perhaps that can be done by
2406 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2407 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002408 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002409 mKeepaliveTracker.handleStopAllKeepalives(nai,
2410 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002411 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2412 // Disable wakeup packet monitoring for each interface.
2413 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2414 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002415 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002416 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002417 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002418 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002419 // Remove the NetworkAgent, but don't mark the netId as
2420 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002421 mNetworkForNetId.remove(nai.network.netId);
2422 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002423 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002424 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2425 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002426 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002427 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002428 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002429 sendUpdatedScoreToFactories(request, 0);
2430 }
2431 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002432 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002433 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002434 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002435 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002436 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002437 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002438 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002439 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002440 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002441 if (nai.created) {
2442 // Tell netd to clean up the configuration for this network
2443 // (routing rules, DNS, etc).
2444 // This may be slow as it requires a lot of netd shelling out to ip and
2445 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2446 // after we've rematched networks with requests which should make a potential
2447 // fallback network the default or requested a new network from the
2448 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2449 // long time.
2450 try {
2451 mNetd.removeNetwork(nai.network.netId);
2452 } catch (Exception e) {
2453 loge("Exception removing network: " + e);
2454 }
Erik Klinea24d4592018-01-11 21:07:29 +09002455 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002456 }
2457 synchronized (mNetworkForNetId) {
2458 mNetIdInUse.delete(nai.network.netId);
2459 }
2460 } else {
2461 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2462 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002463 }
2464 }
2465
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002466 // If this method proves to be too slow then we can maintain a separate
2467 // pendingIntent => NetworkRequestInfo map.
2468 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2469 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2470 Intent intent = pendingIntent.getIntent();
2471 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2472 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2473 if (existingPendingIntent != null &&
2474 existingPendingIntent.getIntent().filterEquals(intent)) {
2475 return entry.getValue();
2476 }
2477 }
2478 return null;
2479 }
2480
2481 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2482 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2483
2484 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2485 if (existingRequest != null) { // remove the existing request.
2486 if (DBG) log("Replacing " + existingRequest.request + " with "
2487 + nri.request + " because their intents matched.");
2488 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2489 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002490 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002491 }
2492
Erik Klineda4bfa82015-04-30 12:58:40 +09002493 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002494 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002495 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002496 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002497 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002498 if (nri.request.networkCapabilities.hasSignalStrength() &&
2499 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2500 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002501 }
2502 }
2503 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002504 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002505 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002506 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002507 }
2508 }
2509
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002510 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2511 int callingUid) {
2512 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2513 if (nri != null) {
2514 handleReleaseNetworkRequest(nri.request, callingUid);
2515 }
2516 }
2517
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002518 // Determines whether the network is the best (or could become the best, if it validated), for
2519 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2520 // on the value of reason:
2521 //
2522 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2523 // then it should be torn down.
2524 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2525 // then it should be lingered.
2526 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2527 final int numRequests;
2528 switch (reason) {
2529 case TEARDOWN:
2530 numRequests = nai.numRequestNetworkRequests();
2531 break;
2532 case LINGER:
2533 numRequests = nai.numForegroundNetworkRequests();
2534 break;
2535 default:
2536 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2537 return true;
2538 }
2539
2540 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002541 return false;
2542 }
Paul Jensene0988542015-06-25 15:30:08 -04002543 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002544 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2545 // Background requests don't affect lingering.
2546 continue;
2547 }
2548
Paul Jensene0988542015-06-25 15:30:08 -04002549 // If this Network is already the highest scoring Network for a request, or if
2550 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002551 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002552 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002553 // Note that this catches two important cases:
2554 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2555 // is currently satisfying the request. This is desirable when
2556 // cellular ends up validating but WiFi does not.
2557 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002558 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002559 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002560 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002561 nai.getCurrentScoreAsValidated())) {
2562 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002563 }
2564 }
Paul Jensene0988542015-06-25 15:30:08 -04002565 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002566 }
2567
Erik Klineacdd6392016-07-07 16:50:58 +09002568 private NetworkRequestInfo getNriForAppRequest(
2569 NetworkRequest request, int callingUid, String requestedOperation) {
2570 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2571
Robert Greenwalt9258c642014-03-26 16:47:06 -07002572 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002573 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002574 log(String.format("UID %d attempted to %s for unowned request %s",
2575 callingUid, requestedOperation, nri));
2576 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002577 }
Erik Klineacdd6392016-07-07 16:50:58 +09002578 }
2579
2580 return nri;
2581 }
2582
Erik Kline57faba92015-11-25 12:49:38 +09002583 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002584 if (mNetworkRequests.get(nri.request) == null) {
2585 return;
Erik Kline57faba92015-11-25 12:49:38 +09002586 }
Hugo Benichicd952782017-09-20 11:20:14 +09002587 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002588 return;
2589 }
2590 if (VDBG || (DBG && nri.request.isRequest())) {
2591 log("releasing " + nri.request + " (timeout)");
2592 }
2593 handleRemoveNetworkRequest(nri);
2594 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002595 }
2596
Erik Klineacdd6392016-07-07 16:50:58 +09002597 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002598 final NetworkRequestInfo nri =
2599 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2600 if (nri == null) {
2601 return;
Erik Kline57faba92015-11-25 12:49:38 +09002602 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002603 if (VDBG || (DBG && nri.request.isRequest())) {
2604 log("releasing " + nri.request + " (release request)");
2605 }
2606 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002607 }
Erik Klineacdd6392016-07-07 16:50:58 +09002608
Hugo Benichidba33db2017-03-23 22:40:44 +09002609 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002610 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002611 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002612
Erik Klineacdd6392016-07-07 16:50:58 +09002613 synchronized (mUidToNetworkRequestCount) {
2614 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2615 if (requests < 1) {
2616 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2617 nri.mUid);
2618 } else if (requests == 1) {
2619 mUidToNetworkRequestCount.removeAt(
2620 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2621 } else {
2622 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2623 }
2624 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002625
Erik Klineacdd6392016-07-07 16:50:58 +09002626 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2627 if (nri.request.isRequest()) {
2628 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002629 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002630 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002631 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002632 nai.removeRequest(nri.request.requestId);
2633 if (VDBG) {
2634 log(" Removing from current network " + nai.name() +
2635 ", leaving " + nai.numNetworkRequests() + " requests.");
2636 }
2637 // If there are still lingered requests on this network, don't tear it down,
2638 // but resume lingering instead.
2639 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002640 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002641 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2642 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002643 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002644 wasKept = true;
2645 }
Hugo Benichicd952782017-09-20 11:20:14 +09002646 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002647 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2648 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002649 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002650 }
Erik Klineacdd6392016-07-07 16:50:58 +09002651 }
2652
2653 // TODO: remove this code once we know that the Slog.wtf is never hit.
2654 //
2655 // Find all networks that are satisfying this request and remove the request
2656 // from their request lists.
2657 // TODO - it's my understanding that for a request there is only a single
2658 // network satisfying it, so this loop is wasteful
2659 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2660 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2661 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2662 otherNai.name() + ", but mNetworkAgentInfos says " +
2663 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002664 }
2665 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002666
Erik Klineacdd6392016-07-07 16:50:58 +09002667 // Maintain the illusion. When this request arrived, we might have pretended
2668 // that a network connected to serve it, even though the network was already
2669 // connected. Now that this request has gone away, we might have to pretend
2670 // that the network disconnected. LegacyTypeTracker will generate that
2671 // phantom disconnect for this type.
2672 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2673 boolean doRemove = true;
2674 if (wasKept) {
2675 // check if any of the remaining requests for this network are for the
2676 // same legacy type - if so, don't remove the nai
2677 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2678 NetworkRequest otherRequest = nai.requestAt(i);
2679 if (otherRequest.legacyType == nri.request.legacyType &&
2680 otherRequest.isRequest()) {
2681 if (DBG) log(" still have other legacy request - leaving");
2682 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002683 }
2684 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002685 }
2686
Erik Klineacdd6392016-07-07 16:50:58 +09002687 if (doRemove) {
2688 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002689 }
2690 }
Erik Klineacdd6392016-07-07 16:50:58 +09002691
2692 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2693 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2694 nri.request);
2695 }
2696 } else {
2697 // listens don't have a singular affectedNetwork. Check all networks to see
2698 // if this listen request applies and remove it.
2699 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2700 nai.removeRequest(nri.request.requestId);
2701 if (nri.request.networkCapabilities.hasSignalStrength() &&
2702 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2703 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2704 }
2705 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002706 }
2707 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002708
Lorenzo Colitti18660282016-07-04 12:55:44 +09002709 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002710 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2711 enforceConnectivityInternalPermission();
2712 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002713 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002714 }
2715
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002716 @Override
2717 public void setAvoidUnvalidated(Network network) {
2718 enforceConnectivityInternalPermission();
2719 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2720 }
2721
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002722 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2723 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2724 " accept=" + accept + " always=" + always);
2725
2726 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2727 if (nai == null) {
2728 // Nothing to do.
2729 return;
2730 }
2731
2732 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002733 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002734 return;
2735 }
2736
2737 if (!nai.networkMisc.explicitlySelected) {
2738 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2739 }
2740
2741 if (accept != nai.networkMisc.acceptUnvalidated) {
2742 int oldScore = nai.getCurrentScore();
2743 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002744 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002745 sendUpdatedScoreToFactories(nai);
2746 }
2747
2748 if (always) {
2749 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002750 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002751 }
2752
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002753 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002754 // Tell the NetworkAgent to not automatically reconnect to the network.
2755 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2756 // Teardown the nework.
2757 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002758 }
2759
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002760 }
2761
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002762 private void handleSetAvoidUnvalidated(Network network) {
2763 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2764 if (nai == null || nai.lastValidated) {
2765 // Nothing to do. The network either disconnected or revalidated.
2766 return;
2767 }
2768 if (!nai.avoidUnvalidated) {
2769 int oldScore = nai.getCurrentScore();
2770 nai.avoidUnvalidated = true;
2771 rematchAllNetworksAndRequests(nai, oldScore);
2772 sendUpdatedScoreToFactories(nai);
2773 }
2774 }
2775
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002776 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002777 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002778 mHandler.sendMessageDelayed(
2779 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2780 PROMPT_UNVALIDATED_DELAY_MS);
2781 }
2782
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002783 @Override
2784 public void startCaptivePortalApp(Network network) {
2785 enforceConnectivityInternalPermission();
2786 mHandler.post(() -> {
2787 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2788 if (nai == null) return;
2789 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2790 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2791 });
2792 }
2793
Hugo Benichic8e9e122016-09-14 23:23:08 +00002794 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002795 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002796 }
2797
Erik Kline065ab6e2016-10-02 18:02:14 +09002798 private void rematchForAvoidBadWifiUpdate() {
2799 rematchAllNetworksAndRequests(null, 0);
2800 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2801 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2802 sendUpdatedScoreToFactories(nai);
2803 }
2804 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002805 }
2806
Erik Kline065ab6e2016-10-02 18:02:14 +09002807 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002808 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002809 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002810 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002811 if (!configRestrict) {
2812 pw.println("Bad Wi-Fi avoidance: unrestricted");
2813 return;
2814 }
2815
2816 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2817 pw.increaseIndent();
2818 pw.println("Config restrict: " + configRestrict);
2819
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002820 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002821 String description;
2822 // Can't use a switch statement because strings are legal case labels, but null is not.
2823 if ("0".equals(value)) {
2824 description = "get stuck";
2825 } else if (value == null) {
2826 description = "prompt";
2827 } else if ("1".equals(value)) {
2828 description = "avoid";
2829 } else {
2830 description = value + " (?)";
2831 }
2832 pw.println("User setting: " + description);
2833 pw.println("Network overrides:");
2834 pw.increaseIndent();
2835 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2836 if (nai.avoidUnvalidated) {
2837 pw.println(nai.name());
2838 }
2839 }
2840 pw.decreaseIndent();
2841 pw.decreaseIndent();
2842 }
2843
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002844 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2845 final String action;
2846 switch (type) {
2847 case NO_INTERNET:
2848 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2849 break;
2850 case LOST_INTERNET:
2851 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2852 break;
2853 default:
2854 Slog.wtf(TAG, "Unknown notification type " + type);
2855 return;
2856 }
2857
2858 Intent intent = new Intent(action);
2859 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2860 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2861 intent.setClassName("com.android.settings",
2862 "com.android.settings.wifi.WifiNoInternetDialog");
2863
2864 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2865 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2866 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2867 }
2868
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002869 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002870 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002871 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2872
2873 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2874 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002875 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002876 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002877 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2878 return;
2879 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002880 showValidationNotification(nai, NotificationType.NO_INTERNET);
2881 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002882
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002883 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2884 NetworkCapabilities nc = nai.networkCapabilities;
2885 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002886
Erik Kline065ab6e2016-10-02 18:02:14 +09002887 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002888 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002889 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2890 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002891 }
2892
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002893 @Override
2894 public int getMultipathPreference(Network network) {
2895 enforceAccessPermission();
2896
2897 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002898 if (nai != null && nai.networkCapabilities
2899 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002900 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2901 }
2902
Lorenzo Colittid260ef22018-01-24 17:35:07 +09002903 Integer networkPreference = mMultipathPolicyTracker.getMultipathPreference(network);
2904 if (networkPreference != null) {
2905 return networkPreference;
2906 }
2907
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002908 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2909 }
2910
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002911 private class InternalHandler extends Handler {
2912 public InternalHandler(Looper looper) {
2913 super(looper);
2914 }
2915
2916 @Override
2917 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002918 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002919 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002920 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002921 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002922 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002923 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002924 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002925 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002926 break;
2927 }
Jason Monkdecd2952013-10-10 14:02:51 -04002928 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002929 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002930 break;
2931 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002932 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002933 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2934 break;
2935 }
2936 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2937 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002938 break;
2939 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002940 case EVENT_REGISTER_NETWORK_AGENT: {
2941 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2942 break;
2943 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002944 case EVENT_REGISTER_NETWORK_REQUEST:
2945 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002946 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002947 break;
2948 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002949 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2950 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002951 handleRegisterNetworkRequestWithIntent(msg);
2952 break;
2953 }
Erik Kline57faba92015-11-25 12:49:38 +09002954 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2955 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2956 handleTimedOutNetworkRequest(nri);
2957 break;
2958 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002959 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2960 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2961 break;
2962 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002963 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002964 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002965 break;
2966 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002967 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002968 Network network = (Network) msg.obj;
2969 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002970 break;
2971 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002972 case EVENT_SET_AVOID_UNVALIDATED: {
2973 handleSetAvoidUnvalidated((Network) msg.obj);
2974 break;
2975 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002976 case EVENT_PROMPT_UNVALIDATED: {
2977 handlePromptUnvalidated((Network) msg.obj);
2978 break;
2979 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002980 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2981 handleMobileDataAlwaysOn();
2982 break;
2983 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002984 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2985 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2986 mKeepaliveTracker.handleStartKeepalive(msg);
2987 break;
2988 }
2989 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2990 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2991 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2992 int slot = msg.arg1;
2993 int reason = msg.arg2;
2994 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2995 break;
2996 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002997 case EVENT_SYSTEM_READY: {
2998 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2999 nai.networkMonitor.systemReady = true;
3000 }
Lorenzo Colittid260ef22018-01-24 17:35:07 +09003001 mMultipathPolicyTracker.start();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003002 break;
3003 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003004 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003005 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003006 break;
3007 }
Erik Klinea24d4592018-01-11 21:07:29 +09003008 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
3009 handlePrivateDnsSettingsChanged();
3010 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08003011 }
3012 }
3013 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003014
3015 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003016 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003017 public int tether(String iface, String callerPkg) {
3018 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003019 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003020 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003021 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003022 } else {
3023 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3024 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003025 }
3026
3027 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003028 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003029 public int untether(String iface, String callerPkg) {
3030 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08003031
3032 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003033 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07003034 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08003035 } else {
3036 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3037 }
3038 }
3039
3040 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003041 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003042 public int getLastTetherError(String iface) {
3043 enforceTetherAccessPermission();
3044
3045 if (isTetheringSupported()) {
3046 return mTethering.getLastTetherError(iface);
3047 } else {
3048 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3049 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003050 }
3051
3052 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003053 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003054 public String[] getTetherableUsbRegexs() {
3055 enforceTetherAccessPermission();
3056 if (isTetheringSupported()) {
3057 return mTethering.getTetherableUsbRegexs();
3058 } else {
3059 return new String[0];
3060 }
3061 }
3062
Lorenzo Colitti18660282016-07-04 12:55:44 +09003063 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003064 public String[] getTetherableWifiRegexs() {
3065 enforceTetherAccessPermission();
3066 if (isTetheringSupported()) {
3067 return mTethering.getTetherableWifiRegexs();
3068 } else {
3069 return new String[0];
3070 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003071 }
3072
Lorenzo Colitti18660282016-07-04 12:55:44 +09003073 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003074 public String[] getTetherableBluetoothRegexs() {
3075 enforceTetherAccessPermission();
3076 if (isTetheringSupported()) {
3077 return mTethering.getTetherableBluetoothRegexs();
3078 } else {
3079 return new String[0];
3080 }
3081 }
3082
Lorenzo Colitti18660282016-07-04 12:55:44 +09003083 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003084 public int setUsbTethering(boolean enable, String callerPkg) {
3085 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003086 if (isTetheringSupported()) {
3087 return mTethering.setUsbTethering(enable);
3088 } else {
3089 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3090 }
3091 }
3092
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003093 // TODO - move iface listing, queries, etc to new module
3094 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003095 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003096 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003097 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003098 return mTethering.getTetherableIfaces();
3099 }
3100
Lorenzo Colitti18660282016-07-04 12:55:44 +09003101 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003102 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003103 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003104 return mTethering.getTetheredIfaces();
3105 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003106
Lorenzo Colitti18660282016-07-04 12:55:44 +09003107 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003108 public String[] getTetheringErroredIfaces() {
3109 enforceTetherAccessPermission();
3110 return mTethering.getErroredIfaces();
3111 }
3112
Lorenzo Colitti18660282016-07-04 12:55:44 +09003113 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003114 public String[] getTetheredDhcpRanges() {
3115 enforceConnectivityInternalPermission();
3116 return mTethering.getTetheredDhcpRanges();
3117 }
3118
Udam Saini0e94c362017-06-07 12:06:28 -07003119 @Override
3120 public boolean isTetheringSupported(String callerPkg) {
3121 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3122 return isTetheringSupported();
3123 }
3124
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003125 // if ro.tether.denied = true we default to no tethering
3126 // gservices could set the secure setting to 1 though to enable it on a build where it
3127 // had previously been turned off.
Udam Saini0e94c362017-06-07 12:06:28 -07003128 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003129 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3130 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3131 Settings.Global.TETHER_SUPPORTED, defaultVal));
3132 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003133 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003134
3135 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3136 boolean adminUser = false;
3137 final long token = Binder.clearCallingIdentity();
3138 try {
3139 adminUser = mUserManager.isAdminUser();
3140 } finally {
3141 Binder.restoreCallingIdentity(token);
3142 }
3143
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003144 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003145 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003146
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003147 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003148 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3149 String callerPkg) {
3150 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003151 if (!isTetheringSupported()) {
3152 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3153 return;
3154 }
3155 mTethering.startTethering(type, receiver, showProvisioningUi);
3156 }
3157
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003158 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003159 public void stopTethering(int type, String callerPkg) {
3160 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003161 mTethering.stopTethering(type);
3162 }
3163
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003164 // Called when we lose the default network and have no replacement yet.
3165 // This will automatically be cleared after X seconds or a new default network
3166 // becomes CONNECTED, whichever happens first. The timer is started by the
3167 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003168 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003169 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003170 if (mNetTransitionWakeLock.isHeld()) {
3171 return;
3172 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003173 mNetTransitionWakeLock.acquire();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003174 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3175 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003176 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003177 mWakelockLogs.log("ACQUIRE for " + forWhom);
3178 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3179 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003180 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003181
Hugo Benichi4c31b342017-03-30 23:18:10 +09003182 // Called when we gain a new default network to release the network transition wakelock in a
3183 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3184 // message is cancelled.
3185 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003186 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003187 if (!mNetTransitionWakeLock.isHeld()) {
3188 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003189 }
3190 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003191 // Cancel self timeout on wakelock hold.
3192 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3193 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3194 mHandler.sendMessageDelayed(msg, 1000);
3195 }
3196
3197 // Called when either message of ensureNetworkTransitionWakelock or
3198 // scheduleReleaseNetworkTransitionWakelock is processed.
3199 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3200 String event = eventName(eventId);
3201 synchronized (this) {
3202 if (!mNetTransitionWakeLock.isHeld()) {
3203 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3204 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3205 return;
3206 }
3207 mNetTransitionWakeLock.release();
Hugo Benichi26bcfa12017-09-05 13:25:07 +09003208 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3209 mTotalWakelockDurationMs += lockDuration;
3210 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3211 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003212 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003213 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003214 }
3215
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003216 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003217 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003218 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003219 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003220 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003221 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003222 }
3223
Lorenzo Colitti18660282016-07-04 12:55:44 +09003224 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003225 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003226 enforceAccessPermission();
3227 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003228 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003229 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003230 mHandler.sendMessage(
3231 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3232 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003233
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003234 private void handleReportNetworkConnectivity(
3235 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003236 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003237 if (network == null) {
3238 nai = getDefaultNetwork();
3239 } else {
3240 nai = getNetworkAgentInfoForNetwork(network);
3241 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003242 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3243 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3244 return;
3245 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003246 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003247 if (hasConnectivity == nai.lastValidated) {
3248 return;
3249 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003250 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003251 int netid = nai.network.netId;
3252 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003253 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003254 // Validating a network that has not yet connected could result in a call to
3255 // rematchNetworkAndRequests() which is not meant to work on such networks.
3256 if (!nai.everConnected) {
3257 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003258 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003259 LinkProperties lp = getLinkProperties(nai);
3260 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3261 return;
3262 }
3263 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003264 }
3265
Paul Jensencee9b512015-05-06 07:32:40 -04003266 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003267 // this information is already available as a world read/writable jvm property
3268 // so this API change wouldn't have a benifit. It also breaks the passing
3269 // of proxy info to all the JVMs.
3270 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003271 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003272 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003273 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3274 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003275 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003276 }
3277
Lorenzo Colitti18660282016-07-04 12:55:44 +09003278 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003279 public ProxyInfo getProxyForNetwork(Network network) {
3280 if (network == null) return getDefaultProxy();
3281 final ProxyInfo globalProxy = getGlobalProxy();
3282 if (globalProxy != null) return globalProxy;
3283 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3284 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3285 // caller may not have.
3286 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3287 if (nai == null) return null;
3288 synchronized (nai) {
3289 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3290 if (proxyInfo == null) return null;
3291 return new ProxyInfo(proxyInfo);
3292 }
3293 }
3294
Paul Jensene0bef712014-12-10 15:12:18 -05003295 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3296 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3297 // proxy is null then there is no proxy in place).
3298 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3299 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3300 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3301 proxy = null;
3302 }
3303 return proxy;
3304 }
3305
3306 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3307 // better for determining if a new proxy broadcast is necessary:
3308 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3309 // avoid unnecessary broadcasts.
3310 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3311 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3312 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3313 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3314 // all set.
3315 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3316 a = canonicalizeProxyInfo(a);
3317 b = canonicalizeProxyInfo(b);
3318 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3319 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3320 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3321 }
3322
Jason Monk207900c2014-04-25 15:00:09 -04003323 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003324 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003325
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003326 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003327 if (proxyProperties == mGlobalProxy) return;
3328 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3329 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3330
3331 String host = "";
3332 int port = 0;
3333 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003334 String pacFileUrl = "";
3335 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003336 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003337 if (!proxyProperties.isValid()) {
3338 if (DBG)
3339 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3340 return;
3341 }
Jason Monk207900c2014-04-25 15:00:09 -04003342 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003343 host = mGlobalProxy.getHost();
3344 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003345 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003346 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003347 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003348 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003349 } else {
3350 mGlobalProxy = null;
3351 }
3352 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003353 final long token = Binder.clearCallingIdentity();
3354 try {
3355 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3356 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3357 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3358 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003359 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003360 } finally {
3361 Binder.restoreCallingIdentity(token);
3362 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003363
Jason Monkcf0f97a2014-10-02 15:39:38 -04003364 if (mGlobalProxy == null) {
3365 proxyProperties = mDefaultProxy;
3366 }
3367 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003368 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003369 }
3370
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003371 private void loadGlobalProxy() {
3372 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003373 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3374 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3375 String exclList = Settings.Global.getString(res,
3376 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003377 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3378 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003379 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003380 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003381 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003382 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003383 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003384 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003385 if (!proxyProperties.isValid()) {
3386 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3387 return;
3388 }
3389
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003390 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003391 mGlobalProxy = proxyProperties;
3392 }
3393 }
3394 }
3395
Jason Monk207900c2014-04-25 15:00:09 -04003396 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003397 // this information is already available as a world read/writable jvm property
3398 // so this API change wouldn't have a benifit. It also breaks the passing
3399 // of proxy info to all the JVMs.
3400 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003401 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003402 return mGlobalProxy;
3403 }
3404 }
3405
Jason Monk207900c2014-04-25 15:00:09 -04003406 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003407 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003408 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003409 proxy = null;
3410 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003411 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003412 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003413 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003414 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003415 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3416 return;
3417 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003418
3419 // This call could be coming from the PacManager, containing the port of the local
3420 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3421 // global (to get the correct local port), and send a broadcast.
3422 // TODO: Switch PacManager to have its own message to send back rather than
3423 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003424 if ((mGlobalProxy != null) && (proxy != null)
3425 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003426 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3427 mGlobalProxy = proxy;
3428 sendProxyBroadcast(mGlobalProxy);
3429 return;
3430 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003431 mDefaultProxy = proxy;
3432
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003433 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003434 if (!mDefaultProxyDisabled) {
3435 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003436 }
3437 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003438 }
3439
Paul Jensene0bef712014-12-10 15:12:18 -05003440 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3441 // This method gets called when any network changes proxy, but the broadcast only ever contains
3442 // the default proxy (even if it hasn't changed).
3443 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3444 // world where an app might be bound to a non-default network.
3445 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3446 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3447 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3448
3449 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3450 sendProxyBroadcast(getDefaultProxy());
3451 }
3452 }
3453
Robert Greenwalt434203a2010-10-11 16:00:27 -07003454 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003455 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3456 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003457 if (!TextUtils.isEmpty(proxy)) {
3458 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003459 if (data.length == 0) {
3460 return;
3461 }
3462
Robert Greenwalt434203a2010-10-11 16:00:27 -07003463 String proxyHost = data[0];
3464 int proxyPort = 8080;
3465 if (data.length > 1) {
3466 try {
3467 proxyPort = Integer.parseInt(data[1]);
3468 } catch (NumberFormatException e) {
3469 return;
3470 }
3471 }
Jason Monk207900c2014-04-25 15:00:09 -04003472 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003473 setGlobalProxy(p);
3474 }
3475 }
3476
Jason Monk207900c2014-04-25 15:00:09 -04003477 private void sendProxyBroadcast(ProxyInfo proxy) {
3478 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003479 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003480 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003481 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003482 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3483 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003484 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003485 final long ident = Binder.clearCallingIdentity();
3486 try {
3487 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3488 } finally {
3489 Binder.restoreCallingIdentity(ident);
3490 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003491 }
3492
3493 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003494 final private HashMap<Uri, Integer> mUriEventMap;
3495 final private Context mContext;
3496 final private Handler mHandler;
3497
3498 SettingsObserver(Context context, Handler handler) {
3499 super(null);
3500 mUriEventMap = new HashMap<Uri, Integer>();
3501 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003502 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003503 }
3504
Erik Klineda4bfa82015-04-30 12:58:40 +09003505 void observe(Uri uri, int what) {
3506 mUriEventMap.put(uri, what);
3507 final ContentResolver resolver = mContext.getContentResolver();
3508 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003509 }
3510
3511 @Override
3512 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003513 Slog.wtf(TAG, "Should never be reached.");
3514 }
3515
3516 @Override
3517 public void onChange(boolean selfChange, Uri uri) {
3518 final Integer what = mUriEventMap.get(uri);
3519 if (what != null) {
3520 mHandler.obtainMessage(what.intValue()).sendToTarget();
3521 } else {
3522 loge("No matching event to send for URI=" + uri);
3523 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003524 }
3525 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003526
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003527 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003528 Slog.d(TAG, s);
3529 }
3530
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003531 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003532 Slog.e(TAG, s);
3533 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003534
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003535 private static void loge(String s, Throwable t) {
3536 Slog.e(TAG, s, t);
3537 }
3538
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003539 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003540 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003541 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3542 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3543 *
3544 * @param oldPackage Package name of the application which currently controls VPN, which will
3545 * be replaced. If there is no such application, this should should either be
3546 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3547 * @param newPackage Package name of the application which should gain control of VPN, or
3548 * {@code null} to disable.
3549 * @param userId User for whom to prepare the new VPN.
3550 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003551 * @hide
3552 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003553 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003554 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3555 int userId) {
3556 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003557
Hugo Benichi20035e02017-04-26 14:53:28 +09003558 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003559 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003560 Vpn vpn = mVpns.get(userId);
3561 if (vpn != null) {
3562 return vpn.prepare(oldPackage, newPackage);
3563 } else {
3564 return false;
3565 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003566 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003567 }
3568
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003569 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003570 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3571 * This method is used by system-privileged apps.
3572 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3573 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3574 *
3575 * @param packageName The package for which authorization state should change.
3576 * @param userId User for whom {@code packageName} is installed.
3577 * @param authorized {@code true} if this app should be able to start a VPN connection without
3578 * explicit user approval, {@code false} if not.
3579 *
Jeff Davidson05542602014-08-11 14:07:27 -07003580 * @hide
3581 */
3582 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003583 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3584 enforceCrossUserPermission(userId);
3585
Hugo Benichi20035e02017-04-26 14:53:28 +09003586 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003587 Vpn vpn = mVpns.get(userId);
3588 if (vpn != null) {
3589 vpn.setPackageAuthorization(packageName, authorized);
3590 }
Jeff Davidson05542602014-08-11 14:07:27 -07003591 }
3592 }
3593
3594 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003595 * Configure a TUN interface and return its file descriptor. Parameters
3596 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003597 * and not available in ConnectivityManager. Permissions are checked in
3598 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003599 * @hide
3600 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003601 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003602 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003603 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003604 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003605 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003606 return mVpns.get(user).establish(config);
3607 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003608 }
3609
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003610 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003611 * Start legacy VPN, controlling native daemons as needed. Creates a
3612 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003613 */
3614 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003615 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003616 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003617 final LinkProperties egress = getActiveLinkProperties();
3618 if (egress == null) {
3619 throw new IllegalStateException("Missing active network connection");
3620 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003621 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003622 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003623 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3624 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003625 }
3626
3627 /**
3628 * Return the information of the ongoing legacy VPN. This method is used
3629 * by VpnSettings and not available in ConnectivityManager. Permissions
3630 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003631 */
3632 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003633 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3634 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003635
Hugo Benichi20035e02017-04-26 14:53:28 +09003636 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003637 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003638 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003639 }
3640
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003641 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003642 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3643 * and not available in ConnectivityManager.
3644 */
3645 @Override
3646 public VpnInfo[] getAllVpnInfo() {
3647 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003648 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003649 if (mLockdownEnabled) {
3650 return new VpnInfo[0];
3651 }
3652
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003653 List<VpnInfo> infoList = new ArrayList<>();
3654 for (int i = 0; i < mVpns.size(); i++) {
3655 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3656 if (info != null) {
3657 infoList.add(info);
3658 }
3659 }
3660 return infoList.toArray(new VpnInfo[infoList.size()]);
3661 }
3662 }
3663
3664 /**
3665 * @return VPN information for accounting, or null if we can't retrieve all required
3666 * information, e.g primary underlying iface.
3667 */
3668 @Nullable
3669 private VpnInfo createVpnInfo(Vpn vpn) {
3670 VpnInfo info = vpn.getVpnInfo();
3671 if (info == null) {
3672 return null;
3673 }
3674 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3675 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3676 // the underlyingNetworks list.
3677 if (underlyingNetworks == null) {
3678 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3679 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3680 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3681 }
3682 } else if (underlyingNetworks.length > 0) {
3683 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3684 if (linkProperties != null) {
3685 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3686 }
3687 }
3688 return info.primaryUnderlyingIface == null ? null : info;
3689 }
3690
3691 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003692 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3693 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003694 * Permissions are checked in Vpn class.
3695 * @hide
3696 */
3697 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003698 public VpnConfig getVpnConfig(int userId) {
3699 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003700 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003701 Vpn vpn = mVpns.get(userId);
3702 if (vpn != null) {
3703 return vpn.getVpnConfig();
3704 } else {
3705 return null;
3706 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003707 }
3708 }
3709
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003710 @Override
3711 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003712 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3713 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3714 return false;
3715 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003716
Hugo Benichi69744342017-11-27 10:57:16 +09003717 synchronized (mVpns) {
3718 // Tear down existing lockdown if profile was removed
3719 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3720 if (mLockdownEnabled) {
3721 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3722 if (profileTag == null) {
3723 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3724 return false;
3725 }
3726 String profileName = new String(profileTag);
3727 final VpnProfile profile = VpnProfile.decode(
3728 profileName, mKeyStore.get(Credentials.VPN + profileName));
3729 if (profile == null) {
3730 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3731 setLockdownTracker(null);
3732 return true;
3733 }
3734 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003735 Vpn vpn = mVpns.get(user);
3736 if (vpn == null) {
3737 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3738 return false;
3739 }
3740 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003741 } else {
3742 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003743 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003744 }
3745
3746 return true;
3747 }
3748
3749 /**
3750 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3751 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3752 */
Hugo Benichi69744342017-11-27 10:57:16 +09003753 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003754 private void setLockdownTracker(LockdownVpnTracker tracker) {
3755 // Shutdown any existing tracker
3756 final LockdownVpnTracker existing = mLockdownTracker;
3757 mLockdownTracker = null;
3758 if (existing != null) {
3759 existing.shutdown();
3760 }
3761
Robin Leec3736bc2017-03-10 16:19:54 +00003762 if (tracker != null) {
3763 mLockdownTracker = tracker;
3764 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003765 }
3766 }
3767
Hugo Benichi69744342017-11-27 10:57:16 +09003768 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003769 private void throwIfLockdownEnabled() {
3770 if (mLockdownEnabled) {
3771 throw new IllegalStateException("Unavailable in lockdown mode");
3772 }
3773 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003774
Robin Lee244ce8e2016-01-05 18:03:46 +00003775 /**
Robin Lee17e61832016-05-09 13:46:28 +01003776 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3777 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003778 *
Robin Lee17e61832016-05-09 13:46:28 +01003779 * @return {@code true} if the service was started, the service was already connected, or there
3780 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003781 */
Robin Lee17e61832016-05-09 13:46:28 +01003782 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003783 synchronized (mVpns) {
3784 Vpn vpn = mVpns.get(userId);
3785 if (vpn == null) {
3786 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3787 // exists already.
3788 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3789 return false;
3790 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003791
Robin Lee812800c2016-05-13 15:38:08 +01003792 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003793 }
3794 }
3795
3796 @Override
Charles He36738632017-05-15 17:07:18 +01003797 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3798 enforceSettingsPermission();
3799 enforceCrossUserPermission(userId);
3800
3801 synchronized (mVpns) {
3802 Vpn vpn = mVpns.get(userId);
3803 if (vpn == null) {
3804 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3805 return false;
3806 }
3807 return vpn.isAlwaysOnPackageSupported(packageName);
3808 }
3809 }
3810
3811 @Override
Robin Leedc679712016-05-03 13:23:03 +01003812 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003813 enforceConnectivityInternalPermission();
3814 enforceCrossUserPermission(userId);
3815
Robin Lee244ce8e2016-01-05 18:03:46 +00003816 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003817 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3818 if (LockdownVpnTracker.isEnabled()) {
3819 return false;
3820 }
3821
Robin Lee244ce8e2016-01-05 18:03:46 +00003822 Vpn vpn = mVpns.get(userId);
3823 if (vpn == null) {
3824 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3825 return false;
3826 }
Robin Lee17e61832016-05-09 13:46:28 +01003827 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003828 return false;
3829 }
Robin Lee17e61832016-05-09 13:46:28 +01003830 if (!startAlwaysOnVpn(userId)) {
3831 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003832 return false;
3833 }
3834 }
3835 return true;
3836 }
3837
3838 @Override
3839 public String getAlwaysOnVpnPackage(int userId) {
3840 enforceConnectivityInternalPermission();
3841 enforceCrossUserPermission(userId);
3842
3843 synchronized (mVpns) {
3844 Vpn vpn = mVpns.get(userId);
3845 if (vpn == null) {
3846 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3847 return null;
3848 }
3849 return vpn.getAlwaysOnPackage();
3850 }
3851 }
3852
Wink Savilleab9321d2013-06-29 21:10:57 -07003853 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003854 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003855 // TODO: Remove? Any reason to trigger a provisioning check?
3856 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003857 }
3858
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003859 /** Location to an updatable file listing carrier provisioning urls.
3860 * An example:
3861 *
3862 * <?xml version="1.0" encoding="utf-8"?>
3863 * <provisioningUrls>
3864 * <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 -07003865 * </provisioningUrls>
3866 */
3867 private static final String PROVISIONING_URL_PATH =
3868 "/data/misc/radio/provisioning_urls.xml";
3869 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003870
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003871 /** XML tag for root element. */
3872 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3873 /** XML tag for individual url */
3874 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003875 /** XML attribute for mcc */
3876 private static final String ATTR_MCC = "mcc";
3877 /** XML attribute for mnc */
3878 private static final String ATTR_MNC = "mnc";
3879
Paul Jensen434dde82015-06-11 09:43:30 -04003880 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003881 FileReader fileReader = null;
3882 XmlPullParser parser = null;
3883 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003884
3885 try {
3886 fileReader = new FileReader(mProvisioningUrlFile);
3887 parser = Xml.newPullParser();
3888 parser.setInput(fileReader);
3889 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3890
3891 while (true) {
3892 XmlUtils.nextElement(parser);
3893
3894 String element = parser.getName();
3895 if (element == null) break;
3896
Paul Jensen434dde82015-06-11 09:43:30 -04003897 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003898 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3899 try {
3900 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3901 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3902 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3903 parser.next();
3904 if (parser.getEventType() == XmlPullParser.TEXT) {
3905 return parser.getText();
3906 }
3907 }
3908 }
3909 } catch (NumberFormatException e) {
3910 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3911 }
3912 }
3913 }
3914 return null;
3915 } catch (FileNotFoundException e) {
3916 loge("Carrier Provisioning Urls file not found");
3917 } catch (XmlPullParserException e) {
3918 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3919 } catch (IOException e) {
3920 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3921 } finally {
3922 if (fileReader != null) {
3923 try {
3924 fileReader.close();
3925 } catch (IOException e) {}
3926 }
3927 }
3928 return null;
3929 }
3930
Wink Saville42d4f082013-07-20 20:31:59 -07003931 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003932 public String getMobileProvisioningUrl() {
3933 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003934 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003935 if (TextUtils.isEmpty(url)) {
3936 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003937 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003938 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003939 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003940 }
Wink Saville8cf35602013-07-10 23:00:07 -07003941 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003942 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003943 String phoneNumber = mTelephonyManager.getLine1Number();
3944 if (TextUtils.isEmpty(phoneNumber)) {
3945 phoneNumber = "0000000000";
3946 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003947 url = String.format(url,
3948 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3949 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003950 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003951 }
3952
Wink Savilleab9321d2013-06-29 21:10:57 -07003953 return url;
3954 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003955
Wink Saville948282b2013-08-29 08:55:16 -07003956 @Override
3957 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003958 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003959 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003960 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3961 return;
3962 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003963 final long ident = Binder.clearCallingIdentity();
3964 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003965 // Concatenate the range of types onto the range of NetIDs.
3966 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3967 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003968 } finally {
3969 Binder.restoreCallingIdentity(ident);
3970 }
Wink Saville948282b2013-08-29 08:55:16 -07003971 }
Wink Saville7788c612013-08-29 14:57:08 -07003972
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003973 @Override
3974 public void setAirplaneMode(boolean enable) {
3975 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003976 final long ident = Binder.clearCallingIdentity();
3977 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003978 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003979 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003980 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3981 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003982 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003983 } finally {
3984 Binder.restoreCallingIdentity(ident);
3985 }
3986 }
3987
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003988 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003989 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003990 Vpn userVpn = mVpns.get(userId);
3991 if (userVpn != null) {
3992 loge("Starting user already has a VPN");
3993 return;
3994 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003995 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003996 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003997 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3998 updateLockdownVpn();
3999 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004000 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004001 }
4002
4003 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004004 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004005 Vpn userVpn = mVpns.get(userId);
4006 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004007 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004008 return;
4009 }
Robin Lee17e61832016-05-09 13:46:28 +01004010 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004011 mVpns.delete(userId);
4012 }
4013 }
4014
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004015 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004016 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004017 final int vpnsSize = mVpns.size();
4018 for (int i = 0; i < vpnsSize; i++) {
4019 Vpn vpn = mVpns.valueAt(i);
4020 vpn.onUserAdded(userId);
4021 }
4022 }
4023 }
4024
4025 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09004026 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004027 final int vpnsSize = mVpns.size();
4028 for (int i = 0; i < vpnsSize; i++) {
4029 Vpn vpn = mVpns.valueAt(i);
4030 vpn.onUserRemoved(userId);
4031 }
4032 }
4033 }
4034
Robin Lee89e7a692016-02-29 14:38:17 +00004035 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09004036 synchronized (mVpns) {
4037 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4038 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4039 updateLockdownVpn();
4040 } else {
4041 startAlwaysOnVpn(userId);
4042 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004043 }
4044 }
4045
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004046 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4047 @Override
4048 public void onReceive(Context context, Intent intent) {
4049 final String action = intent.getAction();
4050 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4051 if (userId == UserHandle.USER_NULL) return;
4052
Robin Lee323f29d2016-05-04 16:38:06 +01004053 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004054 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004055 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004056 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004057 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4058 onUserAdded(userId);
4059 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4060 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004061 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4062 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004063 }
4064 }
4065 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004066
Robin Lee95204e02017-01-27 11:59:22 +00004067 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4068 @Override
4069 public void onReceive(Context context, Intent intent) {
4070 // Try creating lockdown tracker, since user present usually means
4071 // unlocked keystore.
4072 updateLockdownVpn();
4073 mContext.unregisterReceiver(this);
4074 }
4075 };
4076
Robert Greenwalta67be032014-05-16 15:49:14 -07004077 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4078 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4080 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004081
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004082 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4083 // Map from UID to number of NetworkRequests that UID has filed.
4084 @GuardedBy("mUidToNetworkRequestCount")
4085 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4086
Robert Greenwalta67be032014-05-16 15:49:14 -07004087 private static class NetworkFactoryInfo {
4088 public final String name;
4089 public final Messenger messenger;
4090 public final AsyncChannel asyncChannel;
4091
4092 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4093 this.name = name;
4094 this.messenger = messenger;
4095 this.asyncChannel = asyncChannel;
4096 }
4097 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004098
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004099 private void ensureNetworkRequestHasType(NetworkRequest request) {
4100 if (request.type == NetworkRequest.Type.NONE) {
4101 throw new IllegalArgumentException(
4102 "All NetworkRequests in ConnectivityService must have a type");
4103 }
4104 }
4105
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004106 /**
4107 * Tracks info about the requester.
4108 * Also used to notice when the calling process dies so we can self-expire
4109 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004110 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004111 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004112 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004113 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004114 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004115 final int mPid;
4116 final int mUid;
4117 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004118
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004119 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004120 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004121 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004122 mPendingIntent = pi;
4123 messenger = null;
4124 mBinder = null;
4125 mPid = getCallingPid();
4126 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004127 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004128 }
4129
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004130 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004131 super();
4132 messenger = m;
4133 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004134 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004135 mBinder = binder;
4136 mPid = getCallingPid();
4137 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004138 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004139 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004140
4141 try {
4142 mBinder.linkToDeath(this, 0);
4143 } catch (RemoteException e) {
4144 binderDied();
4145 }
4146 }
4147
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004148 private void enforceRequestCountLimit() {
4149 synchronized (mUidToNetworkRequestCount) {
4150 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4151 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004152 throw new ServiceSpecificException(
4153 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004154 }
4155 mUidToNetworkRequestCount.put(mUid, networkRequests);
4156 }
4157 }
4158
Robert Greenwalt9258c642014-03-26 16:47:06 -07004159 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004160 if (mBinder != null) {
4161 mBinder.unlinkToDeath(this, 0);
4162 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004163 }
4164
4165 public void binderDied() {
4166 log("ConnectivityService NetworkRequestInfo binderDied(" +
4167 request + ", " + mBinder + ")");
4168 releaseNetworkRequest(request);
4169 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004170
4171 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004172 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004173 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004174 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004175 }
4176
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004177 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4178 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4179 if (badCapability != null) {
4180 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004181 }
4182 }
4183
Erik Kline9d598e12015-07-13 16:37:51 +09004184 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004185 final SortedSet<Integer> thresholds = new TreeSet();
4186 synchronized (nai) {
4187 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4188 if (nri.request.networkCapabilities.hasSignalStrength() &&
4189 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4190 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4191 }
4192 }
4193 }
Erik Kline9d598e12015-07-13 16:37:51 +09004194 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004195 }
4196
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004197 private void updateSignalStrengthThresholds(
4198 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4199 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004200 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004201 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4202
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004203 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004204 String detail;
4205 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4206 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4207 } else {
4208 detail = reason;
4209 }
4210 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4211 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4212 }
4213
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004214 nai.asyncChannel.sendMessage(
4215 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004216 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004217 }
4218
Etan Cohen859748f2017-04-03 17:42:34 -07004219 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4220 if (nc == null) {
4221 return;
4222 }
4223 NetworkSpecifier ns = nc.getNetworkSpecifier();
4224 if (ns == null) {
4225 return;
4226 }
4227 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4228 ns.assertValidFromUid(Binder.getCallingUid());
4229 }
4230
Robert Greenwalt9258c642014-03-26 16:47:06 -07004231 @Override
4232 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004233 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004234 final NetworkRequest.Type type = (networkCapabilities == null)
4235 ? NetworkRequest.Type.TRACK_DEFAULT
4236 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004237 // If the requested networkCapabilities is null, take them instead from
4238 // the default network request. This allows callers to keep track of
4239 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004240 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004241 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004242 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004243 enforceAccessPermission();
4244 } else {
4245 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4246 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004247 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4248 // of the app when the request is filed, but we never change the request if the app
4249 // changes network state. http://b/29964605
4250 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004251 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004252 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004253 // Set the UID range for this request to the single UID of the requester.
4254 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4255 // are no visible methods to set the UIDs, an app could use reflection to try and get
4256 // networks for other apps so it's essential that the UIDs are overwritten.
4257 // TODO : don't forcefully set the UID when communicating with processes
4258 // that have the NETWORK_SETTINGS permission.
4259 networkCapabilities.setSingleUid(Binder.getCallingUid());
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004260
Etan Cohenba07c8c2017-02-05 10:42:27 -08004261 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004262 throw new IllegalArgumentException("Bad timeout specified");
4263 }
Etan Cohen859748f2017-04-03 17:42:34 -07004264 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004265
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004266 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004267 nextNetworkRequestId(), type);
4268 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004269 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004270
4271 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004272 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004273 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004274 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004275 }
4276 return networkRequest;
4277 }
4278
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004279 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004280 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004281 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004282 } else {
4283 enforceChangePermission();
4284 }
4285 }
4286
fenglub15e72b2015-03-20 11:29:56 -07004287 @Override
fengludb571472015-04-21 17:12:05 -07004288 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004289 enforceAccessPermission();
4290 NetworkAgentInfo nai = null;
4291 if (network == null) {
4292 return false;
4293 }
4294 synchronized (mNetworkForNetId) {
4295 nai = mNetworkForNetId.get(network.netId);
4296 }
4297 if (nai != null) {
4298 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4299 return true;
4300 }
4301 return false;
4302 }
4303
Felipe Lemeee27cab2016-06-20 16:36:29 -07004304 private boolean isSystem(int uid) {
4305 return uid < Process.FIRST_APPLICATION_UID;
4306 }
fenglub15e72b2015-03-20 11:29:56 -07004307
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004308 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004309 final int uid = Binder.getCallingUid();
4310 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004311 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004312 return;
4313 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004314 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4315 // Policy already enforced.
4316 return;
4317 }
4318 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4319 // If UID is restricted, don't allow them to bring up metered APNs.
4320 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004321 }
4322 }
4323
Robert Greenwalt9258c642014-03-26 16:47:06 -07004324 @Override
4325 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4326 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004327 checkNotNull(operation, "PendingIntent cannot be null.");
4328 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4329 enforceNetworkRequestPermissions(networkCapabilities);
4330 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004331 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004332 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004333 // TODO : don't forcefully set the UID when communicating with processes
4334 // that have the NETWORK_SETTINGS permission.
4335 networkCapabilities.setSingleUid(Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004336
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004337 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004338 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4339 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004340 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004341 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4342 nri));
4343 return networkRequest;
4344 }
4345
Jeremy Joslin79294842014-12-03 17:15:28 -08004346 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4347 mHandler.sendMessageDelayed(
4348 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4349 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4350 }
4351
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004352 @Override
4353 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004354 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004355 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4356 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004357 }
4358
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004359 // In order to implement the compatibility measure for pre-M apps that call
4360 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4361 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4362 // This ensures it has permission to do so.
4363 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4364 if (nc == null) {
4365 return false;
4366 }
4367 int[] transportTypes = nc.getTransportTypes();
4368 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4369 return false;
4370 }
4371 try {
4372 mContext.enforceCallingOrSelfPermission(
4373 android.Manifest.permission.ACCESS_WIFI_STATE,
4374 "ConnectivityService");
4375 } catch (SecurityException e) {
4376 return false;
4377 }
4378 return true;
4379 }
4380
Robert Greenwalt9258c642014-03-26 16:47:06 -07004381 @Override
4382 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4383 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004384 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4385 enforceAccessPermission();
4386 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004387
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004388 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004389 // TODO : don't forcefully set the UIDs when communicating with processes
4390 // that have the NETWORK_SETTINGS permission.
4391 nc.setSingleUid(Binder.getCallingUid());
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004392 if (!ConnectivityManager.checkChangePermission(mContext)) {
4393 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4394 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4395 // onLost and onAvailable callbacks when networks move in and out of the background.
4396 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4397 // can't request networks.
4398 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4399 }
Etan Cohen859748f2017-04-03 17:42:34 -07004400 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004401
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004402 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004403 NetworkRequest.Type.LISTEN);
4404 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004405 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004406
4407 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4408 return networkRequest;
4409 }
4410
4411 @Override
4412 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4413 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004414 checkNotNull(operation, "PendingIntent cannot be null.");
4415 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4416 enforceAccessPermission();
4417 }
Etan Cohen859748f2017-04-03 17:42:34 -07004418 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004419
Chalard Jeandda156a2018-01-10 21:19:32 +09004420 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4421 // TODO : don't forcefully set the UIDs when communicating with processes
4422 // that have the NETWORK_SETTINGS permission.
4423 nc.setSingleUid(Binder.getCallingUid());
4424
4425 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004426 NetworkRequest.Type.LISTEN);
4427 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004428 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004429
4430 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004431 }
4432
Erik Klineacdd6392016-07-07 16:50:58 +09004433 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004434 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004435 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004436 mHandler.sendMessage(mHandler.obtainMessage(
4437 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004438 }
4439
4440 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004441 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004442 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004443 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4444 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004445 }
4446
Robert Greenwalta67be032014-05-16 15:49:14 -07004447 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004448 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004449 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4450 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4451 }
4452
4453 @Override
4454 public void unregisterNetworkFactory(Messenger messenger) {
4455 enforceConnectivityInternalPermission();
4456 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4457 }
4458
4459 private void handleUnregisterNetworkFactory(Messenger messenger) {
4460 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4461 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004462 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004463 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004464 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004465 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004466 }
4467
Robert Greenwalt7b816022014-04-18 15:25:25 -07004468 /**
4469 * NetworkAgentInfo supporting a request by requestId.
4470 * These have already been vetted (their Capabilities satisfy the request)
4471 * and the are the highest scored network available.
4472 * the are keyed off the Requests requestId.
4473 */
Hugo Benichicd952782017-09-20 11:20:14 +09004474 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4475 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4477 new SparseArray<NetworkAgentInfo>();
4478
Paul Jensen31a94f42015-02-13 14:18:39 -05004479 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4480 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004481 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4482 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004483 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4484 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4485 // there may not be a strict 1:1 correlation between the two.
4486 @GuardedBy("mNetworkForNetId")
4487 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004488
Robert Greenwalt7b816022014-04-18 15:25:25 -07004489 // NetworkAgentInfo keyed off its connecting messenger
4490 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004491 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4493 new HashMap<Messenger, NetworkAgentInfo>();
4494
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004495 @GuardedBy("mBlockedAppUids")
4496 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4497
Paul Jensen2c311d62014-11-17 12:34:51 -05004498 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004499 private final NetworkRequest mDefaultRequest;
4500
Erik Klineda4bfa82015-04-30 12:58:40 +09004501 // Request used to optionally keep mobile data active even when higher
4502 // priority networks like Wi-Fi are active.
4503 private final NetworkRequest mDefaultMobileDataRequest;
4504
Hugo Benichicd952782017-09-20 11:20:14 +09004505 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4506 synchronized (mNetworkForRequestId) {
4507 return mNetworkForRequestId.get(requestId);
4508 }
4509 }
4510
4511 private void clearNetworkForRequest(int requestId) {
4512 synchronized (mNetworkForRequestId) {
4513 mNetworkForRequestId.remove(requestId);
4514 }
4515 }
4516
4517 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4518 synchronized (mNetworkForRequestId) {
4519 mNetworkForRequestId.put(requestId, nai);
4520 }
4521 }
4522
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004523 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004524 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004525 }
4526
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004527 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004528 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004529 }
4530
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004531 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4532 return nri.request.requestId == mDefaultRequest.requestId;
4533 }
4534
Paul Jensen31a94f42015-02-13 14:18:39 -05004535 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004536 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004537 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004538 enforceConnectivityInternalPermission();
4539
Rubin Xu1bb5c082017-09-05 18:40:49 +01004540 LinkProperties lp = new LinkProperties(linkProperties);
4541 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004542 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4543 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004544 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004545 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4546 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004547 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004548 synchronized (this) {
4549 nai.networkMonitor.systemReady = mSystemReady;
4550 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004551 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4552 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004553 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004554 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004555 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004556 }
4557
4558 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4559 if (VDBG) log("Got NetworkAgent Messenger");
4560 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004561 synchronized (mNetworkForNetId) {
4562 mNetworkForNetId.put(na.network.netId, na);
4563 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004564 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4565 NetworkInfo networkInfo = na.networkInfo;
4566 na.networkInfo = null;
4567 updateNetworkInfo(na, networkInfo);
Chalard Jeanf213ca12018-01-16 18:43:05 +09004568 updateUids(na, null, na.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004569 }
4570
4571 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4572 LinkProperties newLp = networkAgent.linkProperties;
4573 int netId = networkAgent.network.netId;
4574
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004575 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4576 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004577 if (networkAgent.clatd != null) {
4578 networkAgent.clatd.fixupLinkProperties(oldLp);
4579 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004580
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004581 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004582 updateMtu(newLp, oldLp);
4583 // TODO - figure out what to do for clat
4584// for (LinkProperties lp : newLp.getStackedLinks()) {
4585// updateMtu(lp, null);
4586// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004587 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004588
Erik Kline94887872016-04-05 13:30:49 +09004589 updateRoutes(newLp, oldLp, netId);
4590 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004591
Hugo Benichi6f62b732017-06-27 15:13:20 +09004592 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004593 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004594 if (isDefaultNetwork(networkAgent)) {
4595 handleApplyDefaultProxy(newLp.getHttpProxy());
4596 } else {
4597 updateProxy(newLp, oldLp, networkAgent);
4598 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004599 // TODO - move this check to cover the whole function
4600 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004601 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004602 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4603 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004604
4605 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004606 }
4607
Joel Scherpelz668370b2017-06-08 15:35:21 +09004608 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004609 // Marks are only available on WiFi interaces. Checking for
4610 // marks on unsupported interfaces is harmless.
4611 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4612 return;
4613 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004614
Joel Scherpelz668370b2017-06-08 15:35:21 +09004615 int mark = mContext.getResources().getInteger(
4616 com.android.internal.R.integer.config_networkWakeupPacketMark);
4617 int mask = mContext.getResources().getInteger(
4618 com.android.internal.R.integer.config_networkWakeupPacketMask);
4619
4620 // Mask/mark of zero will not detect anything interesting.
4621 // Don't install rules unless both values are nonzero.
4622 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004623 return;
4624 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004625
4626 final String prefix = "iface:" + iface;
4627 try {
4628 if (add) {
4629 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4630 } else {
4631 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4632 }
4633 } catch (Exception e) {
4634 loge("Exception modifying wakeup packet monitoring: " + e);
4635 }
4636
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004637 }
4638
4639 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4640 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004641 CompareResult<String> interfaceDiff = new CompareResult<String>(
4642 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4643 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004644 for (String iface : interfaceDiff.added) {
4645 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004646 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004647 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004648 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004649 } catch (Exception e) {
4650 loge("Exception adding interface: " + e);
4651 }
4652 }
4653 for (String iface : interfaceDiff.removed) {
4654 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004655 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004656 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004657 mNetd.removeInterfaceFromNetwork(iface, netId);
4658 } catch (Exception e) {
4659 loge("Exception removing interface: " + e);
4660 }
4661 }
4662 }
4663
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004664 /**
4665 * Have netd update routes from oldLp to newLp.
4666 * @return true if routes changed between oldLp and newLp
4667 */
4668 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004669 // Compare the route diff to determine which routes should be added and removed.
4670 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4671 oldLp != null ? oldLp.getAllRoutes() : null,
4672 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004673
4674 // add routes before removing old in case it helps with continuous connectivity
4675
4676 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4677 for (RouteInfo route : routeDiff.added) {
4678 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004679 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004680 try {
4681 mNetd.addRoute(netId, route);
4682 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004683 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4684 loge("Exception in addRoute for non-gateway: " + e);
4685 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004686 }
4687 }
4688 for (RouteInfo route : routeDiff.added) {
4689 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004690 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004691 try {
4692 mNetd.addRoute(netId, route);
4693 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004694 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4695 loge("Exception in addRoute for gateway: " + e);
4696 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004697 }
4698 }
4699
4700 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004701 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004702 try {
4703 mNetd.removeRoute(netId, route);
4704 } catch (Exception e) {
4705 loge("Exception in removeRoute: " + e);
4706 }
4707 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004708 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004709 }
Erik Kline41368502015-06-17 13:19:54 +09004710
Erik Kline94887872016-04-05 13:30:49 +09004711 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4712 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4713 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004714 }
Erik Kline94887872016-04-05 13:30:49 +09004715
Erik Kline1742fe12017-12-13 19:40:49 +09004716 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4717 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4718
Erik Klinea24d4592018-01-11 21:07:29 +09004719 if (DBG) {
4720 final Collection<InetAddress> dnses = newLp.getDnsServers();
4721 log("Setting DNS servers for network " + netId + " to " + dnses);
4722 }
Erik Kline94887872016-04-05 13:30:49 +09004723 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004724 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004725 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004726 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004727 }
Erik Kline4edba012017-04-07 15:29:29 +09004728 }
4729
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004730 private String getNetworkPermission(NetworkCapabilities nc) {
4731 // TODO: make these permission strings AIDL constants instead.
4732 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4733 return NetworkManagementService.PERMISSION_SYSTEM;
4734 }
4735 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4736 return NetworkManagementService.PERMISSION_NETWORK;
4737 }
4738 return null;
4739 }
4740
Paul Jensen3d194ea2015-06-16 14:27:36 -04004741 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004742 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4743 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4744 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004745 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004746 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004747 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004748 if (nai.everConnected &&
4749 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4750 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004751 // does not cause any request (that is not a listen) currently matching that agent to
4752 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004753 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichi683ea482017-07-25 11:40:56 +09004754 if (!TextUtils.isEmpty(diff)) {
Hugo Benichi86fc53a2017-08-16 13:19:04 +09004755 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichi683ea482017-07-25 11:40:56 +09004756 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004757 }
4758
Paul Jensen3d194ea2015-06-16 14:27:36 -04004759 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004760 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004761 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004762 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004763 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004764 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004765 }
Paul Jensene0988542015-06-25 15:30:08 -04004766 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004767 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004768 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004769 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004770 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004771 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004772 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004773 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004774 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004775 }
4776
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004777 return newNc;
4778 }
4779
4780 /**
4781 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4782 *
4783 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4784 * capabilities we manage and store in {@code nai}, such as validated status and captive
4785 * portal status)
4786 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4787 * potentially triggers rematches.
4788 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4789 * change.)
4790 *
4791 * @param oldScore score of the network before any of the changes that prompted us
4792 * to call this function.
4793 * @param nai the network having its capabilities updated.
4794 * @param nc the new network capabilities.
4795 */
4796 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4797 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4798
4799 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004800
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004801 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004802 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004803 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004804 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004805 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004806 } catch (RemoteException e) {
4807 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004808 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004809 }
4810
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004811 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004812 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004813 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004814 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004815 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004816
Chalard Jeanf213ca12018-01-16 18:43:05 +09004817 updateUids(nai, prevNc, newNc);
4818
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004819 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004820 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4821 // the change we're processing can't affect any requests, it can only affect the listens
4822 // on this network. We might have been called by rematchNetworkAndRequests when a
4823 // network changed foreground state.
4824 processListenRequests(nai, true);
4825 } else {
4826 // If the requestable capabilities have changed or the score changed, we can't have been
4827 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004828 rematchAllNetworksAndRequests(nai, oldScore);
4829 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004830 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004831
4832 // Report changes that are interesting for network statistics tracking.
4833 if (prevNc != null) {
4834 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004835 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004836 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004837 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004838 if (meteredChanged || roamingChanged) {
4839 notifyIfacesChangedForNetworkStats();
4840 }
4841 }
4842
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004843 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004844 // Tell VPNs about updated capabilities, since they may need to
4845 // bubble those changes through.
4846 synchronized (mVpns) {
4847 for (int i = 0; i < mVpns.size(); i++) {
4848 final Vpn vpn = mVpns.valueAt(i);
4849 vpn.updateCapabilities();
4850 }
4851 }
4852 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004853 }
4854
Chalard Jeanf213ca12018-01-16 18:43:05 +09004855 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4856 NetworkCapabilities newNc) {
4857 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4858 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4859 if (null == prevRanges) prevRanges = new ArraySet<>();
4860 if (null == newRanges) newRanges = new ArraySet<>();
4861 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4862
4863 prevRanges.removeAll(newRanges);
4864 newRanges.removeAll(prevRangesCopy);
4865
4866 try {
4867 if (!newRanges.isEmpty()) {
4868 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4869 newRanges.toArray(addedRangesArray);
4870 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4871 }
4872 if (!prevRanges.isEmpty()) {
4873 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4874 prevRanges.toArray(removedRangesArray);
4875 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4876 }
4877 } catch (Exception e) {
4878 // Never crash!
4879 loge("Exception in updateUids: " + e);
4880 }
4881 }
4882
Hugo Benichief502882017-09-01 01:23:32 +00004883 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4884 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4885 // Ignore updates for disconnected networks
4886 return;
4887 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004888 // newLp is already a defensive copy.
4889 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004890 if (VDBG) {
4891 log("Update of LinkProperties for " + nai.name() +
4892 "; created=" + nai.created +
4893 "; everConnected=" + nai.everConnected);
4894 }
4895 LinkProperties oldLp = nai.linkProperties;
4896 synchronized (nai) {
4897 nai.linkProperties = newLp;
4898 }
4899 if (nai.everConnected) {
4900 updateLinkProperties(nai, oldLp);
4901 }
4902 }
4903
Paul Jensenc8b9a742014-09-30 15:37:41 -04004904 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004905 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4906 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004907 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004908 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004909 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4910 }
4911 }
4912
Robert Greenwalt7b816022014-04-18 15:25:25 -07004913 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4914 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004915 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004916 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4917 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004918 }
4919 }
4920
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004921 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4922 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004923 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004924 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004925 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4926 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004927 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004928 sendIntent(nri.mPendingIntent, intent);
4929 }
4930 // else not handled
4931 }
4932
4933 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4934 mPendingIntentWakeLock.acquire();
4935 try {
4936 if (DBG) log("Sending " + pendingIntent);
4937 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4938 } catch (PendingIntent.CanceledException e) {
4939 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4940 mPendingIntentWakeLock.release();
4941 releasePendingNetworkRequest(pendingIntent);
4942 }
4943 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4944 }
4945
4946 @Override
4947 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4948 String resultData, Bundle resultExtras) {
4949 if (DBG) log("Finished sending " + pendingIntent);
4950 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004951 // Release with a delay so the receiving client has an opportunity to put in its
4952 // own request.
4953 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004954 }
4955
Hugo Benichidba33db2017-03-23 22:40:44 +09004956 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004957 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004958 if (nri.messenger == null) {
4959 return; // Default request has no msgr
4960 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004961 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004962 // TODO: check if defensive copies of data is needed.
4963 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004964 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004965 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4966 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004967 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004968 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004969 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004970 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004971 break;
4972 }
4973 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeandda156a2018-01-10 21:19:32 +09004974 final NetworkCapabilities nc =
4975 new NetworkCapabilities(networkAgent.networkCapabilities);
4976 // TODO : don't remove the UIDs when communicating with processes
4977 // that have the NETWORK_SETTINGS permission.
4978 nc.setSingleUid(nri.mUid);
4979 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004980 break;
4981 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004982 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004983 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004984 break;
4985 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004986 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004987 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004988 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004989 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004990 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004991 String notification = ConnectivityManager.getCallbackName(notificationType);
4992 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004993 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004994 nri.messenger.send(msg);
4995 } catch (RemoteException e) {
4996 // may occur naturally in the race of binder death.
4997 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4998 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004999 }
5000
Hugo Benichidba33db2017-03-23 22:40:44 +09005001 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
5002 bundle.putParcelable(t.getClass().getSimpleName(), t);
5003 }
5004
Paul Jensenc8b9a742014-09-30 15:37:41 -04005005 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005006 if (nai.numRequestNetworkRequests() != 0) {
5007 for (int i = 0; i < nai.numNetworkRequests(); i++) {
5008 NetworkRequest nr = nai.requestAt(i);
5009 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09005010 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005011 loge("Dead network still had at least " + nr);
5012 break;
5013 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005014 }
5015 nai.asyncChannel.disconnect();
5016 }
5017
Robert Greenwalt7b816022014-04-18 15:25:25 -07005018 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
5019 if (oldNetwork == null) {
5020 loge("Unknown NetworkAgentInfo in handleLingerComplete");
5021 return;
5022 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04005023 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005024
5025 // If we get here it means that the last linger timeout for this network expired. So there
5026 // must be no other active linger timers, and we must stop lingering.
5027 oldNetwork.clearLingerState();
5028
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005029 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005030 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005031 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005032 } else {
5033 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005034 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5035 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005036 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005037 }
5038
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005039 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005040 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005041 setupDataActivityTracking(newNetwork);
5042 try {
5043 mNetd.setDefaultNetId(newNetwork.network.netId);
5044 } catch (Exception e) {
5045 loge("Exception setting default network :" + e);
5046 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005047
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005048 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005049 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005050 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005051 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005052 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005053 }
5054
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005055 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005056 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5057 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5058 NetworkRequest nr = nri.request;
5059 if (!nr.isListen()) continue;
5060 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5061 nai.removeRequest(nri.request.requestId);
5062 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5063 }
5064 }
5065
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005066 if (capabilitiesChanged) {
5067 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5068 }
5069
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005070 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5071 NetworkRequest nr = nri.request;
5072 if (!nr.isListen()) continue;
5073 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5074 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005075 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005076 }
5077 }
5078 }
5079
Paul Jensen2161a8e2014-09-11 11:00:39 -04005080 // Handles a network appearing or improving its score.
5081 //
5082 // - Evaluates all current NetworkRequests that can be
5083 // satisfied by newNetwork, and reassigns to newNetwork
5084 // any such requests for which newNetwork is the best.
5085 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005086 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005087 // needed. A network is needed if it is the best network for
5088 // one or more NetworkRequests, or if it is a VPN.
5089 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005090 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005091 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005092 //
5093 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5094 // networks that have no chance (i.e. even if validated)
5095 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005096 //
5097 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5098 // it does not remove NetworkRequests that other Networks could better satisfy.
5099 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5100 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5101 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005102 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005103 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005104 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5105 // performed to tear down unvalidated networks that have no chance (i.e. even if
5106 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005107 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005108 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005109 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005110 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005111 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005112 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005113
5114 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5115 final int score = newNetwork.getCurrentScore();
5116
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005117 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005118
Paul Jensen2161a8e2014-09-11 11:00:39 -04005119 // Find and migrate to this Network any NetworkRequests for
5120 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005121 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005122 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005123 NetworkCapabilities nc = newNetwork.networkCapabilities;
5124 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005125 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005126 // Process requests in the first pass and listens in the second pass. This allows us to
5127 // change a network's capabilities depending on which requests it has. This is only
5128 // correct if the change in capabilities doesn't affect whether the network satisfies
5129 // requests or not, and doesn't affect the network's score.
5130 if (nri.request.isListen()) continue;
5131
Hugo Benichicd952782017-09-20 11:20:14 +09005132 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005133 final boolean satisfies = newNetwork.satisfies(nri.request);
5134 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005135 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005136 log("Network " + newNetwork.name() + " was already satisfying" +
5137 " request " + nri.request.requestId + ". No change.");
5138 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005139 keep = true;
5140 continue;
5141 }
5142
5143 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005144 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005145 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005146 // next check if it's better than any current network we're using for
5147 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005148 if (VDBG) {
5149 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005150 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005151 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005152 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005153 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005154 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005155 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005156 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005157 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005158 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005159 affectedNetworks.add(currentNetwork);
5160 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005161 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005162 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005163 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005164 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005165 if (!newNetwork.addRequest(nri.request)) {
5166 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5167 }
5168 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005169 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005170 // Tell NetworkFactories about the new score, so they can stop
5171 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005172 // TODO - this could get expensive if we have alot of requests for this
5173 // network. Think about if there is a way to reduce this. Push
5174 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005175 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005176 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005177 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005178 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005179 if (currentNetwork != null) {
5180 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5181 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005182 }
5183 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005184 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005185 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5186 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005187 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005188 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5189 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5190 // This means this code doesn't have to handle the case where "currentNetwork" no
5191 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5192 if (DBG) {
5193 log("Network " + newNetwork.name() + " stopped satisfying" +
5194 " request " + nri.request.requestId);
5195 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005196 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005197 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005198 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005199 sendUpdatedScoreToFactories(nri.request, 0);
5200 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005201 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5202 newNetwork.name() +
5203 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005204 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005205 // TODO: Technically, sending CALLBACK_LOST here is
5206 // incorrect if there is a replacement network currently
5207 // connected that can satisfy nri, which is a request
5208 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005209 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5210 // so this code is only incorrect for a network that loses
5211 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005212 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005213 }
5214 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005215 if (isNewDefault) {
5216 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005217 makeDefault(newNetwork);
5218 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005219 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005220 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005221 // Have a new default network, release the transition wakelock in
5222 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005223 }
5224
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005225 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5226 Slog.wtf(TAG, String.format(
5227 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005228 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005229 }
5230 if (newNetwork.getCurrentScore() != score) {
5231 Slog.wtf(TAG, String.format(
5232 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005233 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005234 }
5235
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005236 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005237 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5238 // If the network went from background to foreground or vice versa, we need to update
5239 // its foreground state. It is safe to do this after rematching the requests because
5240 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5241 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005242 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005243 } else {
5244 processListenRequests(newNetwork, false);
5245 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005246
Paul Jensencf4c2c62015-07-01 14:16:32 -04005247 // do this after the default net is switched, but
5248 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005249 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005250
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005251 // Linger any networks that are no longer needed. This should be done after sending the
5252 // available callback for newNetwork.
5253 for (NetworkAgentInfo nai : affectedNetworks) {
5254 updateLingerState(nai, now);
5255 }
5256 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5257 // does not need to be done in any particular order.
5258 updateLingerState(newNetwork, now);
5259
Paul Jensencf4c2c62015-07-01 14:16:32 -04005260 if (isNewDefault) {
5261 // Maintain the illusion: since the legacy API only
5262 // understands one network at a time, we must pretend
5263 // that the current default network disconnected before
5264 // the new one connected.
5265 if (oldDefaultNetwork != null) {
5266 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5267 oldDefaultNetwork, true);
5268 }
5269 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5270 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5271 notifyLockdownVpn(newNetwork);
5272 }
5273
Robert Greenwalt7b816022014-04-18 15:25:25 -07005274 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005275 // Notify battery stats service about this network, both the normal
5276 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005277 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005278 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005279 final IBatteryStats bs = BatteryStatsService.getService();
5280 final int type = newNetwork.networkInfo.getType();
5281
5282 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5283 bs.noteNetworkInterfaceType(baseIface, type);
5284 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5285 final String stackedIface = stacked.getInterfaceName();
5286 bs.noteNetworkInterfaceType(stackedIface, type);
5287 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5288 }
5289 } catch (RemoteException ignored) {
5290 }
5291
Robert Greenwalt152ed372014-12-17 17:19:53 -08005292 // This has to happen after the notifyNetworkCallbacks as that tickles each
5293 // ConnectivityManager instance so that legacy requests correctly bind dns
5294 // requests to this network. The legacy users are listening for this bcast
5295 // and will generally do a dns request so they can ensureRouteToHost and if
5296 // they do that before the callbacks happen they'll use the default network.
5297 //
5298 // TODO: Is there still a race here? We send the broadcast
5299 // after sending the callback, but if the app can receive the
5300 // broadcast before the callback, it might still break.
5301 //
5302 // This *does* introduce a race where if the user uses the new api
5303 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5304 // they may get old info. Reverse this after the old startUsing api is removed.
5305 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005306 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5307 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005308 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005309 // legacy type tracker filters out repeat adds
5310 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5311 }
5312 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005313
5314 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5315 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5316 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5317 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5318 if (newNetwork.isVPN()) {
5319 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5320 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005321 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005322 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5323 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005324 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005325 if (nai.getLingerExpiry() > 0) {
5326 // This network has active linger timers and no requests, but is not
5327 // lingering. Linger it.
5328 //
5329 // One way (the only way?) this can happen if this network is unvalidated
5330 // and became unneeded due to another network improving its score to the
5331 // point where this network will no longer be able to satisfy any requests
5332 // even if it validates.
5333 updateLingerState(nai, now);
5334 } else {
5335 if (DBG) log("Reaping " + nai.name());
5336 teardownUnneededNetwork(nai);
5337 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005338 }
5339 }
5340 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005341 }
5342
Paul Jensen1c7ba022015-06-16 14:27:36 -04005343 /**
5344 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5345 * being disconnected.
5346 * @param changed If only one Network's score or capabilities have been modified since the last
5347 * time this function was called, pass this Network in this argument, otherwise pass
5348 * null.
5349 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5350 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5351 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5352 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5353 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005354 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005355 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005356 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5357 // to avoid the slowness. It is not simply enough to process just "changed", for
5358 // example in the case where "changed"'s score decreases and another network should begin
5359 // satifying a NetworkRequest that "changed" currently satisfies.
5360
5361 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5362 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5363 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005364 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005365 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005366 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005367 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005368 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5369 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5370 // Rematch higher scoring networks first to prevent requests first matching a lower
5371 // scoring network and then a higher scoring network, which could produce multiple
5372 // callbacks and inadvertently unlinger networks.
5373 Arrays.sort(nais);
5374 for (NetworkAgentInfo nai : nais) {
5375 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005376 // Only reap the last time through the loop. Reaping before all rematching
5377 // is complete could incorrectly teardown a network that hasn't yet been
5378 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005379 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005380 : ReapUnvalidatedNetworks.REAP,
5381 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005382 }
5383 }
5384 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005385
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005386 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005387 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005388 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005389 // For now only update icons for default connection.
5390 // TODO: Update WiFi and cellular icons separately. b/17237507
5391 if (!isDefaultNetwork(nai)) return;
5392
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005393 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005394 // Don't repeat publish.
5395 if (newInetCondition == mDefaultInetConditionPublished) return;
5396
5397 mDefaultInetConditionPublished = newInetCondition;
5398 sendInetConditionBroadcast(nai.networkInfo);
5399 }
5400
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005401 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005402 synchronized (mVpns) {
5403 if (mLockdownTracker != null) {
5404 if (nai != null && nai.isVPN()) {
5405 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5406 } else {
5407 mLockdownTracker.onNetworkInfoChanged();
5408 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005409 }
5410 }
5411 }
5412
Robert Greenwalt7b816022014-04-18 15:25:25 -07005413 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005414 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005415 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005416 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005417 synchronized (networkAgent) {
5418 oldInfo = networkAgent.networkInfo;
5419 networkAgent.networkInfo = newInfo;
5420 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005421 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005422
Robert Greenwalt7b816022014-04-18 15:25:25 -07005423 if (DBG) {
5424 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5425 (oldInfo == null ? "null" : oldInfo.getState()) +
5426 " to " + state);
5427 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005428
Robin Lee585e2482016-05-01 23:00:00 +01005429 if (!networkAgent.created
5430 && (state == NetworkInfo.State.CONNECTED
5431 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005432
5433 // A network that has just connected has zero requests and is thus a foreground network.
5434 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5435
Robert Greenwalt7b816022014-04-18 15:25:25 -07005436 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005437 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005438 if (networkAgent.isVPN()) {
5439 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005440 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5441 (networkAgent.networkMisc == null ||
5442 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005443 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005444 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005445 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005446 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005447 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005448 loge("Error creating network " + networkAgent.network.netId + ": "
5449 + e.getMessage());
5450 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005451 }
Paul Jenseneec75412014-08-04 12:21:19 -04005452 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005453 }
5454
5455 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5456 networkAgent.everConnected = true;
5457
Robert Greenwalt7b816022014-04-18 15:25:25 -07005458 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005459 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005460
Paul Jensenca8f16a2014-05-09 12:47:55 -04005461 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005462 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005463
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005464 if (networkAgent.isVPN()) {
5465 // Temporarily disable the default proxy (not global).
5466 synchronized (mProxyLock) {
5467 if (!mDefaultProxyDisabled) {
5468 mDefaultProxyDisabled = true;
5469 if (mGlobalProxy == null && mDefaultProxy != null) {
5470 sendProxyBroadcast(null);
5471 }
5472 }
5473 }
5474 // TODO: support proxy per network.
5475 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005476
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005477 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5478 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5479 // capabilities, so it only needs to be done once on initial connect, not every time the
5480 // network's capabilities change. Note that we do this before rematching the network,
5481 // so we could decide to tear it down immediately afterwards. That's fine though - on
5482 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5483 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005484 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005485
Paul Jensen2161a8e2014-09-11 11:00:39 -04005486 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005487 final long now = SystemClock.elapsedRealtime();
5488 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005489
5490 // This has to happen after matching the requests, because callbacks are just requests.
5491 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005492 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005493 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005494 if (networkAgent.isVPN()) {
5495 synchronized (mProxyLock) {
5496 if (mDefaultProxyDisabled) {
5497 mDefaultProxyDisabled = false;
5498 if (mGlobalProxy == null && mDefaultProxy != null) {
5499 sendProxyBroadcast(mDefaultProxy);
5500 }
5501 }
5502 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005503 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005504 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005505 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5506 state == NetworkInfo.State.SUSPENDED) {
5507 // going into or coming out of SUSPEND: rescore and notify
5508 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005509 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005510 }
5511 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5512 ConnectivityManager.CALLBACK_SUSPENDED :
5513 ConnectivityManager.CALLBACK_RESUMED));
5514 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005515 }
5516 }
5517
Robert Greenwaltac96c522014-06-03 16:43:57 -07005518 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005519 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005520 if (score < 0) {
5521 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5522 "). Bumping score to min of 0");
5523 score = 0;
5524 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005525
Paul Jensen2161a8e2014-09-11 11:00:39 -04005526 final int oldScore = nai.getCurrentScore();
5527 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005528
Paul Jensen85cf78e2015-06-25 13:25:07 -04005529 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005530
Paul Jensenc8b9a742014-09-30 15:37:41 -04005531 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005532 }
5533
Erik Klinec75d4fa2017-02-15 19:59:17 +09005534 // Notify only this one new request of the current state. Transfer all the
5535 // current state by calling NetworkCapabilities and LinkProperties callbacks
5536 // so that callers can be guaranteed to have as close to atomicity in state
5537 // transfer as can be supported by this current API.
5538 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005539 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005540 if (nri.mPendingIntent != null) {
5541 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5542 // Attempt no subsequent state pushes where intents are involved.
5543 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005544 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005545
5546 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5547 // Whether a network is currently suspended is also an important
5548 // element of state to be transferred (it would not otherwise be
5549 // delivered by any currently available mechanism).
5550 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5551 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5552 }
5553 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5554 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005555 }
5556
Robert Greenwalt8d482522015-06-24 13:23:42 -07005557 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005558 // The NetworkInfo we actually send out has no bearing on the real
5559 // state of affairs. For example, if the default connection is mobile,
5560 // and a request for HIPRI has just gone away, we need to pretend that
5561 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5562 // the state to DISCONNECTED, even though the network is of type MOBILE
5563 // and is still connected.
5564 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5565 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005566 if (state != DetailedState.DISCONNECTED) {
5567 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005568 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005569 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005570 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005571 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5572 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5573 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5574 if (info.isFailover()) {
5575 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5576 nai.networkInfo.setFailover(false);
5577 }
5578 if (info.getReason() != null) {
5579 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5580 }
5581 if (info.getExtraInfo() != null) {
5582 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5583 }
5584 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005585 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005586 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005587 if (newDefaultAgent != null) {
5588 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5589 newDefaultAgent.networkInfo);
5590 } else {
5591 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5592 }
5593 }
5594 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5595 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005596 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005597 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005598 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005599 }
5600 }
5601 }
5602
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005603 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005604 if (VDBG) {
5605 String notification = ConnectivityManager.getCallbackName(notifyType);
5606 log("notifyType " + notification + " for " + networkAgent.name());
5607 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005608 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5609 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005610 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5611 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005612 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5613 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005614 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005615 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005616 } else {
5617 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5618 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005619 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005620 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005621
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005622 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5623 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5624 }
5625
Jeff Sharkey69736342014-12-08 14:50:12 -08005626 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005627 * Returns the list of all interfaces that could be used by network traffic that does not
5628 * explicitly specify a network. This includes the default network, but also all VPNs that are
5629 * currently connected.
5630 *
5631 * Must be called on the handler thread.
5632 */
5633 private Network[] getDefaultNetworks() {
5634 ArrayList<Network> defaultNetworks = new ArrayList<>();
5635 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5636 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5637 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5638 defaultNetworks.add(nai.network);
5639 }
5640 }
5641 return defaultNetworks.toArray(new Network[0]);
5642 }
5643
5644 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005645 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5646 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005647 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005648 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005649 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005650 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005651 } catch (Exception ignored) {
5652 }
5653 }
5654
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005655 @Override
5656 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005657 int user = UserHandle.getUserId(Binder.getCallingUid());
5658 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005659 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005660 return mVpns.get(user).addAddress(address, prefixLength);
5661 }
5662 }
5663
5664 @Override
5665 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005666 int user = UserHandle.getUserId(Binder.getCallingUid());
5667 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005668 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005669 return mVpns.get(user).removeAddress(address, prefixLength);
5670 }
5671 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005672
5673 @Override
5674 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005675 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005676 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005677 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005678 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005679 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005680 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005681 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005682 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005683 }
5684 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005685 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005686
5687 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005688 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005689 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005690 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005691 }
5692
5693 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005694 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5695 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5696 enforceKeepalivePermission();
5697 mKeepaliveTracker.startNattKeepalive(
5698 getNetworkAgentInfoForNetwork(network),
5699 intervalSeconds, messenger, binder,
5700 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5701 }
5702
5703 @Override
5704 public void stopKeepalive(Network network, int slot) {
5705 mHandler.sendMessage(mHandler.obtainMessage(
5706 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5707 }
5708
5709 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005710 public void factoryReset() {
5711 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005712
5713 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5714 return;
5715 }
5716
Robin Lee3b3dd942015-05-12 18:14:58 +01005717 final int userId = UserHandle.getCallingUserId();
5718
Stuart Scottf1fb3972015-04-02 18:00:02 -07005719 // Turn airplane mode off
5720 setAirplaneMode(false);
5721
Stuart Scotte3e314d2015-04-20 14:07:45 -07005722 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5723 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005724 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005725 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005726 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005727 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005728 }
5729
Stuart Scotte3e314d2015-04-20 14:07:45 -07005730 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005731 // Remove always-on package
5732 synchronized (mVpns) {
5733 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5734 if (alwaysOnPackage != null) {
5735 setAlwaysOnVpnPackage(userId, null, false);
5736 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5737 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005738
Hugo Benichi69744342017-11-27 10:57:16 +09005739 // Turn Always-on VPN off
5740 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5741 final long ident = Binder.clearCallingIdentity();
5742 try {
5743 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5744 mLockdownEnabled = false;
5745 setLockdownTracker(null);
5746 } finally {
5747 Binder.restoreCallingIdentity(ident);
5748 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005749 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005750
Hugo Benichi69744342017-11-27 10:57:16 +09005751 // Turn VPN off
5752 VpnConfig vpnConfig = getVpnConfig(userId);
5753 if (vpnConfig != null) {
5754 if (vpnConfig.legacy) {
5755 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5756 } else {
5757 // Prevent this app (packagename = vpnConfig.user) from initiating
5758 // VPN connections in the future without user intervention.
5759 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005760
Hugo Benichi69744342017-11-27 10:57:16 +09005761 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5762 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005763 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005764 }
5765 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005766
5767 Settings.Global.putString(mContext.getContentResolver(),
5768 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005769 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005770
Ricky Wai44dcbde2018-01-23 04:09:45 +00005771 @Override
5772 public byte[] getNetworkWatchlistConfigHash() {
5773 NetworkWatchlistManager nwm = mContext.getSystemService(NetworkWatchlistManager.class);
5774 if (nwm == null) {
5775 loge("Unable to get NetworkWatchlistManager");
5776 return null;
5777 }
5778 // Redirect it to network watchlist service to access watchlist file and calculate hash.
5779 return nwm.getWatchlistConfigHash();
5780 }
5781
Paul Jensencf4c2c62015-07-01 14:16:32 -04005782 @VisibleForTesting
5783 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5784 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5785 return new NetworkMonitor(context, handler, nai, defaultRequest);
5786 }
Erik Kline48f12f22016-04-14 17:30:59 +09005787
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005788 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005789 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5790 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005791 }
5792
5793 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005794 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5795 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5796 }
5797
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005798 @VisibleForTesting
5799 public boolean hasService(String name) {
5800 return ServiceManager.checkService(name) != null;
5801 }
5802
Hugo Benichi64901e52017-10-19 14:42:40 +09005803 @VisibleForTesting
5804 protected IpConnectivityMetrics.Logger metricsLogger() {
5805 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5806 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005807 }
5808
5809 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005810 int[] transports = nai.networkCapabilities.getTransportTypes();
5811 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005812 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005813
5814 private static boolean toBool(int encodedBoolean) {
5815 return encodedBoolean != 0; // Only 0 means false.
5816 }
5817
5818 private static int encodeBool(boolean b) {
5819 return b ? 1 : 0;
5820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005821}