blob: fd2ef18d624a8d00d5067b500659fc78ae05331e [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 Jean804b8fb2018-01-30 22:41:41 +090033import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_SUSPENDED;
Chalard Jeandda156a2018-01-10 21:19:32 +090034import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_VPN;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090035import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey72f9c422017-10-27 17:22:59 -060036import static android.net.NetworkCapabilities.TRANSPORT_VPN;
37
Hugo Benichia0385682017-03-22 17:07:57 +090038import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060039
Wenchao Tongf5ea3402015-03-04 13:26:38 -080040import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080041import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090042import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070043import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.ContentResolver;
46import android.content.Context;
47import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070048import android.content.IntentFilter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070049import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070050import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090052import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080053import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070054import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070055import android.net.INetworkPolicyListener;
56import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070057import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080058import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070059import android.net.LinkProperties.CompareResult;
Hugo Benichib577d652017-06-27 15:13:20 +090060import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070061import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070062import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070063import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070064import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080065import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070066import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070067import android.net.NetworkMisc;
Jeff Sharkey75d31892018-01-18 22:01:59 +090068import android.net.NetworkPolicyManager;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070069import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070070import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070071import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070072import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070073import android.net.NetworkUtils;
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 Hea0a87e82017-05-15 17:07:18 +0100141import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700142import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700143import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600144import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400145import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900146import com.android.server.connectivity.NetworkNotificationManager;
147import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400148import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700149import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800150import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700151import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900152import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700153import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700154import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900155import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600156
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700157import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700158
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700159import org.xmlpull.v1.XmlPullParser;
160import org.xmlpull.v1.XmlPullParserException;
161
162import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700164import java.io.FileNotFoundException;
165import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700166import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700168import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700169import java.net.InetAddress;
170import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700171import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700172import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700173import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700174import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700175import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700176import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700177import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700178import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700179import java.util.Objects;
Chalard Jeanf213ca12018-01-16 18:43:05 +0900180import java.util.Set;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600181import java.util.SortedSet;
182import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800183
184/**
185 * @hide
186 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800187public class ConnectivityService extends IConnectivityManager.Stub
188 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900189 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190
Erik Kline7747fd42017-05-12 16:52:48 +0900191 public static final String DIAG_ARG = "--diag";
192 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900193 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900194
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900195 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700196 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Jake Hamby786e71a2014-02-06 14:43:50 -0800198 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900199 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700200
Jeff Sharkey899223b2012-08-04 15:24:58 -0700201 // TODO: create better separation between radio types and network types
202
Robert Greenwalt42acef32009-08-12 16:08:25 -0700203 // how long to wait before switching back to a radio's default network
204 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
205 // system property that can override the above value
206 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
207 "android.telephony.apn-restore";
208
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900209 // How long to wait before putting up a "This network doesn't have an Internet connection,
210 // connect anyway?" dialog after the user selects a network that doesn't validate.
211 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
212
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900213 // Default to 30s linger time-out. Modifiable only for testing.
214 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
215 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
216 @VisibleForTesting
217 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
218
Jeremy Joslin79294842014-12-03 17:15:28 -0800219 // How long to delay to removal of a pending intent based request.
220 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
221 private final int mReleasePendingIntentDelayMs;
222
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900223 private MockableSystemProperties mSystemProperties;
224
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800225 private Tethering mTethering;
226
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700227 private final PermissionMonitor mPermissionMonitor;
228
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700229 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700230
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700231 @GuardedBy("mVpns")
232 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700233
Hugo Benichi69744342017-11-27 10:57:16 +0900234 // TODO: investigate if mLockdownEnabled can be removed and replaced everywhere by
235 // a direct call to LockdownVpnTracker.isEnabled().
236 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700237 private boolean mLockdownEnabled;
Hugo Benichi69744342017-11-27 10:57:16 +0900238 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700239 private LockdownVpnTracker mLockdownTracker;
240
Erik Klineda4bfa82015-04-30 12:58:40 +0900241 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800242 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700243 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700244 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800245
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800246 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700247 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800248
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700249 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800250 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700251 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900252 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700253
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700254 private String mCurrentTcpBufferSizes;
255
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700256 private static final int ENABLED = 1;
257 private static final int DISABLED = 0;
258
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900259 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900260 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
261 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900262
Paul Jensenb10e37f2014-11-25 12:33:08 -0500263 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400264 // Tear down networks that have no chance (e.g. even if validated) of becoming
265 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500266 // all networks have been rematched against all NetworkRequests.
267 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400268 // Don't reap networks. This should be passed when some networks have not yet been
269 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500270 DONT_REAP
271 };
272
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900273 private enum UnneededFor {
274 LINGER, // Determine whether this network is unneeded and should be lingered.
275 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
276 }
277
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700278 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700279 * used internally to change our mobile data enabled flag
280 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700281 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700282
283 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700284 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700285 * from one net to another. Clear happens when we get a new
286 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
287 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700288 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700289 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700290
Robert Greenwalt434203a2010-10-11 16:00:27 -0700291 /**
292 * used internally to reload global proxy settings
293 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700294 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700295
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700296 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400297 * PAC manager has received new port.
298 */
299 private static final int EVENT_PROXY_HAS_CHANGED = 16;
300
Robert Greenwalte049c232014-04-11 15:53:27 -0700301 /**
302 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700303 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700304 */
305 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
306
Robert Greenwalt7b816022014-04-18 15:25:25 -0700307 /**
308 * used internally when registering NetworkAgents
309 * obj = Messenger
310 */
311 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
312
Robert Greenwalt9258c642014-03-26 16:47:06 -0700313 /**
314 * used to add a network request
315 * includes a NetworkRequestInfo
316 */
317 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
318
319 /**
320 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900321 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700322 * cancel it.
323 * includes a NetworkRequestInfo
324 */
325 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
326
327 /**
328 * used to add a network listener - no request
329 * includes a NetworkRequestInfo
330 */
331 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
332
333 /**
334 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400335 * arg1 = UID of caller
336 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700337 */
338 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
339
Robert Greenwalta67be032014-05-16 15:49:14 -0700340 /**
341 * used internally when registering NetworkFactories
342 * obj = Messenger
343 */
344 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
345
Robert Greenwalt27711812014-06-25 16:45:57 -0700346 /**
347 * used internally to expire a wakelock when transitioning
348 * from one net to another. Expire happens when we fail to find
349 * a new network (typically after 1 minute) -
350 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
351 * a replacement network.
352 */
353 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
354
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700355 /**
356 * Used internally to indicate the system is ready.
357 */
358 private static final int EVENT_SYSTEM_READY = 25;
359
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800360 /**
361 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400362 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800363 */
364 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
365
366 /**
367 * used to remove a pending intent and its associated network request.
368 * arg1 = UID of caller
369 * obj = PendingIntent
370 */
371 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
372
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900373 /**
374 * used to specify whether a network should be used even if unvalidated.
375 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
376 * arg2 = whether to remember this choice in the future (1 or 0)
377 * obj = network
378 */
379 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
380
381 /**
382 * used to ask the user to confirm a connection to an unvalidated network.
383 * obj = network
384 */
385 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700386
Erik Klineda4bfa82015-04-30 12:58:40 +0900387 /**
388 * used internally to (re)configure mobile data always-on settings.
389 */
390 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
391
Paul Jensen694f2b82015-06-17 14:15:39 -0400392 /**
393 * used to add a network listener with a pending intent
394 * obj = NetworkRequestInfo
395 */
396 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
397
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900398 /**
399 * used to specify whether a network should not be penalized when it becomes unvalidated.
400 */
401 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
402
403 /**
404 * used to trigger revalidation of a network.
405 */
406 private static final int EVENT_REVALIDATE_NETWORK = 36;
407
Erik Klinea24d4592018-01-11 21:07:29 +0900408 // Handle changes in Private DNS settings.
409 private static final int EVENT_PRIVATE_DNS_SETTINGS_CHANGED = 37;
410
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900411 private static String eventName(int what) {
412 return sMagicDecoderRing.get(what, Integer.toString(what));
413 }
414
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900415 /** Handler thread used for both of the handlers below. */
416 @VisibleForTesting
417 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700418 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700419 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700420 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700421 final private NetworkStateTrackerHandler mTrackerHandler;
Erik Kline1742fe12017-12-13 19:40:49 +0900422 private final DnsManager mDnsManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700423
Mike Lockwood0f79b542009-08-14 14:18:49 -0400424 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800425 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400426
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700427 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700428 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800429 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700430
Robert Greenwalt434203a2010-10-11 16:00:27 -0700431 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400432 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700433 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700434 private boolean mDefaultProxyDisabled = false;
435
Robert Greenwalt434203a2010-10-11 16:00:27 -0700436 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400437 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700438
Jason Monk602b2322013-07-03 17:04:33 -0400439 private PacManager mPacManager = null;
440
Erik Klineda4bfa82015-04-30 12:58:40 +0900441 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700442
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400443 private UserManager mUserManager;
444
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700445 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700446 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700447
Robert Greenwalt50393202011-06-21 17:26:14 -0700448 // the set of network types that can only be enabled by system/sig apps
449 List mProtectedNetworks;
450
John Spurlockbf991a82013-06-24 14:20:23 -0400451 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700452
Wink Savilleab9321d2013-06-29 21:10:57 -0700453 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400454
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900455 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900456 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900457 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900458
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700459 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
Benedict Wong8149f6e2018-01-18 18:31:45 -0800460 private static final int MIN_NET_ID = 100; // some reserved marks
461 private static final int MAX_NET_ID = 65535 - 0x0400; // Top 1024 bits reserved by IpSecService
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700462 private int mNextNetId = MIN_NET_ID;
463
Robert Greenwalt34524f02014-05-18 16:22:10 -0700464 // sequence number of NetworkRequests
465 private int mNextNetworkRequestId = 1;
466
Erik Kline7523eb32015-07-09 18:24:03 +0900467 // NetworkRequest activity String log entries.
468 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
469 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
470
Hugo Benichic2ae2872016-07-11 11:05:12 +0900471 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900472 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900473 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
474
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900475 private static final int MAX_WAKELOCK_LOGS = 20;
476 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900477 private int mTotalWakelockAcquisitions = 0;
478 private int mTotalWakelockReleases = 0;
479 private long mTotalWakelockDurationMs = 0;
480 private long mMaxWakelockDurationMs = 0;
481 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900482
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700483 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
484 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400485 private static class ValidationLog {
486 final Network mNetwork;
487 final String mNetworkExtraInfo;
488 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700489
Paul Jensen0808eb82016-06-03 13:51:21 -0400490 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
491 mNetwork = network;
492 mNetworkExtraInfo = networkExtraInfo;
493 mLog = log;
494 }
495 }
496 private final ArrayDeque<ValidationLog> mValidationLogs =
497 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
498
499 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900500 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700501 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
502 mValidationLogs.removeLast();
503 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400504 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700505 }
506 }
507
Hugo Benichif9fdf872016-07-28 17:53:06 +0900508 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900509
Erik Kline065ab6e2016-10-02 18:02:14 +0900510 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900511 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900512
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700513 /**
514 * Implements support for the legacy "one network per network type" model.
515 *
516 * We used to have a static array of NetworkStateTrackers, one for each
517 * network type, but that doesn't work any more now that we can have,
518 * for example, more that one wifi network. This class stores all the
519 * NetworkAgentInfo objects that support a given type, but the legacy
520 * API will only see the first one.
521 *
522 * It serves two main purposes:
523 *
524 * 1. Provide information about "the network for a given type" (since this
525 * API only supports one).
526 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
527 * the first network for a given type changes, or if the default network
528 * changes.
529 */
530 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900531
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900532 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900533 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900534
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700535 /**
536 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
537 * Each list holds references to all NetworkAgentInfos that are used to
538 * satisfy requests for that network type.
539 *
540 * This array is built out at startup such that an unsupported network
541 * doesn't get an ArrayList instance, making this a tristate:
542 * unsupported, supported but not active and active.
543 *
544 * The actual lists are populated when we scan the network types that
545 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900546 *
547 * Threading model:
548 * - addSupportedType() is only called in the constructor
549 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
550 * They are therefore not thread-safe with respect to each other.
551 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
552 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
553 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700554 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900555 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700556
557 public LegacyTypeTracker() {
558 mTypeLists = (ArrayList<NetworkAgentInfo>[])
559 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
560 }
561
562 public void addSupportedType(int type) {
563 if (mTypeLists[type] != null) {
564 throw new IllegalStateException(
565 "legacy list for type " + type + "already initialized");
566 }
567 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
568 }
569
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700570 public boolean isTypeSupported(int type) {
571 return isNetworkTypeValid(type) && mTypeLists[type] != null;
572 }
573
574 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900575 synchronized (mTypeLists) {
576 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
577 return mTypeLists[type].get(0);
578 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700579 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900580 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700581 }
582
Robert Greenwalt8d482522015-06-24 13:23:42 -0700583 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900584 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900585 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700586 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900587 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900588 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900589 }
590 }
591
592 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700593 public void add(int type, NetworkAgentInfo nai) {
594 if (!isTypeSupported(type)) {
595 return; // Invalid network type.
596 }
597 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
598
599 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
600 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700601 return;
602 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900603 synchronized (mTypeLists) {
604 list.add(nai);
605 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900606
607 // 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 +0900608 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900609 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700610 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
611 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700612 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700613 }
614
Lorenzo Colittia793a672014-07-31 23:20:17 +0900615 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900616 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900617 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
618 if (list == null || list.isEmpty()) {
619 return;
620 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900621 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900622
Hugo Benichi78caa2582016-06-21 09:48:07 +0900623 synchronized (mTypeLists) {
624 if (!list.remove(nai)) {
625 return;
626 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900627 }
628
Robert Greenwalt8d482522015-06-24 13:23:42 -0700629 final DetailedState state = DetailedState.DISCONNECTED;
630
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900631 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700632 maybeLogBroadcast(nai, state, type, wasDefault);
633 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900634 }
635
636 if (!list.isEmpty() && wasFirstNetwork) {
637 if (DBG) log("Other network available for type " + type +
638 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900639 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700640 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
641 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900642 }
643 }
644
645 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900646 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
647 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700648 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900649 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700650 }
651 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700652
Robert Greenwalt8d482522015-06-24 13:23:42 -0700653 // send out another legacy broadcast - currently only used for suspend/unsuspend
654 // toggle
655 public void update(NetworkAgentInfo nai) {
656 final boolean isDefault = isDefaultNetwork(nai);
657 final DetailedState state = nai.networkInfo.getDetailedState();
658 for (int type = 0; type < mTypeLists.length; type++) {
659 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700660 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900661 final boolean isFirst = contains && (nai == list.get(0));
662 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700663 maybeLogBroadcast(nai, state, type, isDefault);
664 sendLegacyNetworkBroadcast(nai, state, type);
665 }
666 }
667 }
668
Lorenzo Colittia793a672014-07-31 23:20:17 +0900669 private String naiToString(NetworkAgentInfo nai) {
670 String name = (nai != null) ? nai.name() : "null";
671 String state = (nai.networkInfo != null) ?
672 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
673 "???/???";
674 return name + " " + state;
675 }
676
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700677 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900678 pw.println("mLegacyTypeTracker:");
679 pw.increaseIndent();
680 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700681 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900682 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700683 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900684 pw.println();
685 pw.println("Current state:");
686 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900687 synchronized (mTypeLists) {
688 for (int type = 0; type < mTypeLists.length; type++) {
689 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
690 for (NetworkAgentInfo nai : mTypeLists[type]) {
691 pw.println(type + " " + naiToString(nai));
692 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900693 }
694 }
695 pw.decreaseIndent();
696 pw.decreaseIndent();
697 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700698 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700699 }
700 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
701
Jeff Sharkey899223b2012-08-04 15:24:58 -0700702 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700703 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900704 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
705 }
706
707 @VisibleForTesting
708 protected ConnectivityService(Context context, INetworkManagementService netManager,
709 INetworkStatsService statsService, INetworkPolicyManager policyManager,
710 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800711 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800712
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900713 mSystemProperties = getSystemProperties();
714
Hugo Benichif9fdf872016-07-28 17:53:06 +0900715 mMetricsLog = logger;
Chalard Jeandda156a2018-01-10 21:19:32 +0900716 mDefaultRequest = createDefaultInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900717 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900718 mNetworkRequests.put(mDefaultRequest, defaultNRI);
719 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900720
Chalard Jeandda156a2018-01-10 21:19:32 +0900721 mDefaultMobileDataRequest = createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900722 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700723
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900724 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900725 mHandlerThread.start();
726 mHandler = new InternalHandler(mHandlerThread.getLooper());
727 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700728
Jeremy Joslin79294842014-12-03 17:15:28 -0800729 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
730 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
731
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900732 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900733
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700734 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700735 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800736 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700737 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900738 mPolicyManagerInternal = checkNotNull(
739 LocalServices.getService(NetworkPolicyManagerInternal.class),
740 "missing NetworkPolicyManagerInternal");
741
Jeff Sharkey82f85212012-08-24 11:17:25 -0700742 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700743 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700744
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700745 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900746 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700747 } catch (RemoteException e) {
748 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700749 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700750 }
751
752 final PowerManager powerManager = (PowerManager) context.getSystemService(
753 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700754 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
755 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
756 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800757 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700758
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700759 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700760
Wink Saville51f456f2013-04-23 14:26:51 -0700761 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900762 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700763 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700764 String[] naStrings = context.getResources().getStringArray(
765 com.android.internal.R.array.networkAttributes);
766 for (String naString : naStrings) {
767 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700768 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700769 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700770 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800771 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700772 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700773 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700774 }
Wink Saville51f456f2013-04-23 14:26:51 -0700775 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
776 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
777 n.type);
778 continue;
779 }
Wink Saville975c8482011-04-07 14:23:45 -0700780 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800781 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700782 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700783 continue;
784 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700785 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700786
Wink Saville975c8482011-04-07 14:23:45 -0700787 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700788 mNetworksDefined++;
789 } catch(Exception e) {
790 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700791 }
792 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700793
794 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
795 if (mNetConfigs[TYPE_VPN] == null) {
796 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
797 // don't need to add TYPE_VPN to mNetConfigs.
798 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
799 mNetworksDefined++; // used only in the log() statement below.
800 }
801
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +0900802 // Do the same for Ethernet, since it's often not specified in the configs, although many
803 // devices can use it via USB host adapters.
804 if (mNetConfigs[TYPE_ETHERNET] == null && hasService(Context.ETHERNET_SERVICE)) {
805 mLegacyTypeTracker.addSupportedType(TYPE_ETHERNET);
806 mNetworksDefined++;
807 }
808
Wink Saville5e56bc52013-07-29 15:00:57 -0700809 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700810
Robert Greenwalt50393202011-06-21 17:26:14 -0700811 mProtectedNetworks = new ArrayList<Integer>();
812 int[] protectedNetworks = context.getResources().getIntArray(
813 com.android.internal.R.array.config_protectedNetworks);
814 for (int p : protectedNetworks) {
815 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
816 mProtectedNetworks.add(p);
817 } else {
818 if (DBG) loge("Ignoring protectedNetwork " + p);
819 }
820 }
821
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900822 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
823 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700824
Erik Kline47222fc2017-04-30 19:36:15 +0900825 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800826
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700827 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
828
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700829 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700830 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100831 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700832 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700833 intentFilter.addAction(Intent.ACTION_USER_ADDED);
834 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000835 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700836 mContext.registerReceiverAsUser(
837 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000838 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
839 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900840
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700841 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700842 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700843 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700844 } catch (RemoteException e) {
845 loge("Error registering observer :" + e);
846 }
847
Erik Klineda4bfa82015-04-30 12:58:40 +0900848 mSettingsObserver = new SettingsObserver(mContext, mHandler);
849 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800850
John Spurlockbf991a82013-06-24 14:20:23 -0400851 mDataConnectionStats = new DataConnectionStats(mContext);
852 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400853
Jason Monkdecd2952013-10-10 14:02:51 -0400854 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700855
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400856 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900857
858 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900859 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
860 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900861
862 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
863 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
864 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
865 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
866 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
867 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
868 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900869
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900870 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900871 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900872 mMultinetworkPolicyTracker.start();
Erik Kline1742fe12017-12-13 19:40:49 +0900873
874 mDnsManager = new DnsManager(mContext, mNetd, mSystemProperties);
Erik Klinea24d4592018-01-11 21:07:29 +0900875 registerPrivateDnsSettingsCallbacks();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800876 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700877
Erik Kline47222fc2017-04-30 19:36:15 +0900878 private Tethering makeTethering() {
879 // TODO: Move other elements into @Overridden getters.
880 final TetheringDependencies deps = new TetheringDependencies();
881 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
882 IoThread.get().getLooper(), new MockableSystemProperties(),
883 deps);
884 }
885
Chalard Jeandda156a2018-01-10 21:19:32 +0900886 private NetworkRequest createDefaultInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900887 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900888 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900889 netCap.addCapability(NET_CAPABILITY_INTERNET);
890 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900891 if (transportType > -1) {
892 netCap.addTransportType(transportType);
893 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900894 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900895 }
896
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900897 // Used only for testing.
898 // TODO: Delete this and either:
899 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
900 // changing ContentResolver to make registerContentObserver non-final).
901 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
902 // by subclassing SettingsObserver.
903 @VisibleForTesting
904 void updateMobileDataAlwaysOn() {
905 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
906 }
907
Erik Klineda4bfa82015-04-30 12:58:40 +0900908 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900909 final boolean enable = toBool(Settings.Global.getInt(
910 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900911 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
912 if (enable == isEnabled) {
913 return; // Nothing to do.
914 }
915
916 if (enable) {
917 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900918 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900919 } else {
920 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
921 }
922 }
923
924 private void registerSettingsCallbacks() {
925 // Watch for global HTTP proxy changes.
926 mSettingsObserver.observe(
927 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
928 EVENT_APPLY_GLOBAL_HTTP_PROXY);
929
930 // Watch for whether or not to keep mobile data always on.
931 mSettingsObserver.observe(
932 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
933 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
934 }
935
Erik Klinea24d4592018-01-11 21:07:29 +0900936 private void registerPrivateDnsSettingsCallbacks() {
937 for (Uri u : DnsManager.getPrivateDnsSettingsUris()) {
938 mSettingsObserver.observe(u, EVENT_PRIVATE_DNS_SETTINGS_CHANGED);
939 }
940 }
941
Robert Greenwalt34524f02014-05-18 16:22:10 -0700942 private synchronized int nextNetworkRequestId() {
943 return mNextNetworkRequestId++;
944 }
945
Paul Jensen67b0b072015-06-10 11:22:17 -0400946 @VisibleForTesting
947 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400948 synchronized (mNetworkForNetId) {
949 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
950 int netId = mNextNetId;
951 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
952 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500953 if (!mNetIdInUse.get(netId)) {
954 mNetIdInUse.put(netId, true);
955 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400956 }
957 }
958 }
959 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700960 }
961
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600962 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800963 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600964 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
965 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800966 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600967 state = nai.getNetworkState();
968 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800969 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600970 final NetworkInfo info = new NetworkInfo(networkType, 0,
971 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800972 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
973 info.setIsAvailable(true);
Jeff Sharkey62262162017-12-04 15:52:01 -0700974 final NetworkCapabilities capabilities = new NetworkCapabilities();
975 capabilities.setCapability(NetworkCapabilities.NET_CAPABILITY_NOT_ROAMING,
976 !info.isRoaming());
977 state = new NetworkState(info, new LinkProperties(), capabilities,
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600978 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800979 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600980 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600981 return state;
982 } else {
983 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800984 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400985 }
986
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800987 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
988 if (network == null) {
989 return null;
990 }
991 synchronized (mNetworkForNetId) {
992 return mNetworkForNetId.get(network.netId);
993 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600994 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800995
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900996 private Network[] getVpnUnderlyingNetworks(int uid) {
Hugo Benichi69744342017-11-27 10:57:16 +0900997 synchronized (mVpns) {
998 if (!mLockdownEnabled) {
999 int user = UserHandle.getUserId(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001000 Vpn vpn = mVpns.get(user);
1001 if (vpn != null && vpn.appliesToUid(uid)) {
1002 return vpn.getUnderlyingNetworks();
1003 }
1004 }
1005 }
1006 return null;
1007 }
1008
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001009 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04001010 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001011
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001012 final Network[] networks = getVpnUnderlyingNetworks(uid);
1013 if (networks != null) {
1014 // getUnderlyingNetworks() returns:
1015 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
1016 // empty array => the VPN explicitly said "no default network".
1017 // non-empty array => the VPN specified one or more default networks; we use the
1018 // first one.
1019 if (networks.length > 0) {
1020 nai = getNetworkAgentInfoForNetwork(networks[0]);
1021 } else {
1022 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08001023 }
1024 }
1025
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001026 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001027 return nai.getNetworkState();
1028 } else {
1029 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001030 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001031 }
1032
1033 /**
1034 * Check if UID should be blocked from using the network with the given LinkProperties.
1035 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001036 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1037 boolean ignoreBlocked) {
1038 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001039 if (ignoreBlocked) {
1040 return false;
1041 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001042 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001043 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1044 if (isSystem(uid)) {
1045 return false;
1046 }
Robin Lee17e61832016-05-09 13:46:28 +01001047 synchronized (mVpns) {
1048 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1049 if (vpn != null && vpn.isBlockingUid(uid)) {
1050 return true;
1051 }
1052 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001053 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001054 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001055 }
1056
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001057 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001058 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1059 return;
1060 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001061 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001062 synchronized (mBlockedAppUids) {
1063 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001064 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001065 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001066 blocked = false;
1067 } else {
1068 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001069 }
1070 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001071 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1072 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1073 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001074 }
1075
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001076 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001077 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1078 * example, this may mark the network as {@link DetailedState#BLOCKED} based
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001079 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001080 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001081 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001082 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1083
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001084 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001085 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001086 }
Hugo Benichi69744342017-11-27 10:57:16 +09001087 synchronized (mVpns) {
1088 if (mLockdownTracker != null) {
1089 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
1090 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001091 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001092 }
1093
1094 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001095 * Return NetworkInfo for the active (i.e., connected) network interface.
1096 * It is assumed that at most one network is active at a time. If more
1097 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001098 * @return the info for the active network, or {@code null} if none is
1099 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001100 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001101 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001102 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001103 enforceAccessPermission();
1104 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001105 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001106 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001107 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1108 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001109 }
1110
Paul Jensen31a94f42015-02-13 14:18:39 -05001111 @Override
1112 public Network getActiveNetwork() {
1113 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001114 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001115 }
1116
1117 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001118 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001119 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001120 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001121 }
1122
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001123 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001124 final int user = UserHandle.getUserId(uid);
1125 int vpnNetId = NETID_UNSET;
1126 synchronized (mVpns) {
1127 final Vpn vpn = mVpns.get(user);
1128 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1129 }
1130 NetworkAgentInfo nai;
1131 if (vpnNetId != NETID_UNSET) {
1132 synchronized (mNetworkForNetId) {
1133 nai = mNetworkForNetId.get(vpnNetId);
1134 }
1135 if (nai != null) return nai.network;
1136 }
1137 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 if (nai != null
1139 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1140 nai = null;
1141 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001142 return nai != null ? nai.network : null;
1143 }
1144
Lorenzo Colitti18660282016-07-04 12:55:44 +09001145 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001146 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1147 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001148 final int uid = Binder.getCallingUid();
1149 NetworkState state = getUnfilteredActiveNetworkState(uid);
1150 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001151 }
1152
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001153 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001154 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001155 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001156 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001157 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001158 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 }
1160
1161 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 public NetworkInfo getNetworkInfo(int networkType) {
1163 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001164 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001165 if (getVpnUnderlyingNetworks(uid) != null) {
1166 // A VPN is active, so we may need to return one of its underlying networks. This
1167 // information is not available in LegacyTypeTracker, so we have to get it from
1168 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001169 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001170 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001171 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001172 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001173 }
1174 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001175 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001176 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 }
1178
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001180 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001181 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001182 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001183 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001184 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001185 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001186 return state.networkInfo;
1187 } else {
1188 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001189 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001190 }
1191
1192 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001193 public NetworkInfo[] getAllNetworkInfo() {
1194 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001195 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001196 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1197 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001198 NetworkInfo info = getNetworkInfo(networkType);
1199 if (info != null) {
1200 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001201 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001202 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001203 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001204 }
1205
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001206 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001207 public Network getNetworkForType(int networkType) {
1208 enforceAccessPermission();
1209 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001210 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1211 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001213 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001214 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001215 }
1216
1217 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001218 public Network[] getAllNetworks() {
1219 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001220 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001221 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001222 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001223 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001224 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001225 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001226 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001227 }
1228
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001229 @Override
1230 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1231 // The basic principle is: if an app's traffic could possibly go over a
1232 // network, without the app doing anything multinetwork-specific,
1233 // (hence, by "default"), then include that network's capabilities in
1234 // the array.
1235 //
1236 // In the normal case, app traffic only goes over the system's default
1237 // network connection, so that's the only network returned.
1238 //
1239 // With a VPN in force, some app traffic may go into the VPN, and thus
1240 // over whatever underlying networks the VPN specifies, while other app
1241 // traffic may go over the system default network (e.g.: a split-tunnel
1242 // VPN, or an app disallowed by the VPN), so the set of networks
1243 // returned includes the VPN's underlying networks and the system
1244 // default.
1245 enforceAccessPermission();
1246
1247 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1248
1249 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001250 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001251 if (nc != null) {
1252 result.put(nai.network, nc);
1253 }
1254
Hugo Benichi69744342017-11-27 10:57:16 +09001255 synchronized (mVpns) {
1256 if (!mLockdownEnabled) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001257 Vpn vpn = mVpns.get(userId);
1258 if (vpn != null) {
1259 Network[] networks = vpn.getUnderlyingNetworks();
1260 if (networks != null) {
1261 for (Network network : networks) {
1262 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001263 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001264 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001265 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001266 }
1267 }
1268 }
1269 }
1270 }
1271 }
1272
1273 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1274 out = result.values().toArray(out);
1275 return out;
1276 }
1277
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001278 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001279 public boolean isNetworkSupported(int networkType) {
1280 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001281 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001282 }
1283
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001284 /**
1285 * Return LinkProperties for the active (i.e., connected) default
1286 * network interface. It is assumed that at most one default network
1287 * is active at a time. If more than one is active, it is indeterminate
1288 * which will be returned.
1289 * @return the ip properties for the active network, or {@code null} if
1290 * none is active
1291 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001292 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001293 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001294 enforceAccessPermission();
1295 final int uid = Binder.getCallingUid();
1296 NetworkState state = getUnfilteredActiveNetworkState(uid);
1297 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001298 }
1299
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001300 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001301 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001302 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001303 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1304 if (nai != null) {
1305 synchronized (nai) {
1306 return new LinkProperties(nai.linkProperties);
1307 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001308 }
1309 return null;
1310 }
1311
Robert Greenwalt12e67352014-05-13 21:41:06 -07001312 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001313 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001314 public LinkProperties getLinkProperties(Network network) {
1315 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001316 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1317 }
1318
1319 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1320 if (nai == null) {
1321 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001322 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001323 synchronized (nai) {
1324 return new LinkProperties(nai.linkProperties);
1325 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001326 }
1327
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001328 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001329 if (nai != null) {
1330 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001331 if (nai.networkCapabilities != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001332 // TODO : don't remove the UIDs when communicating with processes
1333 // that have the NETWORK_SETTINGS permission.
1334 return networkCapabilitiesWithoutUids(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001335 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001336 }
1337 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001338 return null;
1339 }
1340
1341 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001342 public NetworkCapabilities getNetworkCapabilities(Network network) {
1343 enforceAccessPermission();
1344 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1345 }
1346
Chalard Jeanf19db372018-01-26 19:24:40 +09001347 private NetworkCapabilities networkCapabilitiesWithoutUids(NetworkCapabilities nc) {
1348 return new NetworkCapabilities(nc).setUids(null);
1349 }
1350
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001351 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001352 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001353 // Require internal since we're handing out IMSI details
1354 enforceConnectivityInternalPermission();
1355
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001356 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001357 for (Network network : getAllNetworks()) {
1358 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1359 if (nai != null) {
Chalard Jeanf19db372018-01-26 19:24:40 +09001360 // TODO (b/73321673) : NetworkState contains a copy of the
1361 // NetworkCapabilities, which may contain UIDs of apps to which the
1362 // network applies. Should the UIDs be cleared so as not to leak or
1363 // interfere ?
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001364 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001365 }
1366 }
1367 return result.toArray(new NetworkState[result.size()]);
1368 }
1369
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001370 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001371 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001372 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001373 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1374 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1375 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001376 }
1377
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001378 @Override
1379 public boolean isActiveNetworkMetered() {
1380 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001381
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001382 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1383 if (caps != null) {
1384 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1385 } else {
1386 // Always return the most conservative value
1387 return true;
1388 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001389 }
1390
Jeff Sharkey216c1812012-08-05 14:29:23 -07001391 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1392 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001393 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001394 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001395 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001396 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001397 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001398
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001399 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001400 * Ensure that a network route exists to deliver traffic to the specified
1401 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001402 * @param networkType the type of the network over which traffic to the
1403 * specified host is to be routed
1404 * @param hostAddress the IP address of the host to which the route is
1405 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001406 * @return {@code true} on success, {@code false} on failure
1407 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001408 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001409 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001410 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001411 if (mProtectedNetworks.contains(networkType)) {
1412 enforceConnectivityInternalPermission();
1413 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001414
Chad Brubakerc0234532014-02-14 13:24:29 -08001415 InetAddress addr;
1416 try {
1417 addr = InetAddress.getByAddress(hostAddress);
1418 } catch (UnknownHostException e) {
1419 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1420 return false;
1421 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001422
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001423 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001424 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 return false;
1426 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001427
1428 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1429 if (nai == null) {
1430 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1431 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1432 } else {
1433 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1434 }
1435 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001436 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001437
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001438 DetailedState netState;
1439 synchronized (nai) {
1440 netState = nai.networkInfo.getDetailedState();
1441 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001442
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001443 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001444 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001445 log("requestRouteToHostAddress on down network "
1446 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001447 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001448 }
1449 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001450 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001451
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001452 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001453 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001454 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001455 LinkProperties lp;
1456 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001457 synchronized (nai) {
1458 lp = nai.linkProperties;
1459 netId = nai.network.netId;
1460 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001461 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001462 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1463 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001464 } finally {
1465 Binder.restoreCallingIdentity(token);
1466 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001467 }
1468
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001469 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001470 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001471 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001472 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001473 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001474 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001475 if (bestRoute.getGateway().equals(addr)) {
1476 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001477 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001478 } else {
1479 // if we will connect to this through another route, add a direct route
1480 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001481 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001482 }
1483 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001484 if (DBG) log("Adding legacy route " + bestRoute +
1485 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001486 try {
1487 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1488 } catch (Exception e) {
1489 // never crash - catch them all
1490 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001491 return false;
1492 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001493 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001494 }
1495
Jeff Sharkey75d31892018-01-18 22:01:59 +09001496 private final INetworkPolicyListener mPolicyListener = new NetworkPolicyManager.Listener() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001497 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001498 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001499 // TODO: notify UID when it has requested targeted updates
1500 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001501 @Override
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001502 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001503 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001504 if (restrictBackground) {
1505 log("onRestrictBackgroundChanged(true): disabling tethering");
1506 mTethering.untetherAll();
1507 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001508 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001509 };
1510
Robin Lee3b3dd942015-05-12 18:14:58 +01001511 /**
1512 * Require that the caller is either in the same user or has appropriate permission to interact
1513 * across users.
1514 *
1515 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1516 */
1517 private void enforceCrossUserPermission(int userId) {
1518 if (userId == UserHandle.getCallingUserId()) {
1519 // Not a cross-user call.
1520 return;
1521 }
1522 mContext.enforceCallingOrSelfPermission(
1523 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1524 "ConnectivityService");
1525 }
1526
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001527 private void enforceInternetPermission() {
1528 mContext.enforceCallingOrSelfPermission(
1529 android.Manifest.permission.INTERNET,
1530 "ConnectivityService");
1531 }
1532
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001533 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001534 mContext.enforceCallingOrSelfPermission(
1535 android.Manifest.permission.ACCESS_NETWORK_STATE,
1536 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001537 }
1538
1539 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001540 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001541 }
1542
Charles Hea0a87e82017-05-15 17:07:18 +01001543 private void enforceSettingsPermission() {
1544 mContext.enforceCallingOrSelfPermission(
1545 android.Manifest.permission.NETWORK_SETTINGS,
1546 "ConnectivityService");
1547 }
1548
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001549 private void enforceTetherAccessPermission() {
1550 mContext.enforceCallingOrSelfPermission(
1551 android.Manifest.permission.ACCESS_NETWORK_STATE,
1552 "ConnectivityService");
1553 }
1554
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001555 private void enforceConnectivityInternalPermission() {
1556 mContext.enforceCallingOrSelfPermission(
1557 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1558 "ConnectivityService");
1559 }
1560
Hugo Benichi514da602016-07-19 15:59:27 +09001561 private void enforceConnectivityRestrictedNetworksPermission() {
1562 try {
1563 mContext.enforceCallingOrSelfPermission(
1564 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1565 "ConnectivityService");
1566 return;
1567 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1568 enforceConnectivityInternalPermission();
1569 }
1570
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001571 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001572 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001573 }
1574
Lorenzo Colitti18660282016-07-04 12:55:44 +09001575 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001576 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001577 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001578 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001579 }
1580
1581 private void sendInetConditionBroadcast(NetworkInfo info) {
1582 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1583 }
1584
Wink Saville628b0852011-08-04 15:01:58 -07001585 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Hugo Benichi69744342017-11-27 10:57:16 +09001586 synchronized (mVpns) {
1587 if (mLockdownTracker != null) {
1588 info = new NetworkInfo(info);
1589 mLockdownTracker.augmentNetworkInfo(info);
1590 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001591 }
1592
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001593 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001594 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001595 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001596 if (info.isFailover()) {
1597 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1598 info.setFailover(false);
1599 }
1600 if (info.getReason() != null) {
1601 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1602 }
1603 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001604 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1605 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001606 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001607 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001608 return intent;
1609 }
1610
1611 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1612 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1613 }
1614
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001615 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001616 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1617 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1618 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001619 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001620 final long ident = Binder.clearCallingIdentity();
1621 try {
1622 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1623 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1624 } finally {
1625 Binder.restoreCallingIdentity(ident);
1626 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001627 }
1628
Mike Lockwood0f79b542009-08-14 14:18:49 -04001629 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001630 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001631 if (!mSystemReady) {
1632 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001633 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001634 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001635 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001636 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001637 }
1638
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001639 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001640 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001641 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001642 final NetworkInfo ni = intent.getParcelableExtra(
1643 ConnectivityManager.EXTRA_NETWORK_INFO);
1644 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1645 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1646 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001647 } else {
1648 BroadcastOptions opts = BroadcastOptions.makeBasic();
1649 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1650 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001651 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001652 final IBatteryStats bs = BatteryStatsService.getService();
1653 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001654 bs.noteConnectivityChanged(intent.getIntExtra(
1655 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1656 ni != null ? ni.getState().toString() : "?");
1657 } catch (RemoteException e) {
1658 }
1659 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001660 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001661 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001662 } finally {
1663 Binder.restoreCallingIdentity(ident);
1664 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001665 }
1666 }
1667
1668 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001669 loadGlobalProxy();
1670
Hugo Benichi20035e02017-04-26 14:53:28 +09001671 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001672 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001673 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001674 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001675 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001676 }
1677 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001678 // load the global proxy at startup
1679 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001680
Robin Lee244ce8e2016-01-05 18:03:46 +00001681 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1682 // for user to unlock device too.
1683 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001684
Erik Klineda4bfa82015-04-30 12:58:40 +09001685 // Configure whether mobile data is always on.
1686 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1687
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001688 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001689
1690 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001691 }
1692
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001693 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001694 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001695 *
1696 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001697 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001698 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001699 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1700 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001701
1702 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001703 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001704
Robert Greenwalt7b816022014-04-18 15:25:25 -07001705 if (networkAgent.networkCapabilities.hasTransport(
1706 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001707 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1708 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001709 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001710 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001711 } else if (networkAgent.networkCapabilities.hasTransport(
1712 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001713 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1714 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001715 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001716 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001717 } else {
1718 // do not track any other networks
1719 timeout = 0;
1720 }
1721
Robert Greenwalt7b816022014-04-18 15:25:25 -07001722 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001723 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001724 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001725 } catch (Exception e) {
1726 // You shall not crash!
1727 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001728 }
1729 }
1730 }
1731
1732 /**
1733 * Remove data activity tracking when network disconnects.
1734 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001735 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1736 final String iface = networkAgent.linkProperties.getInterfaceName();
1737 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001738
Robert Greenwalt7b816022014-04-18 15:25:25 -07001739 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1740 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001741 try {
1742 // the call fails silently if no idletimer setup for this interface
1743 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001744 } catch (Exception e) {
1745 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001746 }
1747 }
1748 }
1749
1750 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001751 * Reads the network specific MTU size from reources.
1752 * and set it on it's iface.
1753 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001754 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1755 final String iface = newLp.getInterfaceName();
1756 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001757 if (oldLp == null && mtu == 0) {
1758 // Silently ignore unset MTU value.
1759 return;
1760 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001761 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1762 if (VDBG) log("identical MTU - not setting");
1763 return;
1764 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001765 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001766 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001767 return;
1768 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001769
w1997615afd812014-08-05 15:18:11 -07001770 // Cannot set MTU without interface name
1771 if (TextUtils.isEmpty(iface)) {
1772 loge("Setting MTU size with null iface.");
1773 return;
1774 }
1775
Robert Greenwalt7b816022014-04-18 15:25:25 -07001776 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001777 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001778 mNetd.setMtu(iface, mtu);
1779 } catch (Exception e) {
1780 Slog.e(TAG, "exception in setMtu()" + e);
1781 }
1782 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001783
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001784 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001785 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1786
1787 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001788 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001789 protected MockableSystemProperties getSystemProperties() {
1790 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001791 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001792
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001793 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1794 if (isDefaultNetwork(nai) == false) {
1795 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001796 }
1797
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001798 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1799 String[] values = null;
1800 if (tcpBufferSizes != null) {
1801 values = tcpBufferSizes.split(",");
1802 }
1803
1804 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001805 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001806 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1807 values = tcpBufferSizes.split(",");
1808 }
1809
1810 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1811
1812 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001813 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001814
1815 final String prefix = "/sys/kernel/ipv4/tcp_";
1816 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1817 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1818 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1819 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1820 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1821 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1822 mCurrentTcpBufferSizes = tcpBufferSizes;
1823 } catch (IOException e) {
1824 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001825 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001826
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001827 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001828 Settings.Global.TCP_DEFAULT_INIT_RWND,
1829 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001830 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1831 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001832 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001833 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001834 }
1835
Robert Greenwalt562cc542014-05-15 18:07:26 -07001836 @Override
1837 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001838 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001839 NETWORK_RESTORE_DELAY_PROP_NAME);
1840 if(restoreDefaultNetworkDelayStr != null &&
1841 restoreDefaultNetworkDelayStr.length() != 0) {
1842 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001843 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001844 } catch (NumberFormatException e) {
1845 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001847 // if the system property isn't set, use the value for the apn type
1848 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1849
1850 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1851 (mNetConfigs[networkType] != null)) {
1852 ret = mNetConfigs[networkType].restoreTime;
1853 }
1854 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 }
1856
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001857 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001858 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001859 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001860 }
1861 return false;
1862 }
1863
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001864 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1865 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1866 final long DIAG_TIME_MS = 5000;
1867 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1868 // Start gathering diagnostic information.
1869 netDiags.add(new NetworkDiagnostics(
1870 nai.network,
1871 new LinkProperties(nai.linkProperties), // Must be a copy.
1872 DIAG_TIME_MS));
1873 }
1874
1875 for (NetworkDiagnostics netDiag : netDiags) {
1876 pw.println();
1877 netDiag.waitForMeasurements();
1878 netDiag.dump(pw);
1879 }
1880 }
1881
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001882 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001883 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1884 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001885 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001886
Erik Kline7747fd42017-05-12 16:52:48 +09001887 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001888 dumpNetworkDiagnostics(pw);
1889 return;
Erik Klineee363c42017-05-29 09:11:03 +09001890 } else if (argsContain(args, TETHERING_ARG)) {
1891 mTethering.dump(fd, pw, args);
1892 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001893 }
Erik Kline379747a2015-06-05 17:47:34 +09001894
Lorenzo Colittie3805462015-06-03 11:18:24 +09001895 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001896 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001897 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001898 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001899 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001900 pw.println();
1901
Paul Jensen85cf78e2015-06-25 13:25:07 -04001902 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001903 pw.print("Active default network: ");
1904 if (defaultNai == null) {
1905 pw.println("none");
1906 } else {
1907 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001908 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001909 pw.println();
1910
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001911 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001912 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001913 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1914 pw.println(nai.toString());
1915 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001916 pw.println(String.format(
1917 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1918 nai.numForegroundNetworkRequests(),
1919 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1920 nai.numBackgroundNetworkRequests(),
1921 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001922 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001923 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1924 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001925 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001926 pw.decreaseIndent();
1927 pw.println("Lingered:");
1928 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001929 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001930 pw.decreaseIndent();
1931 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001932 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001933 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001934 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001935
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001936 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001937 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001938 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1939 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001940 }
1941 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001942 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001943
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001944 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001945
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001946 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001947 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001948
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001949 pw.println();
1950 mKeepaliveTracker.dump(pw);
1951
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001952 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001953 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001954
Erik Kline7747fd42017-05-12 16:52:48 +09001955 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001956 pw.println();
1957 synchronized (mValidationLogs) {
1958 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001959 for (ValidationLog p : mValidationLogs) {
1960 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001961 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001962 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001963 pw.decreaseIndent();
1964 }
1965 }
Erik Kline7523eb32015-07-09 18:24:03 +09001966
1967 pw.println();
1968 pw.println("mNetworkRequestInfoLogs (most recent first):");
1969 pw.increaseIndent();
1970 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1971 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001972
1973 pw.println();
1974 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1975 pw.increaseIndent();
1976 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1977 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001978
1979 pw.println();
1980 pw.println("NetTransition WakeLock activity (most recent first):");
1981 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09001982 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1983 pw.println("total releases: " + mTotalWakelockReleases);
1984 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1985 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1986 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1987 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1988 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1989 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001990 mWakelockLogs.reverseDump(fd, pw, args);
1991 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001992 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001993 }
1994
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001995 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001996 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001997 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001998 if (officialNai != null && officialNai.equals(nai)) return true;
1999 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002000 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002001 " - " + nai);
2002 }
2003 return false;
2004 }
2005
Robert Greenwalt42acef32009-08-12 16:08:25 -07002006 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002007 private class NetworkStateTrackerHandler extends Handler {
2008 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07002009 super(looper);
2010 }
2011
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002012 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002013 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002014 default:
2015 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002016 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002017 handleAsyncChannelHalfConnect(msg);
2018 break;
2019 }
2020 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2021 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2022 if (nai != null) nai.asyncChannel.disconnect();
2023 break;
2024 }
2025 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2026 handleAsyncChannelDisconnected(msg);
2027 break;
2028 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002029 }
2030 return true;
2031 }
2032
2033 private void maybeHandleNetworkAgentMessage(Message msg) {
2034 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2035 if (nai == null) {
2036 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002037 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002038 }
2039 return;
2040 }
2041
2042 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002043 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002044 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2045 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002046 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2047 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002048 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002049 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002050 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002051 break;
2052 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002053 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002054 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002055 break;
2056 }
2057 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002058 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002059 updateNetworkInfo(nai, info);
2060 break;
2061 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002062 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002063 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002064 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002065 break;
2066 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002067 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002068 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2069 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002070 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002071 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002072 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002073 break;
2074 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002075 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002076 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2077 break;
2078 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002079 }
2080 }
2081
2082 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2083 switch (msg.what) {
2084 default:
2085 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002086 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002087 final NetworkAgentInfo nai;
2088 synchronized (mNetworkForNetId) {
2089 nai = mNetworkForNetId.get(msg.arg2);
2090 }
Erik Klinea24d4592018-01-11 21:07:29 +09002091 if (nai == null) break;
2092
2093 final boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
2094 final boolean wasValidated = nai.lastValidated;
2095 final boolean wasDefault = isDefaultNetwork(nai);
2096
2097 final PrivateDnsConfig privateDnsCfg = (msg.obj instanceof PrivateDnsConfig)
2098 ? (PrivateDnsConfig) msg.obj : null;
2099 final String redirectUrl = (msg.obj instanceof String) ? (String) msg.obj : "";
2100
2101 final boolean reevaluationRequired;
2102 final String logMsg;
2103 if (valid) {
2104 reevaluationRequired = updatePrivateDns(nai, privateDnsCfg);
2105 logMsg = (DBG && (privateDnsCfg != null))
2106 ? " with " + privateDnsCfg.toString() : "";
2107 } else {
2108 reevaluationRequired = false;
2109 logMsg = (DBG && !TextUtils.isEmpty(redirectUrl))
2110 ? " with redirect to " + redirectUrl : "";
2111 }
2112 if (DBG) {
2113 log(nai.name() + " validation " + (valid ? "passed" : "failed") + logMsg);
2114 }
2115 // If there is a change in Private DNS configuration,
2116 // trigger reevaluation of the network to test it.
2117 if (reevaluationRequired) {
2118 nai.networkMonitor.sendMessage(
2119 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2120 break;
2121 }
2122 if (valid != nai.lastValidated) {
2123 if (wasDefault) {
2124 metricsLogger().defaultNetworkMetrics().logDefaultNetworkValidity(
2125 SystemClock.elapsedRealtime(), valid);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002126 }
Erik Klinea24d4592018-01-11 21:07:29 +09002127 final int oldScore = nai.getCurrentScore();
2128 nai.lastValidated = valid;
2129 nai.everValidated |= valid;
2130 updateCapabilities(oldScore, nai, nai.networkCapabilities);
2131 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2132 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
2133 }
2134 updateInetCondition(nai);
2135 // Let the NetworkAgent know the state of its network
2136 Bundle redirectUrlBundle = new Bundle();
2137 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, redirectUrl);
2138 nai.asyncChannel.sendMessage(
2139 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2140 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2141 0, redirectUrlBundle);
2142 if (wasValidated && !nai.lastValidated) {
2143 handleNetworkUnvalidated(nai);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002144 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002145 break;
2146 }
Paul Jensen869868be2014-05-15 10:33:05 -04002147 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002148 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002149 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002150 final NetworkAgentInfo nai;
2151 synchronized (mNetworkForNetId) {
2152 nai = mNetworkForNetId.get(netId);
2153 }
Calvin Onbe96da12016-10-11 15:10:46 -07002154 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002155 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002156 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002157 nai.lastCaptivePortalDetected = visible;
2158 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002159 if (nai.lastCaptivePortalDetected &&
2160 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2161 if (DBG) log("Avoiding captive portal network: " + nai.name());
2162 nai.asyncChannel.sendMessage(
2163 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2164 teardownUnneededNetwork(nai);
2165 break;
2166 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002167 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002168 }
2169 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002170 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002171 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002172 if (nai == null) {
2173 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2174 break;
2175 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002176 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002177 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002178 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002179 }
Paul Jensen869868be2014-05-15 10:33:05 -04002180 }
Paul Jensen869868be2014-05-15 10:33:05 -04002181 break;
2182 }
Erik Klinea24d4592018-01-11 21:07:29 +09002183 case NetworkMonitor.EVENT_PRIVATE_DNS_CONFIG_RESOLVED: {
2184 final NetworkAgentInfo nai;
2185 synchronized (mNetworkForNetId) {
2186 nai = mNetworkForNetId.get(msg.arg2);
2187 }
2188 if (nai == null) break;
2189
2190 final PrivateDnsConfig cfg = (PrivateDnsConfig) msg.obj;
2191 final boolean reevaluationRequired = updatePrivateDns(nai, cfg);
2192 if (nai.lastValidated && reevaluationRequired) {
2193 nai.networkMonitor.sendMessage(
2194 NetworkMonitor.CMD_FORCE_REEVALUATION, Process.SYSTEM_UID);
2195 }
2196 break;
2197 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002198 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002199 return true;
2200 }
2201
Calvin Onbe96da12016-10-11 15:10:46 -07002202 private int getCaptivePortalMode() {
2203 return Settings.Global.getInt(mContext.getContentResolver(),
2204 Settings.Global.CAPTIVE_PORTAL_MODE,
2205 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2206 }
2207
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002208 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2209 switch (msg.what) {
2210 default:
2211 return false;
2212 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2213 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2214 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2215 handleLingerComplete(nai);
2216 }
2217 break;
2218 }
2219 }
2220 return true;
2221 }
2222
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002223 @Override
2224 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002225 if (!maybeHandleAsyncChannelMessage(msg) &&
2226 !maybeHandleNetworkMonitorMessage(msg) &&
2227 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002228 maybeHandleNetworkAgentMessage(msg);
2229 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002230 }
2231 }
2232
Erik Klinea24d4592018-01-11 21:07:29 +09002233 private void handlePrivateDnsSettingsChanged() {
2234 final PrivateDnsConfig cfg = mDnsManager.getPrivateDnsConfig();
2235
2236 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2237 // Private DNS only ever applies to networks that might provide
2238 // Internet access and therefore also require validation.
2239 if (!NetworkMonitor.isValidationRequired(
2240 mDefaultRequest.networkCapabilities, nai.networkCapabilities)) {
2241 continue;
2242 }
2243
2244 // Notify the NetworkMonitor thread in case it needs to cancel or
2245 // schedule DNS resolutions. If a DNS resolution is required the
2246 // result will be sent back to us.
2247 nai.networkMonitor.notifyPrivateDnsSettingsChanged(cfg);
2248
2249 if (!cfg.inStrictMode()) {
2250 // No strict mode hostname DNS resolution needed, so just update
2251 // DNS settings directly. In opportunistic and "off" modes this
2252 // just reprograms netd with the network-supplied DNS servers
2253 // (and of course the boolean of whether or not to attempt TLS).
2254 //
2255 // TODO: Consider code flow parity with strict mode, i.e. having
2256 // NetworkMonitor relay the PrivateDnsConfig back to us and then
2257 // performing this call at that time.
2258 updatePrivateDns(nai, cfg);
2259 }
2260 }
2261 }
2262
2263 private boolean updatePrivateDns(NetworkAgentInfo nai, PrivateDnsConfig newCfg) {
2264 final boolean reevaluationRequired = true;
2265 final boolean dontReevaluate = false;
2266
2267 final PrivateDnsConfig oldCfg = mDnsManager.updatePrivateDns(nai.network, newCfg);
2268 updateDnses(nai.linkProperties, null, nai.network.netId);
2269
2270 if (newCfg == null) {
2271 if (oldCfg == null) return dontReevaluate;
2272 return oldCfg.useTls ? reevaluationRequired : dontReevaluate;
2273 }
2274
2275 if (oldCfg == null) {
2276 return newCfg.useTls ? reevaluationRequired : dontReevaluate;
2277 }
2278
2279 if (oldCfg.useTls != newCfg.useTls) {
2280 return reevaluationRequired;
2281 }
2282
2283 if (newCfg.inStrictMode() && !Objects.equals(oldCfg.hostname, newCfg.hostname)) {
2284 return reevaluationRequired;
2285 }
2286
2287 return dontReevaluate;
2288 }
2289
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002290 private void updateLingerState(NetworkAgentInfo nai, long now) {
2291 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2292 // 2. If the network was lingering and there are now requests, unlinger it.
2293 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2294 // one lingered request, start lingering.
2295 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002296 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002297 if (DBG) log("Unlingering " + nai.name());
2298 nai.unlinger();
2299 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002300 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002301 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002302 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002303 nai.linger();
2304 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2305 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2306 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002307 }
2308
Robert Greenwalt7b816022014-04-18 15:25:25 -07002309 private void handleAsyncChannelHalfConnect(Message msg) {
2310 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002311 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002312 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2313 if (VDBG) log("NetworkFactory connected");
2314 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002315 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002316 if (nri.request.isListen()) continue;
Hugo Benichicd952782017-09-20 11:20:14 +09002317 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002318 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002319 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002320 }
2321 } else {
2322 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002323 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002324 }
2325 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2326 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2327 if (VDBG) log("NetworkAgent connected");
2328 // A network agent has requested a connection. Establish the connection.
2329 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2330 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2331 } else {
2332 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002333 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002334 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002335 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002336 synchronized (mNetworkForNetId) {
2337 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002338 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002339 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002340 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002341 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002342 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002343 }
2344 }
2345 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002346
Robert Greenwalt7b816022014-04-18 15:25:25 -07002347 private void handleAsyncChannelDisconnected(Message msg) {
2348 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2349 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002350 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002351 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002352 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002353 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002354 // TODO - if we move the logic to the network agent (have them disconnect
2355 // because they lost all their requests or because their score isn't good)
2356 // then they would disconnect organically, report their new state and then
2357 // disconnect the channel.
2358 if (nai.networkInfo.isConnected()) {
2359 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2360 null, null);
2361 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002362 final boolean wasDefault = isDefaultNetwork(nai);
2363 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002364 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002365 // Log default network disconnection before required book-keeping.
2366 // Let rematchAllNetworksAndRequests() below record a new default network event
2367 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2368 // whose timestamps tell how long it takes to recover a default network.
Hugo Benichi380a0632017-10-20 09:25:29 +09002369 long now = SystemClock.elapsedRealtime();
2370 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(now, null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002371 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002372 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002373 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2374 // by other networks that are already connected. Perhaps that can be done by
2375 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2376 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002377 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002378 mKeepaliveTracker.handleStopAllKeepalives(nai,
2379 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002380 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2381 // Disable wakeup packet monitoring for each interface.
2382 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2383 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002384 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002385 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002386 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002387 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002388 // Remove the NetworkAgent, but don't mark the netId as
2389 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002390 mNetworkForNetId.remove(nai.network.netId);
2391 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002392 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002393 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2394 NetworkRequest request = nai.requestAt(i);
Hugo Benichicd952782017-09-20 11:20:14 +09002395 NetworkAgentInfo currentNetwork = getNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002396 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Hugo Benichicd952782017-09-20 11:20:14 +09002397 clearNetworkForRequest(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002398 sendUpdatedScoreToFactories(request, 0);
2399 }
2400 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002401 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002402 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002403 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002404 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002405 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002406 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002407 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002408 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002409 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002410 if (nai.created) {
2411 // Tell netd to clean up the configuration for this network
2412 // (routing rules, DNS, etc).
2413 // This may be slow as it requires a lot of netd shelling out to ip and
2414 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2415 // after we've rematched networks with requests which should make a potential
2416 // fallback network the default or requested a new network from the
2417 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2418 // long time.
2419 try {
2420 mNetd.removeNetwork(nai.network.netId);
2421 } catch (Exception e) {
2422 loge("Exception removing network: " + e);
2423 }
Erik Klinea24d4592018-01-11 21:07:29 +09002424 mDnsManager.removeNetwork(nai.network);
Paul Jensen62d30802015-06-17 14:42:30 -04002425 }
2426 synchronized (mNetworkForNetId) {
2427 mNetIdInUse.delete(nai.network.netId);
2428 }
2429 } else {
2430 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2431 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002432 }
2433 }
2434
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002435 // If this method proves to be too slow then we can maintain a separate
2436 // pendingIntent => NetworkRequestInfo map.
2437 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2438 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2439 Intent intent = pendingIntent.getIntent();
2440 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2441 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2442 if (existingPendingIntent != null &&
2443 existingPendingIntent.getIntent().filterEquals(intent)) {
2444 return entry.getValue();
2445 }
2446 }
2447 return null;
2448 }
2449
2450 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2451 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2452
2453 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2454 if (existingRequest != null) { // remove the existing request.
2455 if (DBG) log("Replacing " + existingRequest.request + " with "
2456 + nri.request + " because their intents matched.");
2457 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2458 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002459 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002460 }
2461
Erik Klineda4bfa82015-04-30 12:58:40 +09002462 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002463 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002464 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002465 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002466 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002467 if (nri.request.networkCapabilities.hasSignalStrength() &&
2468 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2469 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002470 }
2471 }
2472 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002473 rematchAllNetworksAndRequests(null, 0);
Hugo Benichicd952782017-09-20 11:20:14 +09002474 if (nri.request.isRequest() && getNetworkForRequest(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002475 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002476 }
2477 }
2478
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002479 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2480 int callingUid) {
2481 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2482 if (nri != null) {
2483 handleReleaseNetworkRequest(nri.request, callingUid);
2484 }
2485 }
2486
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002487 // Determines whether the network is the best (or could become the best, if it validated), for
2488 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2489 // on the value of reason:
2490 //
2491 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2492 // then it should be torn down.
2493 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2494 // then it should be lingered.
2495 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2496 final int numRequests;
2497 switch (reason) {
2498 case TEARDOWN:
2499 numRequests = nai.numRequestNetworkRequests();
2500 break;
2501 case LINGER:
2502 numRequests = nai.numForegroundNetworkRequests();
2503 break;
2504 default:
2505 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2506 return true;
2507 }
2508
2509 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002510 return false;
2511 }
Paul Jensene0988542015-06-25 15:30:08 -04002512 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002513 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2514 // Background requests don't affect lingering.
2515 continue;
2516 }
2517
Paul Jensene0988542015-06-25 15:30:08 -04002518 // If this Network is already the highest scoring Network for a request, or if
2519 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002520 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002521 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002522 // Note that this catches two important cases:
2523 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2524 // is currently satisfying the request. This is desirable when
2525 // cellular ends up validating but WiFi does not.
2526 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002527 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002528 // WiFi ends up validating and out scoring cellular.
Hugo Benichicd952782017-09-20 11:20:14 +09002529 getNetworkForRequest(nri.request.requestId).getCurrentScore() <
Paul Jensene0988542015-06-25 15:30:08 -04002530 nai.getCurrentScoreAsValidated())) {
2531 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002532 }
2533 }
Paul Jensene0988542015-06-25 15:30:08 -04002534 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002535 }
2536
Erik Klineacdd6392016-07-07 16:50:58 +09002537 private NetworkRequestInfo getNriForAppRequest(
2538 NetworkRequest request, int callingUid, String requestedOperation) {
2539 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2540
Robert Greenwalt9258c642014-03-26 16:47:06 -07002541 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002542 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002543 log(String.format("UID %d attempted to %s for unowned request %s",
2544 callingUid, requestedOperation, nri));
2545 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002546 }
Erik Klineacdd6392016-07-07 16:50:58 +09002547 }
2548
2549 return nri;
2550 }
2551
Erik Kline57faba92015-11-25 12:49:38 +09002552 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002553 if (mNetworkRequests.get(nri.request) == null) {
2554 return;
Erik Kline57faba92015-11-25 12:49:38 +09002555 }
Hugo Benichicd952782017-09-20 11:20:14 +09002556 if (getNetworkForRequest(nri.request.requestId) != null) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002557 return;
2558 }
2559 if (VDBG || (DBG && nri.request.isRequest())) {
2560 log("releasing " + nri.request + " (timeout)");
2561 }
2562 handleRemoveNetworkRequest(nri);
2563 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002564 }
2565
Erik Klineacdd6392016-07-07 16:50:58 +09002566 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002567 final NetworkRequestInfo nri =
2568 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2569 if (nri == null) {
2570 return;
Erik Kline57faba92015-11-25 12:49:38 +09002571 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002572 if (VDBG || (DBG && nri.request.isRequest())) {
2573 log("releasing " + nri.request + " (release request)");
2574 }
2575 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002576 }
Erik Klineacdd6392016-07-07 16:50:58 +09002577
Hugo Benichidba33db2017-03-23 22:40:44 +09002578 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002579 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002580 mNetworkRequests.remove(nri.request);
Erik Kline33d8e5c2018-01-15 17:05:07 +09002581
Erik Klineacdd6392016-07-07 16:50:58 +09002582 synchronized (mUidToNetworkRequestCount) {
2583 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2584 if (requests < 1) {
2585 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2586 nri.mUid);
2587 } else if (requests == 1) {
2588 mUidToNetworkRequestCount.removeAt(
2589 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2590 } else {
2591 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2592 }
2593 }
Erik Kline33d8e5c2018-01-15 17:05:07 +09002594
Erik Klineacdd6392016-07-07 16:50:58 +09002595 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2596 if (nri.request.isRequest()) {
2597 boolean wasKept = false;
Hugo Benichicd952782017-09-20 11:20:14 +09002598 NetworkAgentInfo nai = getNetworkForRequest(nri.request.requestId);
Erik Klineacdd6392016-07-07 16:50:58 +09002599 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002600 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002601 nai.removeRequest(nri.request.requestId);
2602 if (VDBG) {
2603 log(" Removing from current network " + nai.name() +
2604 ", leaving " + nai.numNetworkRequests() + " requests.");
2605 }
2606 // If there are still lingered requests on this network, don't tear it down,
2607 // but resume lingering instead.
2608 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002609 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002610 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2611 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002612 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002613 wasKept = true;
2614 }
Hugo Benichicd952782017-09-20 11:20:14 +09002615 clearNetworkForRequest(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002616 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2617 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002618 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002619 }
Erik Klineacdd6392016-07-07 16:50:58 +09002620 }
2621
2622 // TODO: remove this code once we know that the Slog.wtf is never hit.
2623 //
2624 // Find all networks that are satisfying this request and remove the request
2625 // from their request lists.
2626 // TODO - it's my understanding that for a request there is only a single
2627 // network satisfying it, so this loop is wasteful
2628 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2629 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2630 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2631 otherNai.name() + ", but mNetworkAgentInfos says " +
2632 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002633 }
2634 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002635
Erik Klineacdd6392016-07-07 16:50:58 +09002636 // Maintain the illusion. When this request arrived, we might have pretended
2637 // that a network connected to serve it, even though the network was already
2638 // connected. Now that this request has gone away, we might have to pretend
2639 // that the network disconnected. LegacyTypeTracker will generate that
2640 // phantom disconnect for this type.
2641 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2642 boolean doRemove = true;
2643 if (wasKept) {
2644 // check if any of the remaining requests for this network are for the
2645 // same legacy type - if so, don't remove the nai
2646 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2647 NetworkRequest otherRequest = nai.requestAt(i);
2648 if (otherRequest.legacyType == nri.request.legacyType &&
2649 otherRequest.isRequest()) {
2650 if (DBG) log(" still have other legacy request - leaving");
2651 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002652 }
2653 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002654 }
2655
Erik Klineacdd6392016-07-07 16:50:58 +09002656 if (doRemove) {
2657 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002658 }
2659 }
Erik Klineacdd6392016-07-07 16:50:58 +09002660
2661 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2662 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2663 nri.request);
2664 }
2665 } else {
2666 // listens don't have a singular affectedNetwork. Check all networks to see
2667 // if this listen request applies and remove it.
2668 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2669 nai.removeRequest(nri.request.requestId);
2670 if (nri.request.networkCapabilities.hasSignalStrength() &&
2671 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2672 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2673 }
2674 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002675 }
2676 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002677
Lorenzo Colitti18660282016-07-04 12:55:44 +09002678 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002679 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2680 enforceConnectivityInternalPermission();
2681 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002682 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002683 }
2684
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002685 @Override
2686 public void setAvoidUnvalidated(Network network) {
2687 enforceConnectivityInternalPermission();
2688 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2689 }
2690
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002691 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2692 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2693 " accept=" + accept + " always=" + always);
2694
2695 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2696 if (nai == null) {
2697 // Nothing to do.
2698 return;
2699 }
2700
2701 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002702 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002703 return;
2704 }
2705
2706 if (!nai.networkMisc.explicitlySelected) {
2707 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2708 }
2709
2710 if (accept != nai.networkMisc.acceptUnvalidated) {
2711 int oldScore = nai.getCurrentScore();
2712 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002713 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002714 sendUpdatedScoreToFactories(nai);
2715 }
2716
2717 if (always) {
2718 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002719 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002720 }
2721
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002722 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002723 // Tell the NetworkAgent to not automatically reconnect to the network.
2724 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2725 // Teardown the nework.
2726 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002727 }
2728
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002729 }
2730
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002731 private void handleSetAvoidUnvalidated(Network network) {
2732 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2733 if (nai == null || nai.lastValidated) {
2734 // Nothing to do. The network either disconnected or revalidated.
2735 return;
2736 }
2737 if (!nai.avoidUnvalidated) {
2738 int oldScore = nai.getCurrentScore();
2739 nai.avoidUnvalidated = true;
2740 rematchAllNetworksAndRequests(nai, oldScore);
2741 sendUpdatedScoreToFactories(nai);
2742 }
2743 }
2744
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002745 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002746 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002747 mHandler.sendMessageDelayed(
2748 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2749 PROMPT_UNVALIDATED_DELAY_MS);
2750 }
2751
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002752 @Override
2753 public void startCaptivePortalApp(Network network) {
2754 enforceConnectivityInternalPermission();
2755 mHandler.post(() -> {
2756 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2757 if (nai == null) return;
2758 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2759 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2760 });
2761 }
2762
Hugo Benichic8e9e122016-09-14 23:23:08 +00002763 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002764 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002765 }
2766
Erik Kline065ab6e2016-10-02 18:02:14 +09002767 private void rematchForAvoidBadWifiUpdate() {
2768 rematchAllNetworksAndRequests(null, 0);
2769 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2770 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2771 sendUpdatedScoreToFactories(nai);
2772 }
2773 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002774 }
2775
Erik Kline065ab6e2016-10-02 18:02:14 +09002776 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002777 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002778 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002779 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002780 if (!configRestrict) {
2781 pw.println("Bad Wi-Fi avoidance: unrestricted");
2782 return;
2783 }
2784
2785 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2786 pw.increaseIndent();
2787 pw.println("Config restrict: " + configRestrict);
2788
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002789 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002790 String description;
2791 // Can't use a switch statement because strings are legal case labels, but null is not.
2792 if ("0".equals(value)) {
2793 description = "get stuck";
2794 } else if (value == null) {
2795 description = "prompt";
2796 } else if ("1".equals(value)) {
2797 description = "avoid";
2798 } else {
2799 description = value + " (?)";
2800 }
2801 pw.println("User setting: " + description);
2802 pw.println("Network overrides:");
2803 pw.increaseIndent();
2804 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2805 if (nai.avoidUnvalidated) {
2806 pw.println(nai.name());
2807 }
2808 }
2809 pw.decreaseIndent();
2810 pw.decreaseIndent();
2811 }
2812
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002813 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2814 final String action;
2815 switch (type) {
2816 case NO_INTERNET:
2817 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2818 break;
2819 case LOST_INTERNET:
2820 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2821 break;
2822 default:
2823 Slog.wtf(TAG, "Unknown notification type " + type);
2824 return;
2825 }
2826
2827 Intent intent = new Intent(action);
2828 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2829 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2830 intent.setClassName("com.android.settings",
2831 "com.android.settings.wifi.WifiNoInternetDialog");
2832
2833 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2834 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2835 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2836 }
2837
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002838 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002839 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002840 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2841
2842 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2843 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002844 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002845 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002846 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2847 return;
2848 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002849 showValidationNotification(nai, NotificationType.NO_INTERNET);
2850 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002851
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002852 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2853 NetworkCapabilities nc = nai.networkCapabilities;
2854 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002855
Erik Kline065ab6e2016-10-02 18:02:14 +09002856 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002857 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002858 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2859 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002860 }
2861
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002862 @Override
2863 public int getMultipathPreference(Network network) {
2864 enforceAccessPermission();
2865
2866 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002867 if (nai != null && nai.networkCapabilities
2868 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002869 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2870 }
2871
2872 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2873 }
2874
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002875 private class InternalHandler extends Handler {
2876 public InternalHandler(Looper looper) {
2877 super(looper);
2878 }
2879
2880 @Override
2881 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002882 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002883 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002884 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002885 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002886 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002887 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002888 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002889 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002890 break;
2891 }
Jason Monkdecd2952013-10-10 14:02:51 -04002892 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002893 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002894 break;
2895 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002896 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002897 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2898 break;
2899 }
2900 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2901 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002902 break;
2903 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002904 case EVENT_REGISTER_NETWORK_AGENT: {
2905 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2906 break;
2907 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002908 case EVENT_REGISTER_NETWORK_REQUEST:
2909 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002910 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002911 break;
2912 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002913 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2914 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002915 handleRegisterNetworkRequestWithIntent(msg);
2916 break;
2917 }
Erik Kline57faba92015-11-25 12:49:38 +09002918 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2919 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2920 handleTimedOutNetworkRequest(nri);
2921 break;
2922 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002923 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2924 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2925 break;
2926 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002927 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002928 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002929 break;
2930 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002931 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002932 Network network = (Network) msg.obj;
2933 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002934 break;
2935 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002936 case EVENT_SET_AVOID_UNVALIDATED: {
2937 handleSetAvoidUnvalidated((Network) msg.obj);
2938 break;
2939 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002940 case EVENT_PROMPT_UNVALIDATED: {
2941 handlePromptUnvalidated((Network) msg.obj);
2942 break;
2943 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002944 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2945 handleMobileDataAlwaysOn();
2946 break;
2947 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002948 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2949 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2950 mKeepaliveTracker.handleStartKeepalive(msg);
2951 break;
2952 }
2953 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2954 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2955 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2956 int slot = msg.arg1;
2957 int reason = msg.arg2;
2958 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2959 break;
2960 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002961 case EVENT_SYSTEM_READY: {
2962 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2963 nai.networkMonitor.systemReady = true;
2964 }
2965 break;
2966 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002967 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002968 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002969 break;
2970 }
Erik Klinea24d4592018-01-11 21:07:29 +09002971 case EVENT_PRIVATE_DNS_SETTINGS_CHANGED:
2972 handlePrivateDnsSettingsChanged();
2973 break;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002974 }
2975 }
2976 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002977
2978 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002979 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002980 public int tether(String iface, String callerPkg) {
2981 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002982 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002983 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002984 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002985 } else {
2986 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2987 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002988 }
2989
2990 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002991 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002992 public int untether(String iface, String callerPkg) {
2993 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002994
2995 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002996 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002997 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002998 } else {
2999 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3000 }
3001 }
3002
3003 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003004 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003005 public int getLastTetherError(String iface) {
3006 enforceTetherAccessPermission();
3007
3008 if (isTetheringSupported()) {
3009 return mTethering.getLastTetherError(iface);
3010 } else {
3011 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3012 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003013 }
3014
3015 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09003016 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003017 public String[] getTetherableUsbRegexs() {
3018 enforceTetherAccessPermission();
3019 if (isTetheringSupported()) {
3020 return mTethering.getTetherableUsbRegexs();
3021 } else {
3022 return new String[0];
3023 }
3024 }
3025
Lorenzo Colitti18660282016-07-04 12:55:44 +09003026 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003027 public String[] getTetherableWifiRegexs() {
3028 enforceTetherAccessPermission();
3029 if (isTetheringSupported()) {
3030 return mTethering.getTetherableWifiRegexs();
3031 } else {
3032 return new String[0];
3033 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003034 }
3035
Lorenzo Colitti18660282016-07-04 12:55:44 +09003036 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07003037 public String[] getTetherableBluetoothRegexs() {
3038 enforceTetherAccessPermission();
3039 if (isTetheringSupported()) {
3040 return mTethering.getTetherableBluetoothRegexs();
3041 } else {
3042 return new String[0];
3043 }
3044 }
3045
Lorenzo Colitti18660282016-07-04 12:55:44 +09003046 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003047 public int setUsbTethering(boolean enable, String callerPkg) {
3048 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07003049 if (isTetheringSupported()) {
3050 return mTethering.setUsbTethering(enable);
3051 } else {
3052 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
3053 }
3054 }
3055
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003056 // TODO - move iface listing, queries, etc to new module
3057 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09003058 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003059 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003060 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003061 return mTethering.getTetherableIfaces();
3062 }
3063
Lorenzo Colitti18660282016-07-04 12:55:44 +09003064 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003065 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003066 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08003067 return mTethering.getTetheredIfaces();
3068 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003069
Lorenzo Colitti18660282016-07-04 12:55:44 +09003070 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08003071 public String[] getTetheringErroredIfaces() {
3072 enforceTetherAccessPermission();
3073 return mTethering.getErroredIfaces();
3074 }
3075
Lorenzo Colitti18660282016-07-04 12:55:44 +09003076 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07003077 public String[] getTetheredDhcpRanges() {
3078 enforceConnectivityInternalPermission();
3079 return mTethering.getTetheredDhcpRanges();
3080 }
3081
Udam Sainic3b640c2017-06-07 12:06:28 -07003082 @Override
3083 public boolean isTetheringSupported(String callerPkg) {
3084 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
3085 return isTetheringSupported();
3086 }
3087
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003088 // if ro.tether.denied = true we default to no tethering
3089 // gservices could set the secure setting to 1 though to enable it on a build where it
3090 // had previously been turned off.
Udam Sainic3b640c2017-06-07 12:06:28 -07003091 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003092 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
3093 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
3094 Settings.Global.TETHER_SUPPORTED, defaultVal));
3095 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04003096 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07003097
3098 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
3099 boolean adminUser = false;
3100 final long token = Binder.clearCallingIdentity();
3101 try {
3102 adminUser = mUserManager.isAdminUser();
3103 } finally {
3104 Binder.restoreCallingIdentity(token);
3105 }
3106
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003107 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003108 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003109
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003110 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003111 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3112 String callerPkg) {
3113 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003114 if (!isTetheringSupported()) {
3115 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3116 return;
3117 }
3118 mTethering.startTethering(type, receiver, showProvisioningUi);
3119 }
3120
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003121 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003122 public void stopTethering(int type, String callerPkg) {
3123 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003124 mTethering.stopTethering(type);
3125 }
3126
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003127 // Called when we lose the default network and have no replacement yet.
3128 // This will automatically be cleared after X seconds or a new default network
3129 // becomes CONNECTED, whichever happens first. The timer is started by the
3130 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003131 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003132 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003133 if (mNetTransitionWakeLock.isHeld()) {
3134 return;
3135 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003136 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003137 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3138 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003139 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003140 mWakelockLogs.log("ACQUIRE for " + forWhom);
3141 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3142 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003143 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003144
Hugo Benichi4c31b342017-03-30 23:18:10 +09003145 // Called when we gain a new default network to release the network transition wakelock in a
3146 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3147 // message is cancelled.
3148 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003149 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003150 if (!mNetTransitionWakeLock.isHeld()) {
3151 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003152 }
3153 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003154 // Cancel self timeout on wakelock hold.
3155 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3156 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3157 mHandler.sendMessageDelayed(msg, 1000);
3158 }
3159
3160 // Called when either message of ensureNetworkTransitionWakelock or
3161 // scheduleReleaseNetworkTransitionWakelock is processed.
3162 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3163 String event = eventName(eventId);
3164 synchronized (this) {
3165 if (!mNetTransitionWakeLock.isHeld()) {
3166 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3167 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3168 return;
3169 }
3170 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003171 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3172 mTotalWakelockDurationMs += lockDuration;
3173 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3174 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003175 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003176 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003177 }
3178
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003179 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003180 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003181 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003182 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003183 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003184 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003185 }
3186
Lorenzo Colitti18660282016-07-04 12:55:44 +09003187 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003188 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003189 enforceAccessPermission();
3190 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003191 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003192 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003193 mHandler.sendMessage(
3194 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3195 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003196
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003197 private void handleReportNetworkConnectivity(
3198 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003199 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003200 if (network == null) {
3201 nai = getDefaultNetwork();
3202 } else {
3203 nai = getNetworkAgentInfoForNetwork(network);
3204 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003205 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3206 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3207 return;
3208 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003209 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003210 if (hasConnectivity == nai.lastValidated) {
3211 return;
3212 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003213 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003214 int netid = nai.network.netId;
3215 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003216 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003217 // Validating a network that has not yet connected could result in a call to
3218 // rematchNetworkAndRequests() which is not meant to work on such networks.
3219 if (!nai.everConnected) {
3220 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003221 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003222 LinkProperties lp = getLinkProperties(nai);
3223 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3224 return;
3225 }
3226 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003227 }
3228
Paul Jensencee9b512015-05-06 07:32:40 -04003229 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003230 // this information is already available as a world read/writable jvm property
3231 // so this API change wouldn't have a benifit. It also breaks the passing
3232 // of proxy info to all the JVMs.
3233 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003234 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003235 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003236 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3237 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003238 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003239 }
3240
Lorenzo Colitti18660282016-07-04 12:55:44 +09003241 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003242 public ProxyInfo getProxyForNetwork(Network network) {
3243 if (network == null) return getDefaultProxy();
3244 final ProxyInfo globalProxy = getGlobalProxy();
3245 if (globalProxy != null) return globalProxy;
3246 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3247 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3248 // caller may not have.
3249 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3250 if (nai == null) return null;
3251 synchronized (nai) {
3252 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3253 if (proxyInfo == null) return null;
3254 return new ProxyInfo(proxyInfo);
3255 }
3256 }
3257
Paul Jensene0bef712014-12-10 15:12:18 -05003258 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3259 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3260 // proxy is null then there is no proxy in place).
3261 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3262 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3263 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3264 proxy = null;
3265 }
3266 return proxy;
3267 }
3268
3269 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3270 // better for determining if a new proxy broadcast is necessary:
3271 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3272 // avoid unnecessary broadcasts.
3273 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3274 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3275 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3276 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3277 // all set.
3278 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3279 a = canonicalizeProxyInfo(a);
3280 b = canonicalizeProxyInfo(b);
3281 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3282 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3283 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3284 }
3285
Jason Monk207900c2014-04-25 15:00:09 -04003286 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003287 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003288
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003289 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003290 if (proxyProperties == mGlobalProxy) return;
3291 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3292 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3293
3294 String host = "";
3295 int port = 0;
3296 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003297 String pacFileUrl = "";
3298 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003299 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003300 if (!proxyProperties.isValid()) {
3301 if (DBG)
3302 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3303 return;
3304 }
Jason Monk207900c2014-04-25 15:00:09 -04003305 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003306 host = mGlobalProxy.getHost();
3307 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003308 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003309 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003310 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003311 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003312 } else {
3313 mGlobalProxy = null;
3314 }
3315 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003316 final long token = Binder.clearCallingIdentity();
3317 try {
3318 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3319 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3320 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3321 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003322 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003323 } finally {
3324 Binder.restoreCallingIdentity(token);
3325 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003326
Jason Monkcf0f97a2014-10-02 15:39:38 -04003327 if (mGlobalProxy == null) {
3328 proxyProperties = mDefaultProxy;
3329 }
3330 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003331 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003332 }
3333
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003334 private void loadGlobalProxy() {
3335 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003336 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3337 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3338 String exclList = Settings.Global.getString(res,
3339 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003340 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3341 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003342 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003343 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003344 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003345 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003346 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003347 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003348 if (!proxyProperties.isValid()) {
3349 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3350 return;
3351 }
3352
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003353 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003354 mGlobalProxy = proxyProperties;
3355 }
3356 }
3357 }
3358
Jason Monk207900c2014-04-25 15:00:09 -04003359 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003360 // this information is already available as a world read/writable jvm property
3361 // so this API change wouldn't have a benifit. It also breaks the passing
3362 // of proxy info to all the JVMs.
3363 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003364 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003365 return mGlobalProxy;
3366 }
3367 }
3368
Jason Monk207900c2014-04-25 15:00:09 -04003369 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003370 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003371 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003372 proxy = null;
3373 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003374 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003375 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003376 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003377 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003378 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3379 return;
3380 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003381
3382 // This call could be coming from the PacManager, containing the port of the local
3383 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3384 // global (to get the correct local port), and send a broadcast.
3385 // TODO: Switch PacManager to have its own message to send back rather than
3386 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003387 if ((mGlobalProxy != null) && (proxy != null)
3388 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003389 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3390 mGlobalProxy = proxy;
3391 sendProxyBroadcast(mGlobalProxy);
3392 return;
3393 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003394 mDefaultProxy = proxy;
3395
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003396 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003397 if (!mDefaultProxyDisabled) {
3398 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003399 }
3400 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003401 }
3402
Paul Jensene0bef712014-12-10 15:12:18 -05003403 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3404 // This method gets called when any network changes proxy, but the broadcast only ever contains
3405 // the default proxy (even if it hasn't changed).
3406 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3407 // world where an app might be bound to a non-default network.
3408 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3409 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3410 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3411
3412 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3413 sendProxyBroadcast(getDefaultProxy());
3414 }
3415 }
3416
Robert Greenwalt434203a2010-10-11 16:00:27 -07003417 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003418 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3419 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003420 if (!TextUtils.isEmpty(proxy)) {
3421 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003422 if (data.length == 0) {
3423 return;
3424 }
3425
Robert Greenwalt434203a2010-10-11 16:00:27 -07003426 String proxyHost = data[0];
3427 int proxyPort = 8080;
3428 if (data.length > 1) {
3429 try {
3430 proxyPort = Integer.parseInt(data[1]);
3431 } catch (NumberFormatException e) {
3432 return;
3433 }
3434 }
Jason Monk207900c2014-04-25 15:00:09 -04003435 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003436 setGlobalProxy(p);
3437 }
3438 }
3439
Jason Monk207900c2014-04-25 15:00:09 -04003440 private void sendProxyBroadcast(ProxyInfo proxy) {
3441 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003442 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003443 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003444 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003445 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3446 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003447 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003448 final long ident = Binder.clearCallingIdentity();
3449 try {
3450 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3451 } finally {
3452 Binder.restoreCallingIdentity(ident);
3453 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003454 }
3455
3456 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003457 final private HashMap<Uri, Integer> mUriEventMap;
3458 final private Context mContext;
3459 final private Handler mHandler;
3460
3461 SettingsObserver(Context context, Handler handler) {
3462 super(null);
3463 mUriEventMap = new HashMap<Uri, Integer>();
3464 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003465 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003466 }
3467
Erik Klineda4bfa82015-04-30 12:58:40 +09003468 void observe(Uri uri, int what) {
3469 mUriEventMap.put(uri, what);
3470 final ContentResolver resolver = mContext.getContentResolver();
3471 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003472 }
3473
3474 @Override
3475 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003476 Slog.wtf(TAG, "Should never be reached.");
3477 }
3478
3479 @Override
3480 public void onChange(boolean selfChange, Uri uri) {
3481 final Integer what = mUriEventMap.get(uri);
3482 if (what != null) {
3483 mHandler.obtainMessage(what.intValue()).sendToTarget();
3484 } else {
3485 loge("No matching event to send for URI=" + uri);
3486 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003487 }
3488 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003489
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003490 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003491 Slog.d(TAG, s);
3492 }
3493
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003494 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003495 Slog.e(TAG, s);
3496 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003497
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003498 private static void loge(String s, Throwable t) {
3499 Slog.e(TAG, s, t);
3500 }
3501
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003502 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003503 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003504 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3505 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3506 *
3507 * @param oldPackage Package name of the application which currently controls VPN, which will
3508 * be replaced. If there is no such application, this should should either be
3509 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3510 * @param newPackage Package name of the application which should gain control of VPN, or
3511 * {@code null} to disable.
3512 * @param userId User for whom to prepare the new VPN.
3513 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003514 * @hide
3515 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003516 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003517 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3518 int userId) {
3519 enforceCrossUserPermission(userId);
Robin Lee3b3dd942015-05-12 18:14:58 +01003520
Hugo Benichi20035e02017-04-26 14:53:28 +09003521 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003522 throwIfLockdownEnabled();
Robin Lee47283452015-06-01 10:57:03 -07003523 Vpn vpn = mVpns.get(userId);
3524 if (vpn != null) {
3525 return vpn.prepare(oldPackage, newPackage);
3526 } else {
3527 return false;
3528 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003529 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003530 }
3531
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003532 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003533 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3534 * This method is used by system-privileged apps.
3535 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3536 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3537 *
3538 * @param packageName The package for which authorization state should change.
3539 * @param userId User for whom {@code packageName} is installed.
3540 * @param authorized {@code true} if this app should be able to start a VPN connection without
3541 * explicit user approval, {@code false} if not.
3542 *
Jeff Davidson05542602014-08-11 14:07:27 -07003543 * @hide
3544 */
3545 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003546 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3547 enforceCrossUserPermission(userId);
3548
Hugo Benichi20035e02017-04-26 14:53:28 +09003549 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003550 Vpn vpn = mVpns.get(userId);
3551 if (vpn != null) {
3552 vpn.setPackageAuthorization(packageName, authorized);
3553 }
Jeff Davidson05542602014-08-11 14:07:27 -07003554 }
3555 }
3556
3557 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003558 * Configure a TUN interface and return its file descriptor. Parameters
3559 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003560 * and not available in ConnectivityManager. Permissions are checked in
3561 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003562 * @hide
3563 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003564 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003565 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003566 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003567 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003568 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003569 return mVpns.get(user).establish(config);
3570 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003571 }
3572
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003573 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003574 * Start legacy VPN, controlling native daemons as needed. Creates a
3575 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003576 */
3577 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003578 public void startLegacyVpn(VpnProfile profile) {
Hugo Benichi69744342017-11-27 10:57:16 +09003579 int user = UserHandle.getUserId(Binder.getCallingUid());
Jeff Sharkey82f85212012-08-24 11:17:25 -07003580 final LinkProperties egress = getActiveLinkProperties();
3581 if (egress == null) {
3582 throw new IllegalStateException("Missing active network connection");
3583 }
Hugo Benichi20035e02017-04-26 14:53:28 +09003584 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003585 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003586 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3587 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003588 }
3589
3590 /**
3591 * Return the information of the ongoing legacy VPN. This method is used
3592 * by VpnSettings and not available in ConnectivityManager. Permissions
3593 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003594 */
3595 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003596 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3597 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003598
Hugo Benichi20035e02017-04-26 14:53:28 +09003599 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003600 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003601 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003602 }
3603
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003604 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003605 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3606 * and not available in ConnectivityManager.
3607 */
3608 @Override
3609 public VpnInfo[] getAllVpnInfo() {
3610 enforceConnectivityInternalPermission();
Hugo Benichi20035e02017-04-26 14:53:28 +09003611 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003612 if (mLockdownEnabled) {
3613 return new VpnInfo[0];
3614 }
3615
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003616 List<VpnInfo> infoList = new ArrayList<>();
3617 for (int i = 0; i < mVpns.size(); i++) {
3618 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3619 if (info != null) {
3620 infoList.add(info);
3621 }
3622 }
3623 return infoList.toArray(new VpnInfo[infoList.size()]);
3624 }
3625 }
3626
3627 /**
3628 * @return VPN information for accounting, or null if we can't retrieve all required
3629 * information, e.g primary underlying iface.
3630 */
3631 @Nullable
3632 private VpnInfo createVpnInfo(Vpn vpn) {
3633 VpnInfo info = vpn.getVpnInfo();
3634 if (info == null) {
3635 return null;
3636 }
3637 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3638 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3639 // the underlyingNetworks list.
3640 if (underlyingNetworks == null) {
3641 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3642 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3643 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3644 }
3645 } else if (underlyingNetworks.length > 0) {
3646 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3647 if (linkProperties != null) {
3648 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3649 }
3650 }
3651 return info.primaryUnderlyingIface == null ? null : info;
3652 }
3653
3654 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003655 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3656 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003657 * Permissions are checked in Vpn class.
3658 * @hide
3659 */
3660 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003661 public VpnConfig getVpnConfig(int userId) {
3662 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003663 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003664 Vpn vpn = mVpns.get(userId);
3665 if (vpn != null) {
3666 return vpn.getVpnConfig();
3667 } else {
3668 return null;
3669 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003670 }
3671 }
3672
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003673 @Override
3674 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003675 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3676 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3677 return false;
3678 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003679
Hugo Benichi69744342017-11-27 10:57:16 +09003680 synchronized (mVpns) {
3681 // Tear down existing lockdown if profile was removed
3682 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3683 if (mLockdownEnabled) {
3684 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3685 if (profileTag == null) {
3686 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3687 return false;
3688 }
3689 String profileName = new String(profileTag);
3690 final VpnProfile profile = VpnProfile.decode(
3691 profileName, mKeyStore.get(Credentials.VPN + profileName));
3692 if (profile == null) {
3693 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3694 setLockdownTracker(null);
3695 return true;
3696 }
3697 int user = UserHandle.getUserId(Binder.getCallingUid());
Robin Lee18566c12016-03-14 13:08:48 +00003698 Vpn vpn = mVpns.get(user);
3699 if (vpn == null) {
3700 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3701 return false;
3702 }
3703 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Hugo Benichi69744342017-11-27 10:57:16 +09003704 } else {
3705 setLockdownTracker(null);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003706 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003707 }
3708
3709 return true;
3710 }
3711
3712 /**
3713 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3714 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3715 */
Hugo Benichi69744342017-11-27 10:57:16 +09003716 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003717 private void setLockdownTracker(LockdownVpnTracker tracker) {
3718 // Shutdown any existing tracker
3719 final LockdownVpnTracker existing = mLockdownTracker;
3720 mLockdownTracker = null;
3721 if (existing != null) {
3722 existing.shutdown();
3723 }
3724
Robin Leec3736bc2017-03-10 16:19:54 +00003725 if (tracker != null) {
3726 mLockdownTracker = tracker;
3727 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003728 }
3729 }
3730
Hugo Benichi69744342017-11-27 10:57:16 +09003731 @GuardedBy("mVpns")
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003732 private void throwIfLockdownEnabled() {
3733 if (mLockdownEnabled) {
3734 throw new IllegalStateException("Unavailable in lockdown mode");
3735 }
3736 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003737
Robin Lee244ce8e2016-01-05 18:03:46 +00003738 /**
Robin Lee17e61832016-05-09 13:46:28 +01003739 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3740 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003741 *
Robin Lee17e61832016-05-09 13:46:28 +01003742 * @return {@code true} if the service was started, the service was already connected, or there
3743 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003744 */
Robin Lee17e61832016-05-09 13:46:28 +01003745 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003746 synchronized (mVpns) {
3747 Vpn vpn = mVpns.get(userId);
3748 if (vpn == null) {
3749 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3750 // exists already.
3751 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3752 return false;
3753 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003754
Robin Lee812800c2016-05-13 15:38:08 +01003755 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003756 }
3757 }
3758
3759 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003760 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3761 enforceSettingsPermission();
3762 enforceCrossUserPermission(userId);
3763
3764 synchronized (mVpns) {
3765 Vpn vpn = mVpns.get(userId);
3766 if (vpn == null) {
3767 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3768 return false;
3769 }
3770 return vpn.isAlwaysOnPackageSupported(packageName);
3771 }
3772 }
3773
3774 @Override
Robin Leedc679712016-05-03 13:23:03 +01003775 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003776 enforceConnectivityInternalPermission();
3777 enforceCrossUserPermission(userId);
3778
Robin Lee244ce8e2016-01-05 18:03:46 +00003779 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09003780 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3781 if (LockdownVpnTracker.isEnabled()) {
3782 return false;
3783 }
3784
Robin Lee244ce8e2016-01-05 18:03:46 +00003785 Vpn vpn = mVpns.get(userId);
3786 if (vpn == null) {
3787 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3788 return false;
3789 }
Robin Lee17e61832016-05-09 13:46:28 +01003790 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003791 return false;
3792 }
Robin Lee17e61832016-05-09 13:46:28 +01003793 if (!startAlwaysOnVpn(userId)) {
3794 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003795 return false;
3796 }
3797 }
3798 return true;
3799 }
3800
3801 @Override
3802 public String getAlwaysOnVpnPackage(int userId) {
3803 enforceConnectivityInternalPermission();
3804 enforceCrossUserPermission(userId);
3805
3806 synchronized (mVpns) {
3807 Vpn vpn = mVpns.get(userId);
3808 if (vpn == null) {
3809 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3810 return null;
3811 }
3812 return vpn.getAlwaysOnPackage();
3813 }
3814 }
3815
Wink Savilleab9321d2013-06-29 21:10:57 -07003816 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003817 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003818 // TODO: Remove? Any reason to trigger a provisioning check?
3819 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003820 }
3821
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003822 /** Location to an updatable file listing carrier provisioning urls.
3823 * An example:
3824 *
3825 * <?xml version="1.0" encoding="utf-8"?>
3826 * <provisioningUrls>
3827 * <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 -07003828 * </provisioningUrls>
3829 */
3830 private static final String PROVISIONING_URL_PATH =
3831 "/data/misc/radio/provisioning_urls.xml";
3832 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003833
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003834 /** XML tag for root element. */
3835 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3836 /** XML tag for individual url */
3837 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003838 /** XML attribute for mcc */
3839 private static final String ATTR_MCC = "mcc";
3840 /** XML attribute for mnc */
3841 private static final String ATTR_MNC = "mnc";
3842
Paul Jensen434dde82015-06-11 09:43:30 -04003843 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003844 FileReader fileReader = null;
3845 XmlPullParser parser = null;
3846 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003847
3848 try {
3849 fileReader = new FileReader(mProvisioningUrlFile);
3850 parser = Xml.newPullParser();
3851 parser.setInput(fileReader);
3852 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3853
3854 while (true) {
3855 XmlUtils.nextElement(parser);
3856
3857 String element = parser.getName();
3858 if (element == null) break;
3859
Paul Jensen434dde82015-06-11 09:43:30 -04003860 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003861 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3862 try {
3863 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3864 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3865 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3866 parser.next();
3867 if (parser.getEventType() == XmlPullParser.TEXT) {
3868 return parser.getText();
3869 }
3870 }
3871 }
3872 } catch (NumberFormatException e) {
3873 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3874 }
3875 }
3876 }
3877 return null;
3878 } catch (FileNotFoundException e) {
3879 loge("Carrier Provisioning Urls file not found");
3880 } catch (XmlPullParserException e) {
3881 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3882 } catch (IOException e) {
3883 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3884 } finally {
3885 if (fileReader != null) {
3886 try {
3887 fileReader.close();
3888 } catch (IOException e) {}
3889 }
3890 }
3891 return null;
3892 }
3893
Wink Saville42d4f082013-07-20 20:31:59 -07003894 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003895 public String getMobileProvisioningUrl() {
3896 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003897 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003898 if (TextUtils.isEmpty(url)) {
3899 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003900 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003901 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003902 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003903 }
Wink Saville8cf35602013-07-10 23:00:07 -07003904 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003905 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003906 String phoneNumber = mTelephonyManager.getLine1Number();
3907 if (TextUtils.isEmpty(phoneNumber)) {
3908 phoneNumber = "0000000000";
3909 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003910 url = String.format(url,
3911 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3912 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003913 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003914 }
3915
Wink Savilleab9321d2013-06-29 21:10:57 -07003916 return url;
3917 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003918
Wink Saville948282b2013-08-29 08:55:16 -07003919 @Override
3920 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003921 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003922 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003923 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3924 return;
3925 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003926 final long ident = Binder.clearCallingIdentity();
3927 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003928 // Concatenate the range of types onto the range of NetIDs.
3929 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3930 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003931 } finally {
3932 Binder.restoreCallingIdentity(ident);
3933 }
Wink Saville948282b2013-08-29 08:55:16 -07003934 }
Wink Saville7788c612013-08-29 14:57:08 -07003935
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003936 @Override
3937 public void setAirplaneMode(boolean enable) {
3938 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003939 final long ident = Binder.clearCallingIdentity();
3940 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003941 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003942 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003943 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3944 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003945 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003946 } finally {
3947 Binder.restoreCallingIdentity(ident);
3948 }
3949 }
3950
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003951 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003952 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003953 Vpn userVpn = mVpns.get(userId);
3954 if (userVpn != null) {
3955 loge("Starting user already has a VPN");
3956 return;
3957 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003958 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003959 mVpns.put(userId, userVpn);
Hugo Benichi69744342017-11-27 10:57:16 +09003960 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3961 updateLockdownVpn();
3962 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003963 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003964 }
3965
3966 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003967 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003968 Vpn userVpn = mVpns.get(userId);
3969 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003970 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003971 return;
3972 }
Robin Lee17e61832016-05-09 13:46:28 +01003973 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003974 mVpns.delete(userId);
3975 }
3976 }
3977
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003978 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003979 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003980 final int vpnsSize = mVpns.size();
3981 for (int i = 0; i < vpnsSize; i++) {
3982 Vpn vpn = mVpns.valueAt(i);
3983 vpn.onUserAdded(userId);
3984 }
3985 }
3986 }
3987
3988 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003989 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003990 final int vpnsSize = mVpns.size();
3991 for (int i = 0; i < vpnsSize; i++) {
3992 Vpn vpn = mVpns.valueAt(i);
3993 vpn.onUserRemoved(userId);
3994 }
3995 }
3996 }
3997
Robin Lee89e7a692016-02-29 14:38:17 +00003998 private void onUserUnlocked(int userId) {
Hugo Benichi69744342017-11-27 10:57:16 +09003999 synchronized (mVpns) {
4000 // User present may be sent because of an unlock, which might mean an unlocked keystore.
4001 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
4002 updateLockdownVpn();
4003 } else {
4004 startAlwaysOnVpn(userId);
4005 }
Robin Lee9a5f4852015-12-17 11:42:22 +00004006 }
4007 }
4008
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004009 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
4010 @Override
4011 public void onReceive(Context context, Intent intent) {
4012 final String action = intent.getAction();
4013 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
4014 if (userId == UserHandle.USER_NULL) return;
4015
Robin Lee323f29d2016-05-04 16:38:06 +01004016 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004017 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07004018 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004019 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07004020 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
4021 onUserAdded(userId);
4022 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
4023 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00004024 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
4025 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07004026 }
4027 }
4028 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07004029
Robin Lee95204e02017-01-27 11:59:22 +00004030 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
4031 @Override
4032 public void onReceive(Context context, Intent intent) {
4033 // Try creating lockdown tracker, since user present usually means
4034 // unlocked keystore.
4035 updateLockdownVpn();
4036 mContext.unregisterReceiver(this);
4037 }
4038 };
4039
Robert Greenwalta67be032014-05-16 15:49:14 -07004040 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
4041 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004042 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
4043 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07004044
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004045 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
4046 // Map from UID to number of NetworkRequests that UID has filed.
4047 @GuardedBy("mUidToNetworkRequestCount")
4048 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
4049
Robert Greenwalta67be032014-05-16 15:49:14 -07004050 private static class NetworkFactoryInfo {
4051 public final String name;
4052 public final Messenger messenger;
4053 public final AsyncChannel asyncChannel;
4054
4055 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
4056 this.name = name;
4057 this.messenger = messenger;
4058 this.asyncChannel = asyncChannel;
4059 }
4060 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004062 private void ensureNetworkRequestHasType(NetworkRequest request) {
4063 if (request.type == NetworkRequest.Type.NONE) {
4064 throw new IllegalArgumentException(
4065 "All NetworkRequests in ConnectivityService must have a type");
4066 }
4067 }
4068
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004069 /**
4070 * Tracks info about the requester.
4071 * Also used to notice when the calling process dies so we can self-expire
4072 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07004073 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004074 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004075 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08004076 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004077 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004078 final int mPid;
4079 final int mUid;
4080 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004081
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004082 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004083 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004084 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004085 mPendingIntent = pi;
4086 messenger = null;
4087 mBinder = null;
4088 mPid = getCallingPid();
4089 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004090 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004091 }
4092
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004093 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004094 super();
4095 messenger = m;
4096 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004097 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004098 mBinder = binder;
4099 mPid = getCallingPid();
4100 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004101 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004102 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004103
4104 try {
4105 mBinder.linkToDeath(this, 0);
4106 } catch (RemoteException e) {
4107 binderDied();
4108 }
4109 }
4110
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004111 private void enforceRequestCountLimit() {
4112 synchronized (mUidToNetworkRequestCount) {
4113 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4114 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004115 throw new ServiceSpecificException(
4116 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004117 }
4118 mUidToNetworkRequestCount.put(mUid, networkRequests);
4119 }
4120 }
4121
Robert Greenwalt9258c642014-03-26 16:47:06 -07004122 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004123 if (mBinder != null) {
4124 mBinder.unlinkToDeath(this, 0);
4125 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004126 }
4127
4128 public void binderDied() {
4129 log("ConnectivityService NetworkRequestInfo binderDied(" +
4130 request + ", " + mBinder + ")");
4131 releaseNetworkRequest(request);
4132 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004133
4134 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004135 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004136 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004137 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004138 }
4139
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004140 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4141 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4142 if (badCapability != null) {
4143 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004144 }
4145 }
4146
Erik Kline9d598e12015-07-13 16:37:51 +09004147 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004148 final SortedSet<Integer> thresholds = new TreeSet();
4149 synchronized (nai) {
4150 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4151 if (nri.request.networkCapabilities.hasSignalStrength() &&
4152 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4153 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4154 }
4155 }
4156 }
Erik Kline9d598e12015-07-13 16:37:51 +09004157 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004158 }
4159
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004160 private void updateSignalStrengthThresholds(
4161 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4162 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004163 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004164 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4165
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004166 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004167 String detail;
4168 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4169 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4170 } else {
4171 detail = reason;
4172 }
4173 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4174 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4175 }
4176
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004177 nai.asyncChannel.sendMessage(
4178 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004179 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004180 }
4181
Etan Cohen859748f2017-04-03 17:42:34 -07004182 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4183 if (nc == null) {
4184 return;
4185 }
4186 NetworkSpecifier ns = nc.getNetworkSpecifier();
4187 if (ns == null) {
4188 return;
4189 }
4190 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4191 ns.assertValidFromUid(Binder.getCallingUid());
4192 }
4193
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 @Override
4195 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004196 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004197 final NetworkRequest.Type type = (networkCapabilities == null)
4198 ? NetworkRequest.Type.TRACK_DEFAULT
4199 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004200 // If the requested networkCapabilities is null, take them instead from
4201 // the default network request. This allows callers to keep track of
4202 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004203 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004204 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004205 networkCapabilities.removeCapability(NET_CAPABILITY_NOT_VPN);
Erik Klinea2d29402016-03-16 15:31:39 +09004206 enforceAccessPermission();
4207 } else {
4208 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4209 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004210 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4211 // of the app when the request is filed, but we never change the request if the app
4212 // changes network state. http://b/29964605
4213 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004214 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004215 ensureRequestableCapabilities(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004216 // Set the UID range for this request to the single UID of the requester.
4217 // This will overwrite any allowed UIDs in the requested capabilities. Though there
4218 // are no visible methods to set the UIDs, an app could use reflection to try and get
4219 // networks for other apps so it's essential that the UIDs are overwritten.
4220 // TODO : don't forcefully set the UID when communicating with processes
4221 // that have the NETWORK_SETTINGS permission.
4222 networkCapabilities.setSingleUid(Binder.getCallingUid());
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004223
Etan Cohenba07c8c2017-02-05 10:42:27 -08004224 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 throw new IllegalArgumentException("Bad timeout specified");
4226 }
Etan Cohen859748f2017-04-03 17:42:34 -07004227 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004228
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004229 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004230 nextNetworkRequestId(), type);
4231 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004232 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004233
4234 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004235 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004236 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004237 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004238 }
4239 return networkRequest;
4240 }
4241
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004242 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004243 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004244 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004245 } else {
4246 enforceChangePermission();
4247 }
4248 }
4249
fenglub15e72b2015-03-20 11:29:56 -07004250 @Override
fengludb571472015-04-21 17:12:05 -07004251 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004252 enforceAccessPermission();
4253 NetworkAgentInfo nai = null;
4254 if (network == null) {
4255 return false;
4256 }
4257 synchronized (mNetworkForNetId) {
4258 nai = mNetworkForNetId.get(network.netId);
4259 }
4260 if (nai != null) {
4261 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4262 return true;
4263 }
4264 return false;
4265 }
4266
Felipe Lemeee27cab2016-06-20 16:36:29 -07004267 private boolean isSystem(int uid) {
4268 return uid < Process.FIRST_APPLICATION_UID;
4269 }
fenglub15e72b2015-03-20 11:29:56 -07004270
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004271 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004272 final int uid = Binder.getCallingUid();
4273 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004274 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004275 return;
4276 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004277 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4278 // Policy already enforced.
4279 return;
4280 }
4281 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4282 // If UID is restricted, don't allow them to bring up metered APNs.
4283 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004284 }
4285 }
4286
Robert Greenwalt9258c642014-03-26 16:47:06 -07004287 @Override
4288 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4289 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004290 checkNotNull(operation, "PendingIntent cannot be null.");
4291 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4292 enforceNetworkRequestPermissions(networkCapabilities);
4293 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004294 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004295 ensureValidNetworkSpecifier(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004296 // TODO : don't forcefully set the UID when communicating with processes
4297 // that have the NETWORK_SETTINGS permission.
4298 networkCapabilities.setSingleUid(Binder.getCallingUid());
Etan Cohena7434272017-04-03 12:17:51 -07004299
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004300 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004301 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4302 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004303 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004304 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4305 nri));
4306 return networkRequest;
4307 }
4308
Jeremy Joslin79294842014-12-03 17:15:28 -08004309 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4310 mHandler.sendMessageDelayed(
4311 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4312 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4313 }
4314
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004315 @Override
4316 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004317 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004318 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4319 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004320 }
4321
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004322 // In order to implement the compatibility measure for pre-M apps that call
4323 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4324 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4325 // This ensures it has permission to do so.
4326 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4327 if (nc == null) {
4328 return false;
4329 }
4330 int[] transportTypes = nc.getTransportTypes();
4331 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4332 return false;
4333 }
4334 try {
4335 mContext.enforceCallingOrSelfPermission(
4336 android.Manifest.permission.ACCESS_WIFI_STATE,
4337 "ConnectivityService");
4338 } catch (SecurityException e) {
4339 return false;
4340 }
4341 return true;
4342 }
4343
Robert Greenwalt9258c642014-03-26 16:47:06 -07004344 @Override
4345 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4346 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004347 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4348 enforceAccessPermission();
4349 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004350
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004351 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004352 // TODO : don't forcefully set the UIDs when communicating with processes
4353 // that have the NETWORK_SETTINGS permission.
4354 nc.setSingleUid(Binder.getCallingUid());
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004355 if (!ConnectivityManager.checkChangePermission(mContext)) {
4356 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4357 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4358 // onLost and onAvailable callbacks when networks move in and out of the background.
4359 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4360 // can't request networks.
4361 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4362 }
Etan Cohen859748f2017-04-03 17:42:34 -07004363 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004364
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004365 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004366 NetworkRequest.Type.LISTEN);
4367 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004368 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004369
4370 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4371 return networkRequest;
4372 }
4373
4374 @Override
4375 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4376 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004377 checkNotNull(operation, "PendingIntent cannot be null.");
4378 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4379 enforceAccessPermission();
4380 }
Etan Cohen859748f2017-04-03 17:42:34 -07004381 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004382
Chalard Jeandda156a2018-01-10 21:19:32 +09004383 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4384 // TODO : don't forcefully set the UIDs when communicating with processes
4385 // that have the NETWORK_SETTINGS permission.
4386 nc.setSingleUid(Binder.getCallingUid());
4387
4388 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004389 NetworkRequest.Type.LISTEN);
4390 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004391 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004392
4393 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004394 }
4395
Erik Klineacdd6392016-07-07 16:50:58 +09004396 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004397 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004398 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004399 mHandler.sendMessage(mHandler.obtainMessage(
4400 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004401 }
4402
4403 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004404 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004405 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004406 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4407 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004408 }
4409
Robert Greenwalta67be032014-05-16 15:49:14 -07004410 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004411 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004412 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4413 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4414 }
4415
4416 @Override
4417 public void unregisterNetworkFactory(Messenger messenger) {
4418 enforceConnectivityInternalPermission();
4419 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4420 }
4421
4422 private void handleUnregisterNetworkFactory(Messenger messenger) {
4423 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4424 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004425 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004426 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004427 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004428 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004429 }
4430
Robert Greenwalt7b816022014-04-18 15:25:25 -07004431 /**
4432 * NetworkAgentInfo supporting a request by requestId.
4433 * These have already been vetted (their Capabilities satisfy the request)
4434 * and the are the highest scored network available.
4435 * the are keyed off the Requests requestId.
4436 */
Hugo Benichicd952782017-09-20 11:20:14 +09004437 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4438 @GuardedBy("mNetworkForRequestId")
Robert Greenwalt7b816022014-04-18 15:25:25 -07004439 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4440 new SparseArray<NetworkAgentInfo>();
4441
Paul Jensen31a94f42015-02-13 14:18:39 -05004442 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4443 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004444 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4445 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004446 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4447 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4448 // there may not be a strict 1:1 correlation between the two.
4449 @GuardedBy("mNetworkForNetId")
4450 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004451
Robert Greenwalt7b816022014-04-18 15:25:25 -07004452 // NetworkAgentInfo keyed off its connecting messenger
4453 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004454 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004455 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4456 new HashMap<Messenger, NetworkAgentInfo>();
4457
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004458 @GuardedBy("mBlockedAppUids")
4459 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4460
Paul Jensen2c311d62014-11-17 12:34:51 -05004461 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004462 private final NetworkRequest mDefaultRequest;
4463
Erik Klineda4bfa82015-04-30 12:58:40 +09004464 // Request used to optionally keep mobile data active even when higher
4465 // priority networks like Wi-Fi are active.
4466 private final NetworkRequest mDefaultMobileDataRequest;
4467
Hugo Benichicd952782017-09-20 11:20:14 +09004468 private NetworkAgentInfo getNetworkForRequest(int requestId) {
4469 synchronized (mNetworkForRequestId) {
4470 return mNetworkForRequestId.get(requestId);
4471 }
4472 }
4473
4474 private void clearNetworkForRequest(int requestId) {
4475 synchronized (mNetworkForRequestId) {
4476 mNetworkForRequestId.remove(requestId);
4477 }
4478 }
4479
4480 private void setNetworkForRequest(int requestId, NetworkAgentInfo nai) {
4481 synchronized (mNetworkForRequestId) {
4482 mNetworkForRequestId.put(requestId, nai);
4483 }
4484 }
4485
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004486 private NetworkAgentInfo getDefaultNetwork() {
Hugo Benichicd952782017-09-20 11:20:14 +09004487 return getNetworkForRequest(mDefaultRequest.requestId);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004488 }
4489
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004490 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004491 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004492 }
4493
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004494 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4495 return nri.request.requestId == mDefaultRequest.requestId;
4496 }
4497
Paul Jensen31a94f42015-02-13 14:18:39 -05004498 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004499 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004500 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004501 enforceConnectivityInternalPermission();
4502
Rubin Xu1bb5c082017-09-05 18:40:49 +01004503 LinkProperties lp = new LinkProperties(linkProperties);
4504 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004505 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4506 // satisfies mDefaultRequest.
Chalard Jean804b8fb2018-01-30 22:41:41 +09004507 final NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004508 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Chalard Jean804b8fb2018-01-30 22:41:41 +09004509 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp, nc, currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004510 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Chalard Jean804b8fb2018-01-30 22:41:41 +09004511 // Make sure the network capabilities reflect what the agent info says.
4512 nai.networkCapabilities = mixInCapabilities(nai, nc);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004513 synchronized (this) {
4514 nai.networkMonitor.systemReady = mSystemReady;
4515 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004516 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4517 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004518 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004519 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004520 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004521 }
4522
4523 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4524 if (VDBG) log("Got NetworkAgent Messenger");
4525 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004526 synchronized (mNetworkForNetId) {
4527 mNetworkForNetId.put(na.network.netId, na);
4528 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004529 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4530 NetworkInfo networkInfo = na.networkInfo;
4531 na.networkInfo = null;
4532 updateNetworkInfo(na, networkInfo);
Chalard Jeanf213ca12018-01-16 18:43:05 +09004533 updateUids(na, null, na.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004534 }
4535
4536 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4537 LinkProperties newLp = networkAgent.linkProperties;
4538 int netId = networkAgent.network.netId;
4539
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004540 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4541 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004542 if (networkAgent.clatd != null) {
4543 networkAgent.clatd.fixupLinkProperties(oldLp);
4544 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004545
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004546 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004547 updateMtu(newLp, oldLp);
4548 // TODO - figure out what to do for clat
4549// for (LinkProperties lp : newLp.getStackedLinks()) {
4550// updateMtu(lp, null);
4551// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004552 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004553
Erik Kline94887872016-04-05 13:30:49 +09004554 updateRoutes(newLp, oldLp, netId);
4555 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004556
Hugo Benichib577d652017-06-27 15:13:20 +09004557 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004558 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004559 if (isDefaultNetwork(networkAgent)) {
4560 handleApplyDefaultProxy(newLp.getHttpProxy());
4561 } else {
4562 updateProxy(newLp, oldLp, networkAgent);
4563 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004564 // TODO - move this check to cover the whole function
4565 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004566 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004567 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4568 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004569
4570 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004571 }
4572
Joel Scherpelz668370b2017-06-08 15:35:21 +09004573 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004574 // Marks are only available on WiFi interaces. Checking for
4575 // marks on unsupported interfaces is harmless.
4576 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4577 return;
4578 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004579
Joel Scherpelz668370b2017-06-08 15:35:21 +09004580 int mark = mContext.getResources().getInteger(
4581 com.android.internal.R.integer.config_networkWakeupPacketMark);
4582 int mask = mContext.getResources().getInteger(
4583 com.android.internal.R.integer.config_networkWakeupPacketMask);
4584
4585 // Mask/mark of zero will not detect anything interesting.
4586 // Don't install rules unless both values are nonzero.
4587 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004588 return;
4589 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004590
4591 final String prefix = "iface:" + iface;
4592 try {
4593 if (add) {
4594 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4595 } else {
4596 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4597 }
4598 } catch (Exception e) {
4599 loge("Exception modifying wakeup packet monitoring: " + e);
4600 }
4601
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004602 }
4603
4604 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4605 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004606 CompareResult<String> interfaceDiff = new CompareResult<String>(
4607 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4608 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004609 for (String iface : interfaceDiff.added) {
4610 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004611 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004612 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004613 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004614 } catch (Exception e) {
4615 loge("Exception adding interface: " + e);
4616 }
4617 }
4618 for (String iface : interfaceDiff.removed) {
4619 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004620 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004621 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004622 mNetd.removeInterfaceFromNetwork(iface, netId);
4623 } catch (Exception e) {
4624 loge("Exception removing interface: " + e);
4625 }
4626 }
4627 }
4628
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004629 /**
4630 * Have netd update routes from oldLp to newLp.
4631 * @return true if routes changed between oldLp and newLp
4632 */
4633 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004634 // Compare the route diff to determine which routes should be added and removed.
4635 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4636 oldLp != null ? oldLp.getAllRoutes() : null,
4637 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004638
4639 // add routes before removing old in case it helps with continuous connectivity
4640
4641 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4642 for (RouteInfo route : routeDiff.added) {
4643 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004644 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004645 try {
4646 mNetd.addRoute(netId, route);
4647 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004648 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4649 loge("Exception in addRoute for non-gateway: " + e);
4650 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004651 }
4652 }
4653 for (RouteInfo route : routeDiff.added) {
4654 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004655 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004656 try {
4657 mNetd.addRoute(netId, route);
4658 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004659 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4660 loge("Exception in addRoute for gateway: " + e);
4661 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004662 }
4663 }
4664
4665 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004666 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004667 try {
4668 mNetd.removeRoute(netId, route);
4669 } catch (Exception e) {
4670 loge("Exception in removeRoute: " + e);
4671 }
4672 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004673 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004674 }
Erik Kline41368502015-06-17 13:19:54 +09004675
Erik Kline94887872016-04-05 13:30:49 +09004676 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4677 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4678 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004679 }
Erik Kline94887872016-04-05 13:30:49 +09004680
Erik Kline1742fe12017-12-13 19:40:49 +09004681 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4682 final boolean isDefaultNetwork = (defaultNai != null && defaultNai.network.netId == netId);
4683
Erik Klinea24d4592018-01-11 21:07:29 +09004684 if (DBG) {
4685 final Collection<InetAddress> dnses = newLp.getDnsServers();
4686 log("Setting DNS servers for network " + netId + " to " + dnses);
4687 }
Erik Kline94887872016-04-05 13:30:49 +09004688 try {
Erik Klinea24d4592018-01-11 21:07:29 +09004689 mDnsManager.setDnsConfigurationForNetwork(netId, newLp, isDefaultNetwork);
Erik Kline94887872016-04-05 13:30:49 +09004690 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004691 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004692 }
Erik Kline4edba012017-04-07 15:29:29 +09004693 }
4694
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004695 private String getNetworkPermission(NetworkCapabilities nc) {
4696 // TODO: make these permission strings AIDL constants instead.
4697 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4698 return NetworkManagementService.PERMISSION_SYSTEM;
4699 }
4700 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4701 return NetworkManagementService.PERMISSION_NETWORK;
4702 }
4703 return null;
4704 }
4705
Paul Jensen3d194ea2015-06-16 14:27:36 -04004706 /**
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004707 * Augments the NetworkCapabilities passed in by a NetworkAgent with capabilities that are
4708 * maintained here that the NetworkAgent is not aware of (e.g., validated, captive portal,
4709 * and foreground status).
Paul Jensen3d194ea2015-06-16 14:27:36 -04004710 */
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004711 private NetworkCapabilities mixInCapabilities(NetworkAgentInfo nai, NetworkCapabilities nc) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004712 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004713 if (nai.everConnected &&
4714 !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(nc)) {
4715 // TODO: consider not complaining when a network agent degrades its capabilities if this
Hugo Benichibae105a2017-08-16 13:19:04 +09004716 // does not cause any request (that is not a listen) currently matching that agent to
4717 // stop being matched by the updated agent.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004718 String diff = nai.networkCapabilities.describeImmutableDifferences(nc);
Hugo Benichieae7a222017-07-25 11:40:56 +09004719 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004720 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004721 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004722 }
4723
Paul Jensen3d194ea2015-06-16 14:27:36 -04004724 // Don't modify caller's NetworkCapabilities.
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004725 NetworkCapabilities newNc = new NetworkCapabilities(nc);
Paul Jensene0988542015-06-25 15:30:08 -04004726 if (nai.lastValidated) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004727 newNc.addCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004728 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004729 newNc.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004730 }
Paul Jensene0988542015-06-25 15:30:08 -04004731 if (nai.lastCaptivePortalDetected) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004732 newNc.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004733 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004734 newNc.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
Paul Jensen3d194ea2015-06-16 14:27:36 -04004735 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004736 if (nai.isBackgroundNetwork()) {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004737 newNc.removeCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004738 } else {
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004739 newNc.addCapability(NET_CAPABILITY_FOREGROUND);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004740 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09004741 if (nai.isSuspended()) {
4742 newNc.removeCapability(NET_CAPABILITY_NOT_SUSPENDED);
4743 } else {
4744 newNc.addCapability(NET_CAPABILITY_NOT_SUSPENDED);
4745 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004746
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004747 return newNc;
4748 }
4749
4750 /**
4751 * Update the NetworkCapabilities for {@code nai} to {@code nc}. Specifically:
4752 *
4753 * 1. Calls mixInCapabilities to merge the passed-in NetworkCapabilities {@code nc} with the
4754 * capabilities we manage and store in {@code nai}, such as validated status and captive
4755 * portal status)
4756 * 2. Takes action on the result: changes network permissions, sends CAP_CHANGED callbacks, and
4757 * potentially triggers rematches.
4758 * 3. Directly informs other network stack components (NetworkStatsService, VPNs, etc. of the
4759 * change.)
4760 *
4761 * @param oldScore score of the network before any of the changes that prompted us
4762 * to call this function.
4763 * @param nai the network having its capabilities updated.
4764 * @param nc the new network capabilities.
4765 */
4766 private void updateCapabilities(int oldScore, NetworkAgentInfo nai, NetworkCapabilities nc) {
4767 NetworkCapabilities newNc = mixInCapabilities(nai, nc);
4768
4769 if (Objects.equals(nai.networkCapabilities, newNc)) return;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004770
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004771 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004772 final String newPermission = getNetworkPermission(newNc);
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004773 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004774 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004775 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004776 } catch (RemoteException e) {
4777 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004778 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004779 }
4780
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004781 final NetworkCapabilities prevNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004782 synchronized (nai) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004783 prevNc = nai.networkCapabilities;
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004784 nai.networkCapabilities = newNc;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004785 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004786
Chalard Jeanf213ca12018-01-16 18:43:05 +09004787 updateUids(nai, prevNc, newNc);
4788
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004789 if (nai.getCurrentScore() == oldScore && newNc.equalRequestableCapabilities(prevNc)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004790 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4791 // the change we're processing can't affect any requests, it can only affect the listens
4792 // on this network. We might have been called by rematchNetworkAndRequests when a
4793 // network changed foreground state.
4794 processListenRequests(nai, true);
4795 } else {
4796 // If the requestable capabilities have changed or the score changed, we can't have been
4797 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004798 rematchAllNetworksAndRequests(nai, oldScore);
4799 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004800 }
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004801
4802 // Report changes that are interesting for network statistics tracking.
4803 if (prevNc != null) {
4804 final boolean meteredChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_METERED) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004805 newNc.hasCapability(NET_CAPABILITY_NOT_METERED);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004806 final boolean roamingChanged = prevNc.hasCapability(NET_CAPABILITY_NOT_ROAMING) !=
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004807 newNc.hasCapability(NET_CAPABILITY_NOT_ROAMING);
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004808 if (meteredChanged || roamingChanged) {
4809 notifyIfacesChangedForNetworkStats();
4810 }
4811 }
4812
Lorenzo Colittiaa7f7e42018-01-16 00:52:07 +09004813 if (!newNc.hasTransport(TRANSPORT_VPN)) {
Jeff Sharkey72f9c422017-10-27 17:22:59 -06004814 // Tell VPNs about updated capabilities, since they may need to
4815 // bubble those changes through.
4816 synchronized (mVpns) {
4817 for (int i = 0; i < mVpns.size(); i++) {
4818 final Vpn vpn = mVpns.valueAt(i);
4819 vpn.updateCapabilities();
4820 }
4821 }
4822 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004823 }
4824
Chalard Jeanf213ca12018-01-16 18:43:05 +09004825 private void updateUids(NetworkAgentInfo nai, NetworkCapabilities prevNc,
4826 NetworkCapabilities newNc) {
4827 Set<UidRange> prevRanges = null == prevNc ? null : prevNc.getUids();
4828 Set<UidRange> newRanges = null == newNc ? null : newNc.getUids();
4829 if (null == prevRanges) prevRanges = new ArraySet<>();
4830 if (null == newRanges) newRanges = new ArraySet<>();
4831 final Set<UidRange> prevRangesCopy = new ArraySet<>(prevRanges);
4832
4833 prevRanges.removeAll(newRanges);
4834 newRanges.removeAll(prevRangesCopy);
4835
4836 try {
4837 if (!newRanges.isEmpty()) {
4838 final UidRange[] addedRangesArray = new UidRange[newRanges.size()];
4839 newRanges.toArray(addedRangesArray);
4840 mNetd.addVpnUidRanges(nai.network.netId, addedRangesArray);
4841 }
4842 if (!prevRanges.isEmpty()) {
4843 final UidRange[] removedRangesArray = new UidRange[prevRanges.size()];
4844 prevRanges.toArray(removedRangesArray);
4845 mNetd.removeVpnUidRanges(nai.network.netId, removedRangesArray);
4846 }
4847 } catch (Exception e) {
4848 // Never crash!
4849 loge("Exception in updateUids: " + e);
4850 }
4851 }
4852
Hugo Benichief502882017-09-01 01:23:32 +00004853 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4854 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4855 // Ignore updates for disconnected networks
4856 return;
4857 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004858 // newLp is already a defensive copy.
4859 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004860 if (VDBG) {
4861 log("Update of LinkProperties for " + nai.name() +
4862 "; created=" + nai.created +
4863 "; everConnected=" + nai.everConnected);
4864 }
4865 LinkProperties oldLp = nai.linkProperties;
4866 synchronized (nai) {
4867 nai.linkProperties = newLp;
4868 }
4869 if (nai.everConnected) {
4870 updateLinkProperties(nai, oldLp);
4871 }
4872 }
4873
Paul Jensenc8b9a742014-09-30 15:37:41 -04004874 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004875 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4876 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004877 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004878 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004879 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4880 }
4881 }
4882
Robert Greenwalt7b816022014-04-18 15:25:25 -07004883 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4884 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004885 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004886 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4887 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004888 }
4889 }
4890
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004891 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4892 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004893 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004894 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004895 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4896 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004897 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004898 sendIntent(nri.mPendingIntent, intent);
4899 }
4900 // else not handled
4901 }
4902
4903 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4904 mPendingIntentWakeLock.acquire();
4905 try {
4906 if (DBG) log("Sending " + pendingIntent);
4907 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4908 } catch (PendingIntent.CanceledException e) {
4909 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4910 mPendingIntentWakeLock.release();
4911 releasePendingNetworkRequest(pendingIntent);
4912 }
4913 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4914 }
4915
4916 @Override
4917 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4918 String resultData, Bundle resultExtras) {
4919 if (DBG) log("Finished sending " + pendingIntent);
4920 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004921 // Release with a delay so the receiving client has an opportunity to put in its
4922 // own request.
4923 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004924 }
4925
Chalard Jeanf19db372018-01-26 19:24:40 +09004926 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004927 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004928 if (nri.messenger == null) {
4929 return; // Default request has no msgr
4930 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004931 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004932 // TODO: check if defensive copies of data is needed.
4933 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004934 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004935 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4936 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004937 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004938 switch (notificationType) {
Chalard Jean804b8fb2018-01-30 22:41:41 +09004939 case ConnectivityManager.CALLBACK_AVAILABLE: {
4940 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
4941 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
4942 break;
4943 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004944 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004945 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004946 break;
4947 }
4948 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Chalard Jeanf19db372018-01-26 19:24:40 +09004949 // networkAgent can't be null as it has been accessed a few lines above.
Chalard Jeandda156a2018-01-10 21:19:32 +09004950 final NetworkCapabilities nc =
Chalard Jeanf19db372018-01-26 19:24:40 +09004951 networkCapabilitiesWithoutUids(networkAgent.networkCapabilities);
Chalard Jeandda156a2018-01-10 21:19:32 +09004952 putParcelable(bundle, nc);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004953 break;
4954 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004955 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004956 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004957 break;
4958 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004959 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004960 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004961 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004962 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004963 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004964 String notification = ConnectivityManager.getCallbackName(notificationType);
4965 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004966 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004967 nri.messenger.send(msg);
4968 } catch (RemoteException e) {
4969 // may occur naturally in the race of binder death.
4970 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4971 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004972 }
4973
Hugo Benichidba33db2017-03-23 22:40:44 +09004974 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4975 bundle.putParcelable(t.getClass().getSimpleName(), t);
4976 }
4977
Paul Jensenc8b9a742014-09-30 15:37:41 -04004978 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004979 if (nai.numRequestNetworkRequests() != 0) {
4980 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4981 NetworkRequest nr = nai.requestAt(i);
4982 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004983 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004984 loge("Dead network still had at least " + nr);
4985 break;
4986 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004987 }
4988 nai.asyncChannel.disconnect();
4989 }
4990
Robert Greenwalt7b816022014-04-18 15:25:25 -07004991 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4992 if (oldNetwork == null) {
4993 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4994 return;
4995 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004996 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004997
4998 // If we get here it means that the last linger timeout for this network expired. So there
4999 // must be no other active linger timers, and we must stop lingering.
5000 oldNetwork.clearLingerState();
5001
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005002 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005003 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005004 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005005 } else {
5006 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005007 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
5008 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005009 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005010 }
5011
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005012 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005013 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005014 setupDataActivityTracking(newNetwork);
5015 try {
5016 mNetd.setDefaultNetId(newNetwork.network.netId);
5017 } catch (Exception e) {
5018 loge("Exception setting default network :" + e);
5019 }
Lorenzo Colittic78da292018-01-19 00:50:48 +09005020
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005021 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04005022 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07005023 updateTcpBufferSizes(newNetwork);
Erik Kline1742fe12017-12-13 19:40:49 +09005024 mDnsManager.setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Lorenzo Colittic78da292018-01-19 00:50:48 +09005025 notifyIfacesChangedForNetworkStats();
Paul Jensen27b02b72014-07-14 12:03:33 -04005026 }
5027
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005028 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005029 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
5030 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5031 NetworkRequest nr = nri.request;
5032 if (!nr.isListen()) continue;
5033 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
5034 nai.removeRequest(nri.request.requestId);
5035 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
5036 }
5037 }
5038
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005039 if (capabilitiesChanged) {
5040 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
5041 }
5042
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005043 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
5044 NetworkRequest nr = nri.request;
5045 if (!nr.isListen()) continue;
5046 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
5047 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005048 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005049 }
5050 }
5051 }
5052
Paul Jensen2161a8e2014-09-11 11:00:39 -04005053 // Handles a network appearing or improving its score.
5054 //
5055 // - Evaluates all current NetworkRequests that can be
5056 // satisfied by newNetwork, and reassigns to newNetwork
5057 // any such requests for which newNetwork is the best.
5058 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005059 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04005060 // needed. A network is needed if it is the best network for
5061 // one or more NetworkRequests, or if it is a VPN.
5062 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005063 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04005064 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005065 //
5066 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
5067 // networks that have no chance (i.e. even if validated)
5068 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005069 //
5070 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
5071 // it does not remove NetworkRequests that other Networks could better satisfy.
5072 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
5073 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
5074 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04005075 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05005076 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05005077 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
5078 // performed to tear down unvalidated networks that have no chance (i.e. even if
5079 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005080 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005081 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01005082 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005083 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07005084 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005085 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005086
5087 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
5088 final int score = newNetwork.getCurrentScore();
5089
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07005090 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005091
Paul Jensen2161a8e2014-09-11 11:00:39 -04005092 // Find and migrate to this Network any NetworkRequests for
5093 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07005094 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04005095 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005096 NetworkCapabilities nc = newNetwork.networkCapabilities;
5097 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005098 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005099 // Process requests in the first pass and listens in the second pass. This allows us to
5100 // change a network's capabilities depending on which requests it has. This is only
5101 // correct if the change in capabilities doesn't affect whether the network satisfies
5102 // requests or not, and doesn't affect the network's score.
5103 if (nri.request.isListen()) continue;
5104
Hugo Benichicd952782017-09-20 11:20:14 +09005105 final NetworkAgentInfo currentNetwork = getNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005106 final boolean satisfies = newNetwork.satisfies(nri.request);
5107 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005108 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07005109 log("Network " + newNetwork.name() + " was already satisfying" +
5110 " request " + nri.request.requestId + ". No change.");
5111 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09005112 keep = true;
5113 continue;
5114 }
5115
5116 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07005117 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005118 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005119 // next check if it's better than any current network we're using for
5120 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07005121 if (VDBG) {
5122 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04005123 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005124 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005125 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005126 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005127 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07005128 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005129 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005130 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005131 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005132 affectedNetworks.add(currentNetwork);
5133 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005134 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07005135 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005136 newNetwork.unlingerRequest(nri.request);
Hugo Benichicd952782017-09-20 11:20:14 +09005137 setNetworkForRequest(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04005138 if (!newNetwork.addRequest(nri.request)) {
5139 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
5140 }
5141 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005142 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04005143 // Tell NetworkFactories about the new score, so they can stop
5144 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005145 // TODO - this could get expensive if we have alot of requests for this
5146 // network. Think about if there is a way to reduce this. Push
5147 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005148 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09005149 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005150 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05005151 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09005152 if (currentNetwork != null) {
5153 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
5154 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005155 }
5156 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005157 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04005158 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
5159 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005160 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04005161 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
5162 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
5163 // This means this code doesn't have to handle the case where "currentNetwork" no
5164 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
5165 if (DBG) {
5166 log("Network " + newNetwork.name() + " stopped satisfying" +
5167 " request " + nri.request.requestId);
5168 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005169 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005170 if (currentNetwork == newNetwork) {
Hugo Benichicd952782017-09-20 11:20:14 +09005171 clearNetworkForRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005172 sendUpdatedScoreToFactories(nri.request, 0);
5173 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005174 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
5175 newNetwork.name() +
5176 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04005177 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005178 // TODO: Technically, sending CALLBACK_LOST here is
5179 // incorrect if there is a replacement network currently
5180 // connected that can satisfy nri, which is a request
5181 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04005182 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
5183 // so this code is only incorrect for a network that loses
5184 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005185 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005186 }
5187 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005188 if (isNewDefault) {
5189 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09005190 makeDefault(newNetwork);
5191 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
Hugo Benichi64901e52017-10-19 14:42:40 +09005192 metricsLogger().defaultNetworkMetrics().logDefaultNetworkEvent(
Hugo Benichi380a0632017-10-20 09:25:29 +09005193 now, newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09005194 // Have a new default network, release the transition wakelock in
5195 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04005196 }
5197
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005198 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
5199 Slog.wtf(TAG, String.format(
5200 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07005201 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005202 }
5203 if (newNetwork.getCurrentScore() != score) {
5204 Slog.wtf(TAG, String.format(
5205 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08005206 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005207 }
5208
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005209 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005210 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5211 // If the network went from background to foreground or vice versa, we need to update
5212 // its foreground state. It is safe to do this after rematching the requests because
5213 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5214 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005215 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005216 } else {
5217 processListenRequests(newNetwork, false);
5218 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005219
Paul Jensencf4c2c62015-07-01 14:16:32 -04005220 // do this after the default net is switched, but
5221 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005222 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005223
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005224 // Linger any networks that are no longer needed. This should be done after sending the
5225 // available callback for newNetwork.
5226 for (NetworkAgentInfo nai : affectedNetworks) {
5227 updateLingerState(nai, now);
5228 }
5229 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5230 // does not need to be done in any particular order.
5231 updateLingerState(newNetwork, now);
5232
Paul Jensencf4c2c62015-07-01 14:16:32 -04005233 if (isNewDefault) {
5234 // Maintain the illusion: since the legacy API only
5235 // understands one network at a time, we must pretend
5236 // that the current default network disconnected before
5237 // the new one connected.
5238 if (oldDefaultNetwork != null) {
5239 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5240 oldDefaultNetwork, true);
5241 }
5242 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5243 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5244 notifyLockdownVpn(newNetwork);
5245 }
5246
Robert Greenwalt7b816022014-04-18 15:25:25 -07005247 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005248 // Notify battery stats service about this network, both the normal
5249 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005250 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005251 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005252 final IBatteryStats bs = BatteryStatsService.getService();
5253 final int type = newNetwork.networkInfo.getType();
5254
5255 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5256 bs.noteNetworkInterfaceType(baseIface, type);
5257 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5258 final String stackedIface = stacked.getInterfaceName();
5259 bs.noteNetworkInterfaceType(stackedIface, type);
5260 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5261 }
5262 } catch (RemoteException ignored) {
5263 }
5264
Robert Greenwalt152ed372014-12-17 17:19:53 -08005265 // This has to happen after the notifyNetworkCallbacks as that tickles each
5266 // ConnectivityManager instance so that legacy requests correctly bind dns
5267 // requests to this network. The legacy users are listening for this bcast
5268 // and will generally do a dns request so they can ensureRouteToHost and if
5269 // they do that before the callbacks happen they'll use the default network.
5270 //
5271 // TODO: Is there still a race here? We send the broadcast
5272 // after sending the callback, but if the app can receive the
5273 // broadcast before the callback, it might still break.
5274 //
5275 // This *does* introduce a race where if the user uses the new api
5276 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5277 // they may get old info. Reverse this after the old startUsing api is removed.
5278 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005279 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5280 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005281 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005282 // legacy type tracker filters out repeat adds
5283 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5284 }
5285 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005286
5287 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5288 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5289 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5290 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5291 if (newNetwork.isVPN()) {
5292 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5293 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005294 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005295 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5296 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005297 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005298 if (nai.getLingerExpiry() > 0) {
5299 // This network has active linger timers and no requests, but is not
5300 // lingering. Linger it.
5301 //
5302 // One way (the only way?) this can happen if this network is unvalidated
5303 // and became unneeded due to another network improving its score to the
5304 // point where this network will no longer be able to satisfy any requests
5305 // even if it validates.
5306 updateLingerState(nai, now);
5307 } else {
5308 if (DBG) log("Reaping " + nai.name());
5309 teardownUnneededNetwork(nai);
5310 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005311 }
5312 }
5313 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005314 }
5315
Paul Jensen1c7ba022015-06-16 14:27:36 -04005316 /**
5317 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5318 * being disconnected.
5319 * @param changed If only one Network's score or capabilities have been modified since the last
5320 * time this function was called, pass this Network in this argument, otherwise pass
5321 * null.
5322 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5323 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5324 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5325 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5326 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005327 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005328 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005329 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5330 // to avoid the slowness. It is not simply enough to process just "changed", for
5331 // example in the case where "changed"'s score decreases and another network should begin
5332 // satifying a NetworkRequest that "changed" currently satisfies.
5333
5334 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5335 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5336 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005337 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005338 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005339 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005340 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005341 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5342 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5343 // Rematch higher scoring networks first to prevent requests first matching a lower
5344 // scoring network and then a higher scoring network, which could produce multiple
5345 // callbacks and inadvertently unlinger networks.
5346 Arrays.sort(nais);
5347 for (NetworkAgentInfo nai : nais) {
5348 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005349 // Only reap the last time through the loop. Reaping before all rematching
5350 // is complete could incorrectly teardown a network that hasn't yet been
5351 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005352 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005353 : ReapUnvalidatedNetworks.REAP,
5354 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005355 }
5356 }
5357 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005358
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005359 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005360 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005361 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005362 // For now only update icons for default connection.
5363 // TODO: Update WiFi and cellular icons separately. b/17237507
5364 if (!isDefaultNetwork(nai)) return;
5365
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005366 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005367 // Don't repeat publish.
5368 if (newInetCondition == mDefaultInetConditionPublished) return;
5369
5370 mDefaultInetConditionPublished = newInetCondition;
5371 sendInetConditionBroadcast(nai.networkInfo);
5372 }
5373
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005374 private void notifyLockdownVpn(NetworkAgentInfo nai) {
Hugo Benichi69744342017-11-27 10:57:16 +09005375 synchronized (mVpns) {
5376 if (mLockdownTracker != null) {
5377 if (nai != null && nai.isVPN()) {
5378 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5379 } else {
5380 mLockdownTracker.onNetworkInfoChanged();
5381 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005382 }
5383 }
5384 }
5385
Robert Greenwalt7b816022014-04-18 15:25:25 -07005386 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005387 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005388 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005389 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005390 synchronized (networkAgent) {
5391 oldInfo = networkAgent.networkInfo;
5392 networkAgent.networkInfo = newInfo;
5393 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005394 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005395
Robert Greenwalt7b816022014-04-18 15:25:25 -07005396 if (DBG) {
5397 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5398 (oldInfo == null ? "null" : oldInfo.getState()) +
5399 " to " + state);
5400 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005401
Robin Lee585e2482016-05-01 23:00:00 +01005402 if (!networkAgent.created
5403 && (state == NetworkInfo.State.CONNECTED
5404 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005405
5406 // A network that has just connected has zero requests and is thus a foreground network.
5407 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5408
Robert Greenwalt7b816022014-04-18 15:25:25 -07005409 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005410 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005411 if (networkAgent.isVPN()) {
5412 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005413 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5414 (networkAgent.networkMisc == null ||
5415 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005416 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005417 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005418 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005419 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005420 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005421 loge("Error creating network " + networkAgent.network.netId + ": "
5422 + e.getMessage());
5423 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005424 }
Paul Jenseneec75412014-08-04 12:21:19 -04005425 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005426 }
5427
5428 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5429 networkAgent.everConnected = true;
5430
Robert Greenwalt7b816022014-04-18 15:25:25 -07005431 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005432 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005433
Paul Jensenca8f16a2014-05-09 12:47:55 -04005434 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005435 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005436
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005437 if (networkAgent.isVPN()) {
5438 // Temporarily disable the default proxy (not global).
5439 synchronized (mProxyLock) {
5440 if (!mDefaultProxyDisabled) {
5441 mDefaultProxyDisabled = true;
5442 if (mGlobalProxy == null && mDefaultProxy != null) {
5443 sendProxyBroadcast(null);
5444 }
5445 }
5446 }
5447 // TODO: support proxy per network.
5448 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005449
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005450 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5451 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5452 // capabilities, so it only needs to be done once on initial connect, not every time the
5453 // network's capabilities change. Note that we do this before rematching the network,
5454 // so we could decide to tear it down immediately afterwards. That's fine though - on
5455 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5456 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005457 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005458
Paul Jensen2161a8e2014-09-11 11:00:39 -04005459 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005460 final long now = SystemClock.elapsedRealtime();
5461 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005462
5463 // This has to happen after matching the requests, because callbacks are just requests.
5464 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005465 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005466 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005467 if (networkAgent.isVPN()) {
5468 synchronized (mProxyLock) {
5469 if (mDefaultProxyDisabled) {
5470 mDefaultProxyDisabled = false;
5471 if (mGlobalProxy == null && mDefaultProxy != null) {
5472 sendProxyBroadcast(mDefaultProxy);
5473 }
5474 }
5475 }
Chalard Jeanf213ca12018-01-16 18:43:05 +09005476 updateUids(networkAgent, networkAgent.networkCapabilities, null);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005477 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005478 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5479 state == NetworkInfo.State.SUSPENDED) {
5480 // going into or coming out of SUSPEND: rescore and notify
5481 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005482 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005483 }
Chalard Jean804b8fb2018-01-30 22:41:41 +09005484 updateCapabilities(networkAgent.getCurrentScore(), networkAgent,
5485 networkAgent.networkCapabilities);
5486 // TODO (b/73132094) : remove this call once the few users of onSuspended and
5487 // onResumed have been removed.
Robert Greenwalt8d482522015-06-24 13:23:42 -07005488 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5489 ConnectivityManager.CALLBACK_SUSPENDED :
5490 ConnectivityManager.CALLBACK_RESUMED));
5491 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005492 }
5493 }
5494
Robert Greenwaltac96c522014-06-03 16:43:57 -07005495 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005496 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005497 if (score < 0) {
5498 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5499 "). Bumping score to min of 0");
5500 score = 0;
5501 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005502
Paul Jensen2161a8e2014-09-11 11:00:39 -04005503 final int oldScore = nai.getCurrentScore();
5504 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005505
Paul Jensen85cf78e2015-06-25 13:25:07 -04005506 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005507
Paul Jensenc8b9a742014-09-30 15:37:41 -04005508 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005509 }
5510
Erik Klinec75d4fa2017-02-15 19:59:17 +09005511 // Notify only this one new request of the current state. Transfer all the
5512 // current state by calling NetworkCapabilities and LinkProperties callbacks
5513 // so that callers can be guaranteed to have as close to atomicity in state
5514 // transfer as can be supported by this current API.
5515 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005516 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005517 if (nri.mPendingIntent != null) {
5518 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5519 // Attempt no subsequent state pushes where intents are involved.
5520 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005521 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005522
5523 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005524 }
5525
Robert Greenwalt8d482522015-06-24 13:23:42 -07005526 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005527 // The NetworkInfo we actually send out has no bearing on the real
5528 // state of affairs. For example, if the default connection is mobile,
5529 // and a request for HIPRI has just gone away, we need to pretend that
5530 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5531 // the state to DISCONNECTED, even though the network is of type MOBILE
5532 // and is still connected.
5533 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5534 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005535 if (state != DetailedState.DISCONNECTED) {
5536 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005537 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005538 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005539 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005540 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5541 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5542 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5543 if (info.isFailover()) {
5544 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5545 nai.networkInfo.setFailover(false);
5546 }
5547 if (info.getReason() != null) {
5548 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5549 }
5550 if (info.getExtraInfo() != null) {
5551 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5552 }
5553 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005554 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005555 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005556 if (newDefaultAgent != null) {
5557 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5558 newDefaultAgent.networkInfo);
5559 } else {
5560 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5561 }
5562 }
5563 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5564 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005565 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005566 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005567 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005568 }
5569 }
5570 }
5571
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005572 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005573 if (VDBG) {
5574 String notification = ConnectivityManager.getCallbackName(notifyType);
5575 log("notifyType " + notification + " for " + networkAgent.name());
5576 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005577 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5578 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005579 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5580 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005581 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5582 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005583 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005584 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005585 } else {
5586 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5587 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005588 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005589 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005590
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005591 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5592 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5593 }
5594
Jeff Sharkey69736342014-12-08 14:50:12 -08005595 /**
Lorenzo Colittic78da292018-01-19 00:50:48 +09005596 * Returns the list of all interfaces that could be used by network traffic that does not
5597 * explicitly specify a network. This includes the default network, but also all VPNs that are
5598 * currently connected.
5599 *
5600 * Must be called on the handler thread.
5601 */
5602 private Network[] getDefaultNetworks() {
5603 ArrayList<Network> defaultNetworks = new ArrayList<>();
5604 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
5605 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
5606 if (nai.everConnected && (nai == defaultNetwork || nai.isVPN())) {
5607 defaultNetworks.add(nai.network);
5608 }
5609 }
5610 return defaultNetworks.toArray(new Network[0]);
5611 }
5612
5613 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005614 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5615 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005616 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005617 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005618 try {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005619 mStatsService.forceUpdateIfaces(getDefaultNetworks());
Jeff Sharkey69736342014-12-08 14:50:12 -08005620 } catch (Exception ignored) {
5621 }
5622 }
5623
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005624 @Override
5625 public boolean addVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005626 int user = UserHandle.getUserId(Binder.getCallingUid());
5627 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005628 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005629 return mVpns.get(user).addAddress(address, prefixLength);
5630 }
5631 }
5632
5633 @Override
5634 public boolean removeVpnAddress(String address, int prefixLength) {
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005635 int user = UserHandle.getUserId(Binder.getCallingUid());
5636 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005637 throwIfLockdownEnabled();
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005638 return mVpns.get(user).removeAddress(address, prefixLength);
5639 }
5640 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005641
5642 @Override
5643 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005644 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi69744342017-11-27 10:57:16 +09005645 final boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005646 synchronized (mVpns) {
Hugo Benichi69744342017-11-27 10:57:16 +09005647 throwIfLockdownEnabled();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005648 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005649 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005650 if (success) {
Lorenzo Colittic78da292018-01-19 00:50:48 +09005651 mHandler.post(() -> notifyIfacesChangedForNetworkStats());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005652 }
5653 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005654 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005655
5656 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005657 public String getCaptivePortalServerUrl() {
Udam Sainic3b640c2017-06-07 12:06:28 -07005658 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005659 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005660 }
5661
5662 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005663 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5664 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5665 enforceKeepalivePermission();
5666 mKeepaliveTracker.startNattKeepalive(
5667 getNetworkAgentInfoForNetwork(network),
5668 intervalSeconds, messenger, binder,
5669 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5670 }
5671
5672 @Override
5673 public void stopKeepalive(Network network, int slot) {
5674 mHandler.sendMessage(mHandler.obtainMessage(
5675 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5676 }
5677
5678 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005679 public void factoryReset() {
5680 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005681
5682 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5683 return;
5684 }
5685
Robin Lee3b3dd942015-05-12 18:14:58 +01005686 final int userId = UserHandle.getCallingUserId();
5687
Stuart Scottf1fb3972015-04-02 18:00:02 -07005688 // Turn airplane mode off
5689 setAirplaneMode(false);
5690
Stuart Scotte3e314d2015-04-20 14:07:45 -07005691 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5692 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005693 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005694 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005695 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005696 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005697 }
5698
Stuart Scotte3e314d2015-04-20 14:07:45 -07005699 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005700 // Remove always-on package
5701 synchronized (mVpns) {
5702 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5703 if (alwaysOnPackage != null) {
5704 setAlwaysOnVpnPackage(userId, null, false);
5705 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5706 }
Victor Changb04a5ea2016-05-30 20:36:30 +01005707
Hugo Benichi69744342017-11-27 10:57:16 +09005708 // Turn Always-on VPN off
5709 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5710 final long ident = Binder.clearCallingIdentity();
5711 try {
5712 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5713 mLockdownEnabled = false;
5714 setLockdownTracker(null);
5715 } finally {
5716 Binder.restoreCallingIdentity(ident);
5717 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005718 }
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005719
Hugo Benichi69744342017-11-27 10:57:16 +09005720 // Turn VPN off
5721 VpnConfig vpnConfig = getVpnConfig(userId);
5722 if (vpnConfig != null) {
5723 if (vpnConfig.legacy) {
5724 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5725 } else {
5726 // Prevent this app (packagename = vpnConfig.user) from initiating
5727 // VPN connections in the future without user intervention.
5728 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005729
Hugo Benichi69744342017-11-27 10:57:16 +09005730 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
5731 }
Stuart Scotte3e314d2015-04-20 14:07:45 -07005732 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005733 }
5734 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005735
5736 Settings.Global.putString(mContext.getContentResolver(),
5737 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005738 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005739
5740 @VisibleForTesting
5741 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5742 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5743 return new NetworkMonitor(context, handler, nai, defaultRequest);
5744 }
Erik Kline48f12f22016-04-14 17:30:59 +09005745
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005746 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005747 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5748 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005749 }
5750
5751 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005752 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5753 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5754 }
5755
Lorenzo Colitti7bbe3ee2017-08-24 22:35:10 +09005756 @VisibleForTesting
5757 public boolean hasService(String name) {
5758 return ServiceManager.checkService(name) != null;
5759 }
5760
Hugo Benichi64901e52017-10-19 14:42:40 +09005761 @VisibleForTesting
5762 protected IpConnectivityMetrics.Logger metricsLogger() {
5763 return checkNotNull(LocalServices.getService(IpConnectivityMetrics.Logger.class),
5764 "no IpConnectivityMetrics service");
Hugo Benichicfddd682016-05-31 16:28:06 +09005765 }
5766
5767 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
Hugo Benichiedf5c242017-11-11 08:06:43 +09005768 int[] transports = nai.networkCapabilities.getTransportTypes();
5769 mMetricsLog.log(nai.network.netId, transports, new NetworkEvent(evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005770 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005771
5772 private static boolean toBool(int encodedBoolean) {
5773 return encodedBoolean != 0; // Only 0 means false.
5774 }
5775
5776 private static int encodeBool(boolean b) {
5777 return b ? 1 : 0;
5778 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005779}