blob: 14b505c6fb28d48c7157479f151a212e61eafd6c [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;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060032
Wenchao Tongf5ea3402015-03-04 13:26:38 -080033import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080034import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090035import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070036import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070037import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.ContentResolver;
39import android.content.Context;
40import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070041import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070043import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090044import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070045import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090047import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070049import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070050import android.net.INetworkPolicyListener;
51import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070052import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080053import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070054import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070055import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070056import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070057import android.net.NetworkCapabilities;
Etan Cohena7434272017-04-03 12:17:51 -070058import android.net.MatchAllNetworkSpecifier;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070062import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070063import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070065import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070066import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070067import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040068import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070069import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040071import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090072import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090073import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090074import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090075import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080076import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080077import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070078import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040079import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080080import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070081import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070082import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070083import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080084import android.os.Looper;
85import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070086import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070087import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070088import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070089import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080091import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090092import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070093import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040094import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070096import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070097import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070098import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070099import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700100import android.util.LocalLog;
101import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600102import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700103import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800104import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700105import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500106import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700107import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700108import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Wink Savilleab9321d2013-06-29 21:10:57 -0700110import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400111import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400112import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700113import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700114import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700115import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700116import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800117import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700118import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700119import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600120import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700121import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900122import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900123import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700124import com.android.internal.util.XmlUtils;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900125import com.android.server.LocalServices;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700126import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400127import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900128import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700129import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900130import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900131import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700132import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600133import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400134import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900135import com.android.server.connectivity.NetworkNotificationManager;
136import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400137import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700138import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800139import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700140import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700141import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700142import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900143import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600144
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700145import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700146
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700147import org.xmlpull.v1.XmlPullParser;
148import org.xmlpull.v1.XmlPullParserException;
149
150import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700152import java.io.FileNotFoundException;
153import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700154import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700156import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700157import java.net.InetAddress;
158import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700159import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700160import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700161import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700162import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700163import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700165import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700166import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700167import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600168import java.util.SortedSet;
169import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
171/**
172 * @hide
173 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800174public class ConnectivityService extends IConnectivityManager.Stub
175 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900176 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900178 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700179 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Jake Hamby786e71a2014-02-06 14:43:50 -0800181 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900182 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700183
Jeff Sharkey899223b2012-08-04 15:24:58 -0700184 // TODO: create better separation between radio types and network types
185
Robert Greenwalt42acef32009-08-12 16:08:25 -0700186 // how long to wait before switching back to a radio's default network
187 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
188 // system property that can override the above value
189 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
190 "android.telephony.apn-restore";
191
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900192 // How long to wait before putting up a "This network doesn't have an Internet connection,
193 // connect anyway?" dialog after the user selects a network that doesn't validate.
194 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
195
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900196 // Default to 30s linger time-out. Modifiable only for testing.
197 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
198 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
199 @VisibleForTesting
200 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
201
Jeremy Joslin79294842014-12-03 17:15:28 -0800202 // How long to delay to removal of a pending intent based request.
203 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
204 private final int mReleasePendingIntentDelayMs;
205
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900206 private MockableSystemProperties mSystemProperties;
207
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800208 private Tethering mTethering;
209
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700210 private final PermissionMonitor mPermissionMonitor;
211
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700212 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700213
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700214 @GuardedBy("mVpns")
215 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700216
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700217 private boolean mLockdownEnabled;
218 private LockdownVpnTracker mLockdownTracker;
219
Erik Klineda4bfa82015-04-30 12:58:40 +0900220 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700222 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700223 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800225 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
227 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700228 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800229
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700230 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800231 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700232 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900233 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700234
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700235 private String mCurrentTcpBufferSizes;
236
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237 private static final int ENABLED = 1;
238 private static final int DISABLED = 0;
239
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900240 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900241 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
242 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900243
Paul Jensenb10e37f2014-11-25 12:33:08 -0500244 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400245 // Tear down networks that have no chance (e.g. even if validated) of becoming
246 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500247 // all networks have been rematched against all NetworkRequests.
248 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400249 // Don't reap networks. This should be passed when some networks have not yet been
250 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500251 DONT_REAP
252 };
253
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900254 private enum UnneededFor {
255 LINGER, // Determine whether this network is unneeded and should be lingered.
256 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
257 }
258
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700259 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700260 * used internally to change our mobile data enabled flag
261 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700262 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700263
264 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700265 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700266 * from one net to another. Clear happens when we get a new
267 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
268 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700269 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700270 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700271
Robert Greenwalt434203a2010-10-11 16:00:27 -0700272 /**
273 * used internally to reload global proxy settings
274 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700275 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700276
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700277 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400278 * PAC manager has received new port.
279 */
280 private static final int EVENT_PROXY_HAS_CHANGED = 16;
281
Robert Greenwalte049c232014-04-11 15:53:27 -0700282 /**
283 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700284 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700285 */
286 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
287
Robert Greenwalt7b816022014-04-18 15:25:25 -0700288 /**
289 * used internally when registering NetworkAgents
290 * obj = Messenger
291 */
292 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
293
Robert Greenwalt9258c642014-03-26 16:47:06 -0700294 /**
295 * used to add a network request
296 * includes a NetworkRequestInfo
297 */
298 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
299
300 /**
301 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900302 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700303 * cancel it.
304 * includes a NetworkRequestInfo
305 */
306 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
307
308 /**
309 * used to add a network listener - no request
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
313
314 /**
315 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400316 * arg1 = UID of caller
317 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700318 */
319 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
320
Robert Greenwalta67be032014-05-16 15:49:14 -0700321 /**
322 * used internally when registering NetworkFactories
323 * obj = Messenger
324 */
325 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
326
Robert Greenwalt27711812014-06-25 16:45:57 -0700327 /**
328 * used internally to expire a wakelock when transitioning
329 * from one net to another. Expire happens when we fail to find
330 * a new network (typically after 1 minute) -
331 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
332 * a replacement network.
333 */
334 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
335
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700336 /**
337 * Used internally to indicate the system is ready.
338 */
339 private static final int EVENT_SYSTEM_READY = 25;
340
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800341 /**
342 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400343 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800344 */
345 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
346
347 /**
348 * used to remove a pending intent and its associated network request.
349 * arg1 = UID of caller
350 * obj = PendingIntent
351 */
352 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
353
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900354 /**
355 * used to specify whether a network should be used even if unvalidated.
356 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
357 * arg2 = whether to remember this choice in the future (1 or 0)
358 * obj = network
359 */
360 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
361
362 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900363 * used to specify whether a network should not be penalized when it becomes unvalidated.
364 */
365 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
366
367 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900368 * used to ask the user to confirm a connection to an unvalidated network.
369 * obj = network
370 */
371 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700372
Erik Klineda4bfa82015-04-30 12:58:40 +0900373 /**
374 * used internally to (re)configure mobile data always-on settings.
375 */
376 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
377
Paul Jensen694f2b82015-06-17 14:15:39 -0400378 /**
379 * used to add a network listener with a pending intent
380 * obj = NetworkRequestInfo
381 */
382 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
383
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900384 private static String eventName(int what) {
385 return sMagicDecoderRing.get(what, Integer.toString(what));
386 }
387
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900388 /** Handler thread used for both of the handlers below. */
389 @VisibleForTesting
390 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700391 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700392 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700393 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700394 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700395
Mike Lockwood0f79b542009-08-14 14:18:49 -0400396 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800397 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400398
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700399 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700400 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800401 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700402
Robert Greenwalt434203a2010-10-11 16:00:27 -0700403 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400404 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700405 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700406 private boolean mDefaultProxyDisabled = false;
407
Robert Greenwalt434203a2010-10-11 16:00:27 -0700408 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400409 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700410
Jason Monk602b2322013-07-03 17:04:33 -0400411 private PacManager mPacManager = null;
412
Erik Klineda4bfa82015-04-30 12:58:40 +0900413 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700414
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400415 private UserManager mUserManager;
416
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700417 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700418 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700419
Robert Greenwalt50393202011-06-21 17:26:14 -0700420 // the set of network types that can only be enabled by system/sig apps
421 List mProtectedNetworks;
422
John Spurlockbf991a82013-06-24 14:20:23 -0400423 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700424
Wink Savilleab9321d2013-06-29 21:10:57 -0700425 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400426
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900427 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900428 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900429 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900430
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700431 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
432 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700433 private final static int MAX_NET_ID = 65535;
434 private int mNextNetId = MIN_NET_ID;
435
Robert Greenwalt34524f02014-05-18 16:22:10 -0700436 // sequence number of NetworkRequests
437 private int mNextNetworkRequestId = 1;
438
Erik Kline7523eb32015-07-09 18:24:03 +0900439 // NetworkRequest activity String log entries.
440 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
441 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
442
Hugo Benichic2ae2872016-07-11 11:05:12 +0900443 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900444 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900445 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
446
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900447 private static final int MAX_WAKELOCK_LOGS = 20;
448 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
449
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700450 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
451 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400452 private static class ValidationLog {
453 final Network mNetwork;
454 final String mNetworkExtraInfo;
455 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700456
Paul Jensen0808eb82016-06-03 13:51:21 -0400457 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
458 mNetwork = network;
459 mNetworkExtraInfo = networkExtraInfo;
460 mLog = log;
461 }
462 }
463 private final ArrayDeque<ValidationLog> mValidationLogs =
464 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
465
466 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700467 synchronized(mValidationLogs) {
468 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
469 mValidationLogs.removeLast();
470 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400471 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700472 }
473 }
474
Hugo Benichif9fdf872016-07-28 17:53:06 +0900475 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900476
Erik Kline065ab6e2016-10-02 18:02:14 +0900477 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900478 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900479
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700480 /**
481 * Implements support for the legacy "one network per network type" model.
482 *
483 * We used to have a static array of NetworkStateTrackers, one for each
484 * network type, but that doesn't work any more now that we can have,
485 * for example, more that one wifi network. This class stores all the
486 * NetworkAgentInfo objects that support a given type, but the legacy
487 * API will only see the first one.
488 *
489 * It serves two main purposes:
490 *
491 * 1. Provide information about "the network for a given type" (since this
492 * API only supports one).
493 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
494 * the first network for a given type changes, or if the default network
495 * changes.
496 */
497 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900499 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900501
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700502 /**
503 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
504 * Each list holds references to all NetworkAgentInfos that are used to
505 * satisfy requests for that network type.
506 *
507 * This array is built out at startup such that an unsupported network
508 * doesn't get an ArrayList instance, making this a tristate:
509 * unsupported, supported but not active and active.
510 *
511 * The actual lists are populated when we scan the network types that
512 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900513 *
514 * Threading model:
515 * - addSupportedType() is only called in the constructor
516 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
517 * They are therefore not thread-safe with respect to each other.
518 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
519 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
520 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700521 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900522 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700523
524 public LegacyTypeTracker() {
525 mTypeLists = (ArrayList<NetworkAgentInfo>[])
526 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
527 }
528
529 public void addSupportedType(int type) {
530 if (mTypeLists[type] != null) {
531 throw new IllegalStateException(
532 "legacy list for type " + type + "already initialized");
533 }
534 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
535 }
536
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700537 public boolean isTypeSupported(int type) {
538 return isNetworkTypeValid(type) && mTypeLists[type] != null;
539 }
540
541 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900542 synchronized (mTypeLists) {
543 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
544 return mTypeLists[type].get(0);
545 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700546 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900547 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700548 }
549
Robert Greenwalt8d482522015-06-24 13:23:42 -0700550 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900551 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700553 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900554 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900555 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900556 }
557 }
558
559 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 public void add(int type, NetworkAgentInfo nai) {
561 if (!isTypeSupported(type)) {
562 return; // Invalid network type.
563 }
564 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
565
566 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
567 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700568 return;
569 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900570 synchronized (mTypeLists) {
571 list.add(nai);
572 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900573
574 // 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 +0900575 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900576 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
578 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700579 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700580 }
581
Lorenzo Colittia793a672014-07-31 23:20:17 +0900582 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900583 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900584 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
585 if (list == null || list.isEmpty()) {
586 return;
587 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900588 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900589
Hugo Benichi78caa2582016-06-21 09:48:07 +0900590 synchronized (mTypeLists) {
591 if (!list.remove(nai)) {
592 return;
593 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594 }
595
Robert Greenwalt8d482522015-06-24 13:23:42 -0700596 final DetailedState state = DetailedState.DISCONNECTED;
597
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900598 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700599 maybeLogBroadcast(nai, state, type, wasDefault);
600 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900601 }
602
603 if (!list.isEmpty() && wasFirstNetwork) {
604 if (DBG) log("Other network available for type " + type +
605 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900606 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700607 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
608 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900609 }
610 }
611
612 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900613 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
614 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700615 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900616 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700617 }
618 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700619
Robert Greenwalt8d482522015-06-24 13:23:42 -0700620 // send out another legacy broadcast - currently only used for suspend/unsuspend
621 // toggle
622 public void update(NetworkAgentInfo nai) {
623 final boolean isDefault = isDefaultNetwork(nai);
624 final DetailedState state = nai.networkInfo.getDetailedState();
625 for (int type = 0; type < mTypeLists.length; type++) {
626 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700627 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900628 final boolean isFirst = contains && (nai == list.get(0));
629 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700630 maybeLogBroadcast(nai, state, type, isDefault);
631 sendLegacyNetworkBroadcast(nai, state, type);
632 }
633 }
634 }
635
Lorenzo Colittia793a672014-07-31 23:20:17 +0900636 private String naiToString(NetworkAgentInfo nai) {
637 String name = (nai != null) ? nai.name() : "null";
638 String state = (nai.networkInfo != null) ?
639 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
640 "???/???";
641 return name + " " + state;
642 }
643
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700644 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900645 pw.println("mLegacyTypeTracker:");
646 pw.increaseIndent();
647 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700648 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900649 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700650 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900651 pw.println();
652 pw.println("Current state:");
653 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900654 synchronized (mTypeLists) {
655 for (int type = 0; type < mTypeLists.length; type++) {
656 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
657 for (NetworkAgentInfo nai : mTypeLists[type]) {
658 pw.println(type + " " + naiToString(nai));
659 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900660 }
661 }
662 pw.decreaseIndent();
663 pw.decreaseIndent();
664 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700665 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700666 }
667 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
668
Jeff Sharkey899223b2012-08-04 15:24:58 -0700669 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700670 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900671 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
672 }
673
674 @VisibleForTesting
675 protected ConnectivityService(Context context, INetworkManagementService netManager,
676 INetworkStatsService statsService, INetworkPolicyManager policyManager,
677 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800678 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800679
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900680 mSystemProperties = getSystemProperties();
681
Hugo Benichif9fdf872016-07-28 17:53:06 +0900682 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900683 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900684 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900685 mNetworkRequests.put(mDefaultRequest, defaultNRI);
686 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900687
688 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900689 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700690
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900691 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900692 mHandlerThread.start();
693 mHandler = new InternalHandler(mHandlerThread.getLooper());
694 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700695
Jeremy Joslin79294842014-12-03 17:15:28 -0800696 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
697 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
698
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900699 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900700
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700701 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700702 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800703 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700704 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900705 mPolicyManagerInternal = checkNotNull(
706 LocalServices.getService(NetworkPolicyManagerInternal.class),
707 "missing NetworkPolicyManagerInternal");
708
Jeff Sharkey82f85212012-08-24 11:17:25 -0700709 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700710 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700711
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700712 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900713 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700714 } catch (RemoteException e) {
715 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700716 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700717 }
718
719 final PowerManager powerManager = (PowerManager) context.getSystemService(
720 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700721 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
722 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
723 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800724 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700725
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700726 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700727
Wink Saville51f456f2013-04-23 14:26:51 -0700728 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900729 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700730 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700731 String[] naStrings = context.getResources().getStringArray(
732 com.android.internal.R.array.networkAttributes);
733 for (String naString : naStrings) {
734 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700735 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700736 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700737 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800738 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700739 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700740 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700741 }
Wink Saville51f456f2013-04-23 14:26:51 -0700742 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
743 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
744 n.type);
745 continue;
746 }
Wink Saville975c8482011-04-07 14:23:45 -0700747 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800748 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700749 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700750 continue;
751 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700752 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700753
Wink Saville975c8482011-04-07 14:23:45 -0700754 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700755 mNetworksDefined++;
756 } catch(Exception e) {
757 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700758 }
759 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700760
761 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
762 if (mNetConfigs[TYPE_VPN] == null) {
763 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
764 // don't need to add TYPE_VPN to mNetConfigs.
765 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
766 mNetworksDefined++; // used only in the log() statement below.
767 }
768
Wink Saville5e56bc52013-07-29 15:00:57 -0700769 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700770
Robert Greenwalt50393202011-06-21 17:26:14 -0700771 mProtectedNetworks = new ArrayList<Integer>();
772 int[] protectedNetworks = context.getResources().getIntArray(
773 com.android.internal.R.array.config_protectedNetworks);
774 for (int p : protectedNetworks) {
775 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
776 mProtectedNetworks.add(p);
777 } else {
778 if (DBG) loge("Ignoring protectedNetwork " + p);
779 }
780 }
781
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900782 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
783 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700784
Christopher Wiley497c1472016-10-11 13:26:03 -0700785 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
786 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800787
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700788 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
789
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700790 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700791 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100792 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700793 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700794 intentFilter.addAction(Intent.ACTION_USER_ADDED);
795 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000796 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700797 mContext.registerReceiverAsUser(
798 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000799 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
800 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900801
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700802 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700803 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700804 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700805 } catch (RemoteException e) {
806 loge("Error registering observer :" + e);
807 }
808
Erik Klineda4bfa82015-04-30 12:58:40 +0900809 mSettingsObserver = new SettingsObserver(mContext, mHandler);
810 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800811
John Spurlockbf991a82013-06-24 14:20:23 -0400812 mDataConnectionStats = new DataConnectionStats(mContext);
813 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400814
Jason Monkdecd2952013-10-10 14:02:51 -0400815 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700816
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400817 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900818
819 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900820 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
821 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900822
823 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
824 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
825 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
826 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
827 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
828 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
829 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900830
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900831 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900832 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900833 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700835
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900836 private NetworkRequest createInternetRequestForTransport(
837 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900838 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900839 netCap.addCapability(NET_CAPABILITY_INTERNET);
840 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900841 if (transportType > -1) {
842 netCap.addTransportType(transportType);
843 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900844 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900845 }
846
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900847 // Used only for testing.
848 // TODO: Delete this and either:
849 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
850 // changing ContentResolver to make registerContentObserver non-final).
851 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
852 // by subclassing SettingsObserver.
853 @VisibleForTesting
854 void updateMobileDataAlwaysOn() {
855 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
856 }
857
Erik Klineda4bfa82015-04-30 12:58:40 +0900858 private void handleMobileDataAlwaysOn() {
859 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900860 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900861 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
862 if (enable == isEnabled) {
863 return; // Nothing to do.
864 }
865
866 if (enable) {
867 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900868 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900869 } else {
870 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
871 }
872 }
873
874 private void registerSettingsCallbacks() {
875 // Watch for global HTTP proxy changes.
876 mSettingsObserver.observe(
877 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
878 EVENT_APPLY_GLOBAL_HTTP_PROXY);
879
880 // Watch for whether or not to keep mobile data always on.
881 mSettingsObserver.observe(
882 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
883 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
884 }
885
Robert Greenwalt34524f02014-05-18 16:22:10 -0700886 private synchronized int nextNetworkRequestId() {
887 return mNextNetworkRequestId++;
888 }
889
Paul Jensen67b0b072015-06-10 11:22:17 -0400890 @VisibleForTesting
891 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400892 synchronized (mNetworkForNetId) {
893 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
894 int netId = mNextNetId;
895 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
896 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500897 if (!mNetIdInUse.get(netId)) {
898 mNetIdInUse.put(netId, true);
899 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400900 }
901 }
902 }
903 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700904 }
905
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600906 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800907 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600908 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
909 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800910 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600911 state = nai.getNetworkState();
912 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800913 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600914 final NetworkInfo info = new NetworkInfo(networkType, 0,
915 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800916 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
917 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600918 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
919 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800920 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600921 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600922 return state;
923 } else {
924 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800925 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400926 }
927
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800928 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
929 if (network == null) {
930 return null;
931 }
932 synchronized (mNetworkForNetId) {
933 return mNetworkForNetId.get(network.netId);
934 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600935 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900937 private Network[] getVpnUnderlyingNetworks(int uid) {
938 if (!mLockdownEnabled) {
939 int user = UserHandle.getUserId(uid);
940 synchronized (mVpns) {
941 Vpn vpn = mVpns.get(user);
942 if (vpn != null && vpn.appliesToUid(uid)) {
943 return vpn.getUnderlyingNetworks();
944 }
945 }
946 }
947 return null;
948 }
949
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800950 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400951 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800952
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900953 final Network[] networks = getVpnUnderlyingNetworks(uid);
954 if (networks != null) {
955 // getUnderlyingNetworks() returns:
956 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
957 // empty array => the VPN explicitly said "no default network".
958 // non-empty array => the VPN specified one or more default networks; we use the
959 // first one.
960 if (networks.length > 0) {
961 nai = getNetworkAgentInfoForNetwork(networks[0]);
962 } else {
963 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800964 }
965 }
966
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600968 return nai.getNetworkState();
969 } else {
970 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800971 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400972 }
973
974 /**
975 * Check if UID should be blocked from using the network with the given LinkProperties.
976 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600977 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
978 boolean ignoreBlocked) {
979 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900980 if (ignoreBlocked) {
981 return false;
982 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600983 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900984 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
985 if (isSystem(uid)) {
986 return false;
987 }
Robin Lee17e61832016-05-09 13:46:28 +0100988 synchronized (mVpns) {
989 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
990 if (vpn != null && vpn.isBlockingUid(uid)) {
991 return true;
992 }
993 }
Robert Greenwalt12e67352014-05-13 21:41:06 -0700994 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900995 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700996 }
997
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900998 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +0900999 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1000 return;
1001 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001002 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001003 synchronized (mBlockedAppUids) {
1004 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001005 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001006 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001007 blocked = false;
1008 } else {
1009 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001010 }
1011 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001012 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1013 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1014 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001015 }
1016
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001017 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001018 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1019 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1020 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1021 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001022 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001023 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001024 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1025
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001026 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001027 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001028 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001029 if (mLockdownTracker != null) {
1030 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001031 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001032
1033 // TODO: apply metered state closer to NetworkAgentInfo
1034 final long token = Binder.clearCallingIdentity();
1035 try {
1036 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1037 } catch (RemoteException e) {
1038 } finally {
1039 Binder.restoreCallingIdentity(token);
1040 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001041 }
1042
1043 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001044 * Return NetworkInfo for the active (i.e., connected) network interface.
1045 * It is assumed that at most one network is active at a time. If more
1046 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001047 * @return the info for the active network, or {@code null} if none is
1048 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001050 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 enforceAccessPermission();
1053 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001054 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001055 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001056 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1057 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 }
1059
Paul Jensen31a94f42015-02-13 14:18:39 -05001060 @Override
1061 public Network getActiveNetwork() {
1062 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001063 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001064 }
1065
1066 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001067 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001068 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001069 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001070 }
1071
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001072 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001073 final int user = UserHandle.getUserId(uid);
1074 int vpnNetId = NETID_UNSET;
1075 synchronized (mVpns) {
1076 final Vpn vpn = mVpns.get(user);
1077 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1078 }
1079 NetworkAgentInfo nai;
1080 if (vpnNetId != NETID_UNSET) {
1081 synchronized (mNetworkForNetId) {
1082 nai = mNetworkForNetId.get(vpnNetId);
1083 }
1084 if (nai != null) return nai.network;
1085 }
1086 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001087 if (nai != null
1088 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1089 nai = null;
1090 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001091 return nai != null ? nai.network : null;
1092 }
1093
Lorenzo Colitti18660282016-07-04 12:55:44 +09001094 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001095 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1096 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001097 final int uid = Binder.getCallingUid();
1098 NetworkState state = getUnfilteredActiveNetworkState(uid);
1099 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001100 }
1101
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001102 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001103 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001104 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001105 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001106 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001107 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001108 }
1109
1110 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001111 public NetworkInfo getNetworkInfo(int networkType) {
1112 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001113 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001114 if (getVpnUnderlyingNetworks(uid) != null) {
1115 // A VPN is active, so we may need to return one of its underlying networks. This
1116 // information is not available in LegacyTypeTracker, so we have to get it from
1117 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001118 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001119 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001120 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001121 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001122 }
1123 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001124 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001125 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001126 }
1127
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001128 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001129 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001130 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001131 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001132 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001133 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001134 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001135 return state.networkInfo;
1136 } else {
1137 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001138 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001139 }
1140
1141 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001142 public NetworkInfo[] getAllNetworkInfo() {
1143 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001144 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001145 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1146 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001147 NetworkInfo info = getNetworkInfo(networkType);
1148 if (info != null) {
1149 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001150 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001152 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
1154
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001155 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001156 public Network getNetworkForType(int networkType) {
1157 enforceAccessPermission();
1158 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001159 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1160 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001161 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001162 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001163 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001164 }
1165
1166 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001167 public Network[] getAllNetworks() {
1168 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001169 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001170 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001171 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001172 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001173 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001174 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001175 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001176 }
1177
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001178 @Override
1179 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1180 // The basic principle is: if an app's traffic could possibly go over a
1181 // network, without the app doing anything multinetwork-specific,
1182 // (hence, by "default"), then include that network's capabilities in
1183 // the array.
1184 //
1185 // In the normal case, app traffic only goes over the system's default
1186 // network connection, so that's the only network returned.
1187 //
1188 // With a VPN in force, some app traffic may go into the VPN, and thus
1189 // over whatever underlying networks the VPN specifies, while other app
1190 // traffic may go over the system default network (e.g.: a split-tunnel
1191 // VPN, or an app disallowed by the VPN), so the set of networks
1192 // returned includes the VPN's underlying networks and the system
1193 // default.
1194 enforceAccessPermission();
1195
1196 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1197
1198 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001199 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001200 if (nc != null) {
1201 result.put(nai.network, nc);
1202 }
1203
1204 if (!mLockdownEnabled) {
1205 synchronized (mVpns) {
1206 Vpn vpn = mVpns.get(userId);
1207 if (vpn != null) {
1208 Network[] networks = vpn.getUnderlyingNetworks();
1209 if (networks != null) {
1210 for (Network network : networks) {
1211 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001212 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001213 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001214 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001215 }
1216 }
1217 }
1218 }
1219 }
1220 }
1221
1222 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1223 out = result.values().toArray(out);
1224 return out;
1225 }
1226
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001227 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001228 public boolean isNetworkSupported(int networkType) {
1229 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001230 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001231 }
1232
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001233 /**
1234 * Return LinkProperties for the active (i.e., connected) default
1235 * network interface. It is assumed that at most one default network
1236 * is active at a time. If more than one is active, it is indeterminate
1237 * which will be returned.
1238 * @return the ip properties for the active network, or {@code null} if
1239 * none is active
1240 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001241 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001242 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 enforceAccessPermission();
1244 final int uid = Binder.getCallingUid();
1245 NetworkState state = getUnfilteredActiveNetworkState(uid);
1246 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001247 }
1248
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001249 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001250 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001251 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1253 if (nai != null) {
1254 synchronized (nai) {
1255 return new LinkProperties(nai.linkProperties);
1256 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001257 }
1258 return null;
1259 }
1260
Robert Greenwalt12e67352014-05-13 21:41:06 -07001261 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001262 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001263 public LinkProperties getLinkProperties(Network network) {
1264 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001265 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1266 }
1267
1268 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1269 if (nai == null) {
1270 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001271 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001272 synchronized (nai) {
1273 return new LinkProperties(nai.linkProperties);
1274 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001275 }
1276
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001277 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001278 if (nai != null) {
1279 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001280 if (nai.networkCapabilities != null) {
1281 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001282 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001283 }
1284 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001285 return null;
1286 }
1287
1288 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001289 public NetworkCapabilities getNetworkCapabilities(Network network) {
1290 enforceAccessPermission();
1291 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1292 }
1293
1294 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001295 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001296 // Require internal since we're handing out IMSI details
1297 enforceConnectivityInternalPermission();
1298
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001299 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001300 for (Network network : getAllNetworks()) {
1301 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1302 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001303 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001304 }
1305 }
1306 return result.toArray(new NetworkState[result.size()]);
1307 }
1308
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001309 @Override
1310 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1311 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001312 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001313 final long token = Binder.clearCallingIdentity();
1314 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001315 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1316 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001317 try {
1318 return mPolicyManager.getNetworkQuotaInfo(state);
1319 } catch (RemoteException e) {
1320 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001321 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001322 return null;
1323 } finally {
1324 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001325 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001326 }
1327
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001328 @Override
1329 public boolean isActiveNetworkMetered() {
1330 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001331
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001332 final NetworkInfo info = getActiveNetworkInfo();
1333 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001334 }
1335
Jeff Sharkey216c1812012-08-05 14:29:23 -07001336 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1337 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001338 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001339 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001340 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001341 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001342 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001343
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001344 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001345 * Ensure that a network route exists to deliver traffic to the specified
1346 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001347 * @param networkType the type of the network over which traffic to the
1348 * specified host is to be routed
1349 * @param hostAddress the IP address of the host to which the route is
1350 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001351 * @return {@code true} on success, {@code false} on failure
1352 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001353 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001354 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001355 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001356 if (mProtectedNetworks.contains(networkType)) {
1357 enforceConnectivityInternalPermission();
1358 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001359
Chad Brubakerc0234532014-02-14 13:24:29 -08001360 InetAddress addr;
1361 try {
1362 addr = InetAddress.getByAddress(hostAddress);
1363 } catch (UnknownHostException e) {
1364 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1365 return false;
1366 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001367
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001369 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 return false;
1371 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001372
1373 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1374 if (nai == null) {
1375 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1376 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1377 } else {
1378 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1379 }
1380 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001381 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001382
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001383 DetailedState netState;
1384 synchronized (nai) {
1385 netState = nai.networkInfo.getDetailedState();
1386 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001387
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001388 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001389 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001390 log("requestRouteToHostAddress on down network "
1391 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001392 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001393 }
1394 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001396
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001397 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001398 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001399 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001400 LinkProperties lp;
1401 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001402 synchronized (nai) {
1403 lp = nai.linkProperties;
1404 netId = nai.network.netId;
1405 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001406 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001407 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1408 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001409 } finally {
1410 Binder.restoreCallingIdentity(token);
1411 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001412 }
1413
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001414 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001415 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001416 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001417 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001418 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001419 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001420 if (bestRoute.getGateway().equals(addr)) {
1421 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001422 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001423 } else {
1424 // if we will connect to this through another route, add a direct route
1425 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001426 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001427 }
1428 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001429 if (DBG) log("Adding legacy route " + bestRoute +
1430 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001431 try {
1432 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1433 } catch (Exception e) {
1434 // never crash - catch them all
1435 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001436 return false;
1437 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001438 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001439 }
1440
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001441 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001442 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001443 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001444 // TODO: notify UID when it has requested targeted updates
1445 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001446 @Override
1447 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001448 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001449 @Override
1450 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001451 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001452 if (restrictBackground) {
1453 log("onRestrictBackgroundChanged(true): disabling tethering");
1454 mTethering.untetherAll();
1455 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001456 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001457 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001458 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001459 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001460 };
1461
Robin Lee3b3dd942015-05-12 18:14:58 +01001462 /**
1463 * Require that the caller is either in the same user or has appropriate permission to interact
1464 * across users.
1465 *
1466 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1467 */
1468 private void enforceCrossUserPermission(int userId) {
1469 if (userId == UserHandle.getCallingUserId()) {
1470 // Not a cross-user call.
1471 return;
1472 }
1473 mContext.enforceCallingOrSelfPermission(
1474 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1475 "ConnectivityService");
1476 }
1477
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001478 private void enforceInternetPermission() {
1479 mContext.enforceCallingOrSelfPermission(
1480 android.Manifest.permission.INTERNET,
1481 "ConnectivityService");
1482 }
1483
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001484 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001485 mContext.enforceCallingOrSelfPermission(
1486 android.Manifest.permission.ACCESS_NETWORK_STATE,
1487 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001488 }
1489
1490 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001491 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001492 }
1493
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001494 private void enforceTetherAccessPermission() {
1495 mContext.enforceCallingOrSelfPermission(
1496 android.Manifest.permission.ACCESS_NETWORK_STATE,
1497 "ConnectivityService");
1498 }
1499
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001500 private void enforceConnectivityInternalPermission() {
1501 mContext.enforceCallingOrSelfPermission(
1502 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1503 "ConnectivityService");
1504 }
1505
Hugo Benichi514da602016-07-19 15:59:27 +09001506 private void enforceConnectivityRestrictedNetworksPermission() {
1507 try {
1508 mContext.enforceCallingOrSelfPermission(
1509 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1510 "ConnectivityService");
1511 return;
1512 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1513 enforceConnectivityInternalPermission();
1514 }
1515
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001516 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001517 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001518 }
1519
Lorenzo Colitti18660282016-07-04 12:55:44 +09001520 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001521 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001522 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001523 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001524 }
1525
1526 private void sendInetConditionBroadcast(NetworkInfo info) {
1527 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1528 }
1529
Wink Saville628b0852011-08-04 15:01:58 -07001530 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001531 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001532 info = new NetworkInfo(info);
1533 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001534 }
1535
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001536 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001537 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001538 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001539 if (info.isFailover()) {
1540 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1541 info.setFailover(false);
1542 }
1543 if (info.getReason() != null) {
1544 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1545 }
1546 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001547 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1548 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001549 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001550 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001551 return intent;
1552 }
1553
1554 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1555 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1556 }
1557
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001558 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001559 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1560 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1561 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001562 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001563 final long ident = Binder.clearCallingIdentity();
1564 try {
1565 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1566 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1567 } finally {
1568 Binder.restoreCallingIdentity(ident);
1569 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001570 }
1571
Mike Lockwood0f79b542009-08-14 14:18:49 -04001572 private void sendStickyBroadcast(Intent intent) {
1573 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001574 if (!mSystemReady) {
1575 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001576 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001577 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001578 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001579 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001580 }
1581
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001582 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001583 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001584 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001585 final NetworkInfo ni = intent.getParcelableExtra(
1586 ConnectivityManager.EXTRA_NETWORK_INFO);
1587 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1588 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1589 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001590 } else {
1591 BroadcastOptions opts = BroadcastOptions.makeBasic();
1592 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1593 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001594 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001595 final IBatteryStats bs = BatteryStatsService.getService();
1596 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001597 bs.noteConnectivityChanged(intent.getIntExtra(
1598 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1599 ni != null ? ni.getState().toString() : "?");
1600 } catch (RemoteException e) {
1601 }
1602 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001603 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001604 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001605 } finally {
1606 Binder.restoreCallingIdentity(ident);
1607 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001608 }
1609 }
1610
1611 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001612 loadGlobalProxy();
1613
Mike Lockwood0f79b542009-08-14 14:18:49 -04001614 synchronized(this) {
1615 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001616 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001617 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001618 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001619 }
1620 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001621 // load the global proxy at startup
1622 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001623
Robin Lee244ce8e2016-01-05 18:03:46 +00001624 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1625 // for user to unlock device too.
1626 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001627
Erik Klineda4bfa82015-04-30 12:58:40 +09001628 // Configure whether mobile data is always on.
1629 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1630
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001631 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001632
1633 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001634 }
1635
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001636 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001637 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001638 *
1639 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001640 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001641 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001642 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1643 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001644
1645 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001646 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001647
Robert Greenwalt7b816022014-04-18 15:25:25 -07001648 if (networkAgent.networkCapabilities.hasTransport(
1649 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001650 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1651 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001652 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001653 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001654 } else if (networkAgent.networkCapabilities.hasTransport(
1655 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001656 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1657 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001658 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001659 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001660 } else {
1661 // do not track any other networks
1662 timeout = 0;
1663 }
1664
Robert Greenwalt7b816022014-04-18 15:25:25 -07001665 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001666 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001667 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001668 } catch (Exception e) {
1669 // You shall not crash!
1670 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001671 }
1672 }
1673 }
1674
1675 /**
1676 * Remove data activity tracking when network disconnects.
1677 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001678 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1679 final String iface = networkAgent.linkProperties.getInterfaceName();
1680 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001681
Robert Greenwalt7b816022014-04-18 15:25:25 -07001682 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1683 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001684 try {
1685 // the call fails silently if no idletimer setup for this interface
1686 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001687 } catch (Exception e) {
1688 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001689 }
1690 }
1691 }
1692
1693 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001694 * Reads the network specific MTU size from reources.
1695 * and set it on it's iface.
1696 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001697 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1698 final String iface = newLp.getInterfaceName();
1699 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001700 if (oldLp == null && mtu == 0) {
1701 // Silently ignore unset MTU value.
1702 return;
1703 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001704 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1705 if (VDBG) log("identical MTU - not setting");
1706 return;
1707 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001708 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001709 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001710 return;
1711 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001712
w1997615afd812014-08-05 15:18:11 -07001713 // Cannot set MTU without interface name
1714 if (TextUtils.isEmpty(iface)) {
1715 loge("Setting MTU size with null iface.");
1716 return;
1717 }
1718
Robert Greenwalt7b816022014-04-18 15:25:25 -07001719 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001720 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001721 mNetd.setMtu(iface, mtu);
1722 } catch (Exception e) {
1723 Slog.e(TAG, "exception in setMtu()" + e);
1724 }
1725 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001726
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001727 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001728 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1729
1730 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001731 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001732 protected MockableSystemProperties getSystemProperties() {
1733 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001734 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001735
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001736 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1737 if (isDefaultNetwork(nai) == false) {
1738 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001739 }
1740
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001741 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1742 String[] values = null;
1743 if (tcpBufferSizes != null) {
1744 values = tcpBufferSizes.split(",");
1745 }
1746
1747 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001748 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001749 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1750 values = tcpBufferSizes.split(",");
1751 }
1752
1753 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1754
1755 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001756 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001757
1758 final String prefix = "/sys/kernel/ipv4/tcp_";
1759 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1760 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1761 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1762 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1763 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1764 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1765 mCurrentTcpBufferSizes = tcpBufferSizes;
1766 } catch (IOException e) {
1767 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001768 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001769
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001770 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001771 Settings.Global.TCP_DEFAULT_INIT_RWND,
1772 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001773 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1774 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001775 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001776 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001777 }
1778
Mattias Falk8b47b362011-08-23 14:15:13 +02001779 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001780 /*
1781 * Tell the VMs to toss their DNS caches
1782 */
1783 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1784 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001785 /*
1786 * Connectivity events can happen before boot has completed ...
1787 */
1788 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001789 final long ident = Binder.clearCallingIdentity();
1790 try {
1791 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1792 } finally {
1793 Binder.restoreCallingIdentity(ident);
1794 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001795 }
1796
Robert Greenwalt562cc542014-05-15 18:07:26 -07001797 @Override
1798 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001799 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001800 NETWORK_RESTORE_DELAY_PROP_NAME);
1801 if(restoreDefaultNetworkDelayStr != null &&
1802 restoreDefaultNetworkDelayStr.length() != 0) {
1803 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001804 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001805 } catch (NumberFormatException e) {
1806 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001808 // if the system property isn't set, use the value for the apn type
1809 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1810
1811 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1812 (mNetConfigs[networkType] != null)) {
1813 ret = mNetConfigs[networkType].restoreTime;
1814 }
1815 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001816 }
1817
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001818 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001819 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001820 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001821 }
1822 return false;
1823 }
1824
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001825 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1826 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1827 final long DIAG_TIME_MS = 5000;
1828 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1829 // Start gathering diagnostic information.
1830 netDiags.add(new NetworkDiagnostics(
1831 nai.network,
1832 new LinkProperties(nai.linkProperties), // Must be a copy.
1833 DIAG_TIME_MS));
1834 }
1835
1836 for (NetworkDiagnostics netDiag : netDiags) {
1837 pw.println();
1838 netDiag.waitForMeasurements();
1839 netDiag.dump(pw);
1840 }
1841 }
1842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001844 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1845 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001846 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001847
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001848 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001849 dumpNetworkDiagnostics(pw);
1850 return;
1851 }
Erik Kline379747a2015-06-05 17:47:34 +09001852
Lorenzo Colittie3805462015-06-03 11:18:24 +09001853 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001854 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001855 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001856 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001857 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001858 pw.println();
1859
Paul Jensen85cf78e2015-06-25 13:25:07 -04001860 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001861 pw.print("Active default network: ");
1862 if (defaultNai == null) {
1863 pw.println("none");
1864 } else {
1865 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001866 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001867 pw.println();
1868
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001869 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001870 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001871 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1872 pw.println(nai.toString());
1873 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001874 pw.println(String.format(
1875 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1876 nai.numForegroundNetworkRequests(),
1877 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1878 nai.numBackgroundNetworkRequests(),
1879 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001880 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001881 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1882 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001883 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001884 pw.decreaseIndent();
1885 pw.println("Lingered:");
1886 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001887 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001888 pw.decreaseIndent();
1889 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001890 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001891 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001892 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001893
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001894 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001895 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001896 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1897 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001898 }
1899 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001900 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001901
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001902 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001903
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001904 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001905 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001906
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001907 pw.println();
1908 mKeepaliveTracker.dump(pw);
1909
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001910 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001911 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001912
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001913 if (argsContain(args, "--short") == false) {
1914 pw.println();
1915 synchronized (mValidationLogs) {
1916 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001917 for (ValidationLog p : mValidationLogs) {
1918 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001919 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001920 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001921 pw.decreaseIndent();
1922 }
1923 }
Erik Kline7523eb32015-07-09 18:24:03 +09001924
1925 pw.println();
1926 pw.println("mNetworkRequestInfoLogs (most recent first):");
1927 pw.increaseIndent();
1928 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1929 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001930
1931 pw.println();
1932 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1933 pw.increaseIndent();
1934 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1935 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001936
1937 pw.println();
1938 pw.println("NetTransition WakeLock activity (most recent first):");
1939 pw.increaseIndent();
1940 mWakelockLogs.reverseDump(fd, pw, args);
1941 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001942 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001943 }
1944
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001945 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001946 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001947 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001948 if (officialNai != null && officialNai.equals(nai)) return true;
1949 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001950 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001951 " - " + nai);
1952 }
1953 return false;
1954 }
1955
Robert Greenwalt42acef32009-08-12 16:08:25 -07001956 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001957 private class NetworkStateTrackerHandler extends Handler {
1958 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001959 super(looper);
1960 }
1961
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001962 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001964 default:
1965 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001966 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001967 handleAsyncChannelHalfConnect(msg);
1968 break;
1969 }
1970 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1971 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1972 if (nai != null) nai.asyncChannel.disconnect();
1973 break;
1974 }
1975 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1976 handleAsyncChannelDisconnected(msg);
1977 break;
1978 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001979 }
1980 return true;
1981 }
1982
1983 private void maybeHandleNetworkAgentMessage(Message msg) {
1984 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1985 if (nai == null) {
1986 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001987 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001988 }
1989 return;
1990 }
1991
1992 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001993 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001994 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
1995 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09001996 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
1997 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001998 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07001999 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002000 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002001 break;
2002 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002003 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002004 if (VDBG) {
2005 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002006 "; created=" + nai.created +
2007 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002008 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002009 LinkProperties oldLp = nai.linkProperties;
2010 synchronized (nai) {
2011 nai.linkProperties = (LinkProperties)msg.obj;
2012 }
Robin Lee585e2482016-05-01 23:00:00 +01002013 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002014 break;
2015 }
2016 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002017 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002018 updateNetworkInfo(nai, info);
2019 break;
2020 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002021 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002022 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002023 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002024 break;
2025 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002026 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002027 try {
2028 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002029 } catch (Exception e) {
2030 // Never crash!
2031 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002032 }
2033 break;
2034 }
2035 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002036 try {
2037 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002038 } catch (Exception e) {
2039 // Never crash!
2040 loge("Exception in removeVpnUidRanges: " + e);
2041 }
2042 break;
2043 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002044 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002045 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2046 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002047 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002048 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002049 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002050 break;
2051 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002052 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002053 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2054 break;
2055 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002056 }
2057 }
2058
2059 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2060 switch (msg.what) {
2061 default:
2062 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002063 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002064 final NetworkAgentInfo nai;
2065 synchronized (mNetworkForNetId) {
2066 nai = mNetworkForNetId.get(msg.arg2);
2067 }
2068 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002069 final boolean valid =
2070 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002071 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002072 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2073 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002074 if (valid != nai.lastValidated) {
2075 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002076 nai.lastValidated = valid;
2077 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002078 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002079 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2080 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002081 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002082 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002083 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002084 Bundle redirectUrlBundle = new Bundle();
2085 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002086 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002087 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002088 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002089 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002090 if (wasValidated && !nai.lastValidated) {
2091 handleNetworkUnvalidated(nai);
2092 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002093 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002094 break;
2095 }
Paul Jensen869868be2014-05-15 10:33:05 -04002096 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002097 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002098 final boolean visible = (msg.arg1 != 0);
2099 final NetworkAgentInfo nai;
2100 synchronized (mNetworkForNetId) {
2101 nai = mNetworkForNetId.get(netId);
2102 }
Calvin Onbe96da12016-10-11 15:10:46 -07002103 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002104 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002105 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002106 nai.lastCaptivePortalDetected = visible;
2107 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002108 if (nai.lastCaptivePortalDetected &&
2109 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2110 if (DBG) log("Avoiding captive portal network: " + nai.name());
2111 nai.asyncChannel.sendMessage(
2112 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2113 teardownUnneededNetwork(nai);
2114 break;
2115 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002116 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002117 }
2118 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002119 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002120 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002121 if (nai == null) {
2122 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2123 break;
2124 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002125 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002126 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002127 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002128 }
Paul Jensen869868be2014-05-15 10:33:05 -04002129 }
Paul Jensen869868be2014-05-15 10:33:05 -04002130 break;
2131 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002132 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002133 return true;
2134 }
2135
Calvin Onbe96da12016-10-11 15:10:46 -07002136 private int getCaptivePortalMode() {
2137 return Settings.Global.getInt(mContext.getContentResolver(),
2138 Settings.Global.CAPTIVE_PORTAL_MODE,
2139 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2140 }
2141
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002142 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2143 switch (msg.what) {
2144 default:
2145 return false;
2146 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2147 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2148 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2149 handleLingerComplete(nai);
2150 }
2151 break;
2152 }
2153 }
2154 return true;
2155 }
2156
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002157 @Override
2158 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002159 if (!maybeHandleAsyncChannelMessage(msg) &&
2160 !maybeHandleNetworkMonitorMessage(msg) &&
2161 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002162 maybeHandleNetworkAgentMessage(msg);
2163 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002164 }
2165 }
2166
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002167 private void updateLingerState(NetworkAgentInfo nai, long now) {
2168 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2169 // 2. If the network was lingering and there are now requests, unlinger it.
2170 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2171 // one lingered request, start lingering.
2172 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002173 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002174 if (DBG) log("Unlingering " + nai.name());
2175 nai.unlinger();
2176 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002177 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002178 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002179 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002180 nai.linger();
2181 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2182 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2183 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002184 }
2185
Robert Greenwalt7b816022014-04-18 15:25:25 -07002186 private void handleAsyncChannelHalfConnect(Message msg) {
2187 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002188 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002189 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2190 if (VDBG) log("NetworkFactory connected");
2191 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002192 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002193 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002194 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002195 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002196 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002197 }
2198 } else {
2199 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002200 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002201 }
2202 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2203 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2204 if (VDBG) log("NetworkAgent connected");
2205 // A network agent has requested a connection. Establish the connection.
2206 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2207 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2208 } else {
2209 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002210 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002211 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002212 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002213 synchronized (mNetworkForNetId) {
2214 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002215 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002216 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002217 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002218 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002219 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002220 }
2221 }
2222 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002223
Robert Greenwalt7b816022014-04-18 15:25:25 -07002224 private void handleAsyncChannelDisconnected(Message msg) {
2225 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2226 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002227 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002228 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002229 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002230 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002231 // TODO - if we move the logic to the network agent (have them disconnect
2232 // because they lost all their requests or because their score isn't good)
2233 // then they would disconnect organically, report their new state and then
2234 // disconnect the channel.
2235 if (nai.networkInfo.isConnected()) {
2236 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2237 null, null);
2238 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002239 final boolean wasDefault = isDefaultNetwork(nai);
2240 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002241 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002242 // Log default network disconnection before required book-keeping.
2243 // Let rematchAllNetworksAndRequests() below record a new default network event
2244 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2245 // whose timestamps tell how long it takes to recover a default network.
2246 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002247 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002248 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002249 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2250 // by other networks that are already connected. Perhaps that can be done by
2251 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2252 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002253 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002254 mKeepaliveTracker.handleStopAllKeepalives(nai,
2255 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002256 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002257 mNetworkAgentInfos.remove(msg.replyTo);
2258 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002259 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002260 // Remove the NetworkAgent, but don't mark the netId as
2261 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002262 mNetworkForNetId.remove(nai.network.netId);
2263 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002264 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002265 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2266 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002267 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2268 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2269 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002270 sendUpdatedScoreToFactories(request, 0);
2271 }
2272 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002273 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002274 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002275 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002276 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002277 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002278 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002279 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002280 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002281 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002282 if (nai.created) {
2283 // Tell netd to clean up the configuration for this network
2284 // (routing rules, DNS, etc).
2285 // This may be slow as it requires a lot of netd shelling out to ip and
2286 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2287 // after we've rematched networks with requests which should make a potential
2288 // fallback network the default or requested a new network from the
2289 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2290 // long time.
2291 try {
2292 mNetd.removeNetwork(nai.network.netId);
2293 } catch (Exception e) {
2294 loge("Exception removing network: " + e);
2295 }
2296 }
2297 synchronized (mNetworkForNetId) {
2298 mNetIdInUse.delete(nai.network.netId);
2299 }
2300 } else {
2301 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2302 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002303 }
2304 }
2305
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002306 // If this method proves to be too slow then we can maintain a separate
2307 // pendingIntent => NetworkRequestInfo map.
2308 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2309 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2310 Intent intent = pendingIntent.getIntent();
2311 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2312 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2313 if (existingPendingIntent != null &&
2314 existingPendingIntent.getIntent().filterEquals(intent)) {
2315 return entry.getValue();
2316 }
2317 }
2318 return null;
2319 }
2320
2321 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2322 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2323
2324 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2325 if (existingRequest != null) { // remove the existing request.
2326 if (DBG) log("Replacing " + existingRequest.request + " with "
2327 + nri.request + " because their intents matched.");
2328 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2329 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002330 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002331 }
2332
Erik Klineda4bfa82015-04-30 12:58:40 +09002333 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002334 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002335 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002336 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002337 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002338 if (nri.request.networkCapabilities.hasSignalStrength() &&
2339 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2340 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002341 }
2342 }
2343 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002344 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002345 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002346 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002347 }
2348 }
2349
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002350 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2351 int callingUid) {
2352 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2353 if (nri != null) {
2354 handleReleaseNetworkRequest(nri.request, callingUid);
2355 }
2356 }
2357
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002358 // Determines whether the network is the best (or could become the best, if it validated), for
2359 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2360 // on the value of reason:
2361 //
2362 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2363 // then it should be torn down.
2364 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2365 // then it should be lingered.
2366 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2367 final int numRequests;
2368 switch (reason) {
2369 case TEARDOWN:
2370 numRequests = nai.numRequestNetworkRequests();
2371 break;
2372 case LINGER:
2373 numRequests = nai.numForegroundNetworkRequests();
2374 break;
2375 default:
2376 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2377 return true;
2378 }
2379
2380 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002381 return false;
2382 }
Paul Jensene0988542015-06-25 15:30:08 -04002383 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002384 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2385 // Background requests don't affect lingering.
2386 continue;
2387 }
2388
Paul Jensene0988542015-06-25 15:30:08 -04002389 // If this Network is already the highest scoring Network for a request, or if
2390 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002391 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002392 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002393 // Note that this catches two important cases:
2394 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2395 // is currently satisfying the request. This is desirable when
2396 // cellular ends up validating but WiFi does not.
2397 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002398 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002399 // WiFi ends up validating and out scoring cellular.
2400 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2401 nai.getCurrentScoreAsValidated())) {
2402 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002403 }
2404 }
Paul Jensene0988542015-06-25 15:30:08 -04002405 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002406 }
2407
Erik Klineacdd6392016-07-07 16:50:58 +09002408 private NetworkRequestInfo getNriForAppRequest(
2409 NetworkRequest request, int callingUid, String requestedOperation) {
2410 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2411
Robert Greenwalt9258c642014-03-26 16:47:06 -07002412 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002413 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002414 log(String.format("UID %d attempted to %s for unowned request %s",
2415 callingUid, requestedOperation, nri));
2416 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002417 }
Erik Klineacdd6392016-07-07 16:50:58 +09002418 }
2419
2420 return nri;
2421 }
2422
Erik Kline57faba92015-11-25 12:49:38 +09002423 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2424 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2425 nri.request.requestId) == null) {
2426 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2427 }
2428 }
2429
Erik Klineacdd6392016-07-07 16:50:58 +09002430 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2431 final NetworkRequestInfo nri = getNriForAppRequest(
2432 request, callingUid, "release NetworkRequest");
Erik Kline57faba92015-11-25 12:49:38 +09002433 if (nri != null) {
2434 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2435 }
2436 }
Erik Klineacdd6392016-07-07 16:50:58 +09002437
Erik Kline57faba92015-11-25 12:49:38 +09002438 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2439 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2440 if (VDBG || (DBG && nri.request.isRequest())) {
2441 log("releasing " + nri.request + " (" + logCallbackType + ")");
2442 }
Erik Klineacdd6392016-07-07 16:50:58 +09002443 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002444 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002445 synchronized (mUidToNetworkRequestCount) {
2446 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2447 if (requests < 1) {
2448 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2449 nri.mUid);
2450 } else if (requests == 1) {
2451 mUidToNetworkRequestCount.removeAt(
2452 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2453 } else {
2454 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2455 }
2456 }
2457 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2458 if (nri.request.isRequest()) {
2459 boolean wasKept = false;
2460 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2461 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002462 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002463 nai.removeRequest(nri.request.requestId);
2464 if (VDBG) {
2465 log(" Removing from current network " + nai.name() +
2466 ", leaving " + nai.numNetworkRequests() + " requests.");
2467 }
2468 // If there are still lingered requests on this network, don't tear it down,
2469 // but resume lingering instead.
2470 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002471 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002472 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2473 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002474 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002475 wasKept = true;
2476 }
2477 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002478 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2479 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002480 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002481 }
Erik Klineacdd6392016-07-07 16:50:58 +09002482 }
2483
2484 // TODO: remove this code once we know that the Slog.wtf is never hit.
2485 //
2486 // Find all networks that are satisfying this request and remove the request
2487 // from their request lists.
2488 // TODO - it's my understanding that for a request there is only a single
2489 // network satisfying it, so this loop is wasteful
2490 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2491 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2492 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2493 otherNai.name() + ", but mNetworkAgentInfos says " +
2494 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002495 }
2496 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002497
Erik Klineacdd6392016-07-07 16:50:58 +09002498 // Maintain the illusion. When this request arrived, we might have pretended
2499 // that a network connected to serve it, even though the network was already
2500 // connected. Now that this request has gone away, we might have to pretend
2501 // that the network disconnected. LegacyTypeTracker will generate that
2502 // phantom disconnect for this type.
2503 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2504 boolean doRemove = true;
2505 if (wasKept) {
2506 // check if any of the remaining requests for this network are for the
2507 // same legacy type - if so, don't remove the nai
2508 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2509 NetworkRequest otherRequest = nai.requestAt(i);
2510 if (otherRequest.legacyType == nri.request.legacyType &&
2511 otherRequest.isRequest()) {
2512 if (DBG) log(" still have other legacy request - leaving");
2513 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002514 }
2515 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002516 }
2517
Erik Klineacdd6392016-07-07 16:50:58 +09002518 if (doRemove) {
2519 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002520 }
2521 }
Erik Klineacdd6392016-07-07 16:50:58 +09002522
2523 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2524 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2525 nri.request);
2526 }
2527 } else {
2528 // listens don't have a singular affectedNetwork. Check all networks to see
2529 // if this listen request applies and remove it.
2530 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2531 nai.removeRequest(nri.request.requestId);
2532 if (nri.request.networkCapabilities.hasSignalStrength() &&
2533 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2534 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2535 }
2536 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002537 }
Erik Kline57faba92015-11-25 12:49:38 +09002538 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002539 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002540
Lorenzo Colitti18660282016-07-04 12:55:44 +09002541 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002542 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2543 enforceConnectivityInternalPermission();
2544 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2545 accept ? 1 : 0, always ? 1: 0, network));
2546 }
2547
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002548 @Override
2549 public void setAvoidUnvalidated(Network network) {
2550 enforceConnectivityInternalPermission();
2551 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2552 }
2553
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002554 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2555 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2556 " accept=" + accept + " always=" + always);
2557
2558 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2559 if (nai == null) {
2560 // Nothing to do.
2561 return;
2562 }
2563
2564 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002565 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002566 return;
2567 }
2568
2569 if (!nai.networkMisc.explicitlySelected) {
2570 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2571 }
2572
2573 if (accept != nai.networkMisc.acceptUnvalidated) {
2574 int oldScore = nai.getCurrentScore();
2575 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002576 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002577 sendUpdatedScoreToFactories(nai);
2578 }
2579
2580 if (always) {
2581 nai.asyncChannel.sendMessage(
2582 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2583 }
2584
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002585 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002586 // Tell the NetworkAgent to not automatically reconnect to the network.
2587 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2588 // Teardown the nework.
2589 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002590 }
2591
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002592 }
2593
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002594 private void handleSetAvoidUnvalidated(Network network) {
2595 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2596 if (nai == null || nai.lastValidated) {
2597 // Nothing to do. The network either disconnected or revalidated.
2598 return;
2599 }
2600 if (!nai.avoidUnvalidated) {
2601 int oldScore = nai.getCurrentScore();
2602 nai.avoidUnvalidated = true;
2603 rematchAllNetworksAndRequests(nai, oldScore);
2604 sendUpdatedScoreToFactories(nai);
2605 }
2606 }
2607
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002608 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002609 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002610 mHandler.sendMessageDelayed(
2611 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2612 PROMPT_UNVALIDATED_DELAY_MS);
2613 }
2614
Hugo Benichic8e9e122016-09-14 23:23:08 +00002615 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002616 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002617 }
2618
Erik Kline065ab6e2016-10-02 18:02:14 +09002619 private void rematchForAvoidBadWifiUpdate() {
2620 rematchAllNetworksAndRequests(null, 0);
2621 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2622 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2623 sendUpdatedScoreToFactories(nai);
2624 }
2625 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002626 }
2627
Erik Kline065ab6e2016-10-02 18:02:14 +09002628 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002629 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002630 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002631 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002632 if (!configRestrict) {
2633 pw.println("Bad Wi-Fi avoidance: unrestricted");
2634 return;
2635 }
2636
2637 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2638 pw.increaseIndent();
2639 pw.println("Config restrict: " + configRestrict);
2640
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002641 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002642 String description;
2643 // Can't use a switch statement because strings are legal case labels, but null is not.
2644 if ("0".equals(value)) {
2645 description = "get stuck";
2646 } else if (value == null) {
2647 description = "prompt";
2648 } else if ("1".equals(value)) {
2649 description = "avoid";
2650 } else {
2651 description = value + " (?)";
2652 }
2653 pw.println("User setting: " + description);
2654 pw.println("Network overrides:");
2655 pw.increaseIndent();
2656 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2657 if (nai.avoidUnvalidated) {
2658 pw.println(nai.name());
2659 }
2660 }
2661 pw.decreaseIndent();
2662 pw.decreaseIndent();
2663 }
2664
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002665 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2666 final String action;
2667 switch (type) {
2668 case NO_INTERNET:
2669 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2670 break;
2671 case LOST_INTERNET:
2672 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2673 break;
2674 default:
2675 Slog.wtf(TAG, "Unknown notification type " + type);
2676 return;
2677 }
2678
2679 Intent intent = new Intent(action);
2680 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2681 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2682 intent.setClassName("com.android.settings",
2683 "com.android.settings.wifi.WifiNoInternetDialog");
2684
2685 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2686 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2687 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2688 }
2689
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002690 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002691 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002692 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2693
2694 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2695 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002696 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002697 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002698 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2699 return;
2700 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002701 showValidationNotification(nai, NotificationType.NO_INTERNET);
2702 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002703
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002704 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2705 NetworkCapabilities nc = nai.networkCapabilities;
2706 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002707
Erik Kline065ab6e2016-10-02 18:02:14 +09002708 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002709 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002710 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2711 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002712 }
2713
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002714 @Override
2715 public int getMultipathPreference(Network network) {
2716 enforceAccessPermission();
2717
2718 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2719 if (nai != null && !nai.networkInfo.isMetered()) {
2720 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2721 }
2722
2723 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2724 }
2725
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002726 private class InternalHandler extends Handler {
2727 public InternalHandler(Looper looper) {
2728 super(looper);
2729 }
2730
2731 @Override
2732 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002733 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002734 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002735 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002736 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002737 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002738 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002739 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002740 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002741 break;
2742 }
Jason Monkdecd2952013-10-10 14:02:51 -04002743 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002744 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002745 break;
2746 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002747 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002748 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2749 break;
2750 }
2751 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2752 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002753 break;
2754 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002755 case EVENT_REGISTER_NETWORK_AGENT: {
2756 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2757 break;
2758 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002759 case EVENT_REGISTER_NETWORK_REQUEST:
2760 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002761 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002762 break;
2763 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002764 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2765 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002766 handleRegisterNetworkRequestWithIntent(msg);
2767 break;
2768 }
Erik Kline57faba92015-11-25 12:49:38 +09002769 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2770 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2771 handleTimedOutNetworkRequest(nri);
2772 break;
2773 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002774 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2775 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2776 break;
2777 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002778 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002779 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002780 break;
2781 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002782 case EVENT_SET_ACCEPT_UNVALIDATED: {
2783 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2784 break;
2785 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002786 case EVENT_SET_AVOID_UNVALIDATED: {
2787 handleSetAvoidUnvalidated((Network) msg.obj);
2788 break;
2789 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002790 case EVENT_PROMPT_UNVALIDATED: {
2791 handlePromptUnvalidated((Network) msg.obj);
2792 break;
2793 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002794 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2795 handleMobileDataAlwaysOn();
2796 break;
2797 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002798 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2799 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2800 mKeepaliveTracker.handleStartKeepalive(msg);
2801 break;
2802 }
2803 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2804 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2805 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2806 int slot = msg.arg1;
2807 int reason = msg.arg2;
2808 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2809 break;
2810 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002811 case EVENT_SYSTEM_READY: {
2812 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2813 nai.networkMonitor.systemReady = true;
2814 }
2815 break;
2816 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002817 }
2818 }
2819 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002820
2821 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002822 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002823 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002824 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002825 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002826 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002827 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002828 } else {
2829 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2830 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002831 }
2832
2833 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002834 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002835 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002836 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002837
2838 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002839 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002840 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002841 } else {
2842 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2843 }
2844 }
2845
2846 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002847 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002848 public int getLastTetherError(String iface) {
2849 enforceTetherAccessPermission();
2850
2851 if (isTetheringSupported()) {
2852 return mTethering.getLastTetherError(iface);
2853 } else {
2854 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2855 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002856 }
2857
2858 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002859 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002860 public String[] getTetherableUsbRegexs() {
2861 enforceTetherAccessPermission();
2862 if (isTetheringSupported()) {
2863 return mTethering.getTetherableUsbRegexs();
2864 } else {
2865 return new String[0];
2866 }
2867 }
2868
Lorenzo Colitti18660282016-07-04 12:55:44 +09002869 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002870 public String[] getTetherableWifiRegexs() {
2871 enforceTetherAccessPermission();
2872 if (isTetheringSupported()) {
2873 return mTethering.getTetherableWifiRegexs();
2874 } else {
2875 return new String[0];
2876 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002877 }
2878
Lorenzo Colitti18660282016-07-04 12:55:44 +09002879 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002880 public String[] getTetherableBluetoothRegexs() {
2881 enforceTetherAccessPermission();
2882 if (isTetheringSupported()) {
2883 return mTethering.getTetherableBluetoothRegexs();
2884 } else {
2885 return new String[0];
2886 }
2887 }
2888
Lorenzo Colitti18660282016-07-04 12:55:44 +09002889 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002890 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002891 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002892 if (isTetheringSupported()) {
2893 return mTethering.setUsbTethering(enable);
2894 } else {
2895 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2896 }
2897 }
2898
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002899 // TODO - move iface listing, queries, etc to new module
2900 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002901 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002902 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002903 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002904 return mTethering.getTetherableIfaces();
2905 }
2906
Lorenzo Colitti18660282016-07-04 12:55:44 +09002907 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002908 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002909 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002910 return mTethering.getTetheredIfaces();
2911 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002912
Lorenzo Colitti18660282016-07-04 12:55:44 +09002913 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002914 public String[] getTetheringErroredIfaces() {
2915 enforceTetherAccessPermission();
2916 return mTethering.getErroredIfaces();
2917 }
2918
Lorenzo Colitti18660282016-07-04 12:55:44 +09002919 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002920 public String[] getTetheredDhcpRanges() {
2921 enforceConnectivityInternalPermission();
2922 return mTethering.getTetheredDhcpRanges();
2923 }
2924
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002925 // if ro.tether.denied = true we default to no tethering
2926 // gservices could set the secure setting to 1 though to enable it on a build where it
2927 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002928 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002929 public boolean isTetheringSupported() {
2930 enforceTetherAccessPermission();
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09002931 int defaultVal = (mSystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002932 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002933 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2934 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07002935
2936 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
2937 boolean adminUser = false;
2938 final long token = Binder.clearCallingIdentity();
2939 try {
2940 adminUser = mUserManager.isAdminUser();
2941 } finally {
2942 Binder.restoreCallingIdentity(token);
2943 }
2944
2945 return tetherEnabledInSettings && adminUser &&
Erik Klined781fba2017-01-23 13:01:58 +09002946 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002947 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002948
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002949 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09002950 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002951 ConnectivityManager.enforceTetherChangePermission(mContext);
2952 if (!isTetheringSupported()) {
2953 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2954 return;
2955 }
2956 mTethering.startTethering(type, receiver, showProvisioningUi);
2957 }
2958
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002959 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002960 public void stopTethering(int type) {
2961 ConnectivityManager.enforceTetherChangePermission(mContext);
2962 mTethering.stopTethering(type);
2963 }
2964
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002965 // Called when we lose the default network and have no replacement yet.
2966 // This will automatically be cleared after X seconds or a new default network
2967 // becomes CONNECTED, whichever happens first. The timer is started by the
2968 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09002969 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002970 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002971 if (mNetTransitionWakeLock.isHeld()) {
2972 return;
2973 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002974 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002975 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09002976 mWakelockLogs.log("ACQUIRE for " + forWhom);
2977 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
2978 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002979 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002980
Hugo Benichi4c31b342017-03-30 23:18:10 +09002981 // Called when we gain a new default network to release the network transition wakelock in a
2982 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
2983 // message is cancelled.
2984 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002985 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002986 if (!mNetTransitionWakeLock.isHeld()) {
2987 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002988 }
2989 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09002990 // Cancel self timeout on wakelock hold.
2991 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
2992 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
2993 mHandler.sendMessageDelayed(msg, 1000);
2994 }
2995
2996 // Called when either message of ensureNetworkTransitionWakelock or
2997 // scheduleReleaseNetworkTransitionWakelock is processed.
2998 private void handleReleaseNetworkTransitionWakelock(int eventId) {
2999 String event = eventName(eventId);
3000 synchronized (this) {
3001 if (!mNetTransitionWakeLock.isHeld()) {
3002 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3003 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3004 return;
3005 }
3006 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003007 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003008 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003009 }
3010
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003011 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003012 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003013 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003014 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003015 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003016 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003017 }
3018
Lorenzo Colitti18660282016-07-04 12:55:44 +09003019 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003020 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003021 enforceAccessPermission();
3022 enforceInternetPermission();
3023
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003024 // TODO: execute this logic on ConnectivityService handler.
3025 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003026 if (network == null) {
3027 nai = getDefaultNetwork();
3028 } else {
3029 nai = getNetworkAgentInfoForNetwork(network);
3030 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003031 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3032 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3033 return;
3034 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003035 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003036 if (hasConnectivity == nai.lastValidated) {
3037 return;
3038 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003039 final int uid = Binder.getCallingUid();
3040 if (DBG) {
3041 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3042 ") by " + uid);
3043 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003044 // Validating a network that has not yet connected could result in a call to
3045 // rematchNetworkAndRequests() which is not meant to work on such networks.
3046 if (!nai.everConnected) {
3047 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003048 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003049 LinkProperties lp = getLinkProperties(nai);
3050 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3051 return;
3052 }
3053 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003054 }
3055
Paul Jensencee9b512015-05-06 07:32:40 -04003056 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003057 // this information is already available as a world read/writable jvm property
3058 // so this API change wouldn't have a benifit. It also breaks the passing
3059 // of proxy info to all the JVMs.
3060 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003061 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003062 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003063 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3064 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003065 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003066 }
3067
Lorenzo Colitti18660282016-07-04 12:55:44 +09003068 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003069 public ProxyInfo getProxyForNetwork(Network network) {
3070 if (network == null) return getDefaultProxy();
3071 final ProxyInfo globalProxy = getGlobalProxy();
3072 if (globalProxy != null) return globalProxy;
3073 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3074 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3075 // caller may not have.
3076 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3077 if (nai == null) return null;
3078 synchronized (nai) {
3079 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3080 if (proxyInfo == null) return null;
3081 return new ProxyInfo(proxyInfo);
3082 }
3083 }
3084
Paul Jensene0bef712014-12-10 15:12:18 -05003085 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3086 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3087 // proxy is null then there is no proxy in place).
3088 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3089 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3090 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3091 proxy = null;
3092 }
3093 return proxy;
3094 }
3095
3096 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3097 // better for determining if a new proxy broadcast is necessary:
3098 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3099 // avoid unnecessary broadcasts.
3100 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3101 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3102 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3103 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3104 // all set.
3105 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3106 a = canonicalizeProxyInfo(a);
3107 b = canonicalizeProxyInfo(b);
3108 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3109 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3110 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3111 }
3112
Jason Monk207900c2014-04-25 15:00:09 -04003113 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003114 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003115
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003116 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003117 if (proxyProperties == mGlobalProxy) return;
3118 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3119 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3120
3121 String host = "";
3122 int port = 0;
3123 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003124 String pacFileUrl = "";
3125 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003126 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003127 if (!proxyProperties.isValid()) {
3128 if (DBG)
3129 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3130 return;
3131 }
Jason Monk207900c2014-04-25 15:00:09 -04003132 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003133 host = mGlobalProxy.getHost();
3134 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003135 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003136 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003137 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003138 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003139 } else {
3140 mGlobalProxy = null;
3141 }
3142 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003143 final long token = Binder.clearCallingIdentity();
3144 try {
3145 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3146 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3147 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3148 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003149 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003150 } finally {
3151 Binder.restoreCallingIdentity(token);
3152 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003153
Jason Monkcf0f97a2014-10-02 15:39:38 -04003154 if (mGlobalProxy == null) {
3155 proxyProperties = mDefaultProxy;
3156 }
3157 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003158 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003159 }
3160
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003161 private void loadGlobalProxy() {
3162 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003163 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3164 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3165 String exclList = Settings.Global.getString(res,
3166 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003167 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3168 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003169 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003170 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003171 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003172 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003173 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003174 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003175 if (!proxyProperties.isValid()) {
3176 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3177 return;
3178 }
3179
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003180 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003181 mGlobalProxy = proxyProperties;
3182 }
3183 }
3184 }
3185
Jason Monk207900c2014-04-25 15:00:09 -04003186 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003187 // this information is already available as a world read/writable jvm property
3188 // so this API change wouldn't have a benifit. It also breaks the passing
3189 // of proxy info to all the JVMs.
3190 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003191 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003192 return mGlobalProxy;
3193 }
3194 }
3195
Jason Monk207900c2014-04-25 15:00:09 -04003196 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003197 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003198 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003199 proxy = null;
3200 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003201 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003202 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003203 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003204 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003205 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3206 return;
3207 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003208
3209 // This call could be coming from the PacManager, containing the port of the local
3210 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3211 // global (to get the correct local port), and send a broadcast.
3212 // TODO: Switch PacManager to have its own message to send back rather than
3213 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003214 if ((mGlobalProxy != null) && (proxy != null)
3215 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003216 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3217 mGlobalProxy = proxy;
3218 sendProxyBroadcast(mGlobalProxy);
3219 return;
3220 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003221 mDefaultProxy = proxy;
3222
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003223 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003224 if (!mDefaultProxyDisabled) {
3225 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003226 }
3227 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003228 }
3229
Paul Jensene0bef712014-12-10 15:12:18 -05003230 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3231 // This method gets called when any network changes proxy, but the broadcast only ever contains
3232 // the default proxy (even if it hasn't changed).
3233 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3234 // world where an app might be bound to a non-default network.
3235 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3236 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3237 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3238
3239 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3240 sendProxyBroadcast(getDefaultProxy());
3241 }
3242 }
3243
Robert Greenwalt434203a2010-10-11 16:00:27 -07003244 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003245 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3246 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003247 if (!TextUtils.isEmpty(proxy)) {
3248 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003249 if (data.length == 0) {
3250 return;
3251 }
3252
Robert Greenwalt434203a2010-10-11 16:00:27 -07003253 String proxyHost = data[0];
3254 int proxyPort = 8080;
3255 if (data.length > 1) {
3256 try {
3257 proxyPort = Integer.parseInt(data[1]);
3258 } catch (NumberFormatException e) {
3259 return;
3260 }
3261 }
Jason Monk207900c2014-04-25 15:00:09 -04003262 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003263 setGlobalProxy(p);
3264 }
3265 }
3266
Jason Monk207900c2014-04-25 15:00:09 -04003267 private void sendProxyBroadcast(ProxyInfo proxy) {
3268 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003269 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003270 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003271 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003272 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3273 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003274 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003275 final long ident = Binder.clearCallingIdentity();
3276 try {
3277 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3278 } finally {
3279 Binder.restoreCallingIdentity(ident);
3280 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003281 }
3282
3283 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003284 final private HashMap<Uri, Integer> mUriEventMap;
3285 final private Context mContext;
3286 final private Handler mHandler;
3287
3288 SettingsObserver(Context context, Handler handler) {
3289 super(null);
3290 mUriEventMap = new HashMap<Uri, Integer>();
3291 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003292 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003293 }
3294
Erik Klineda4bfa82015-04-30 12:58:40 +09003295 void observe(Uri uri, int what) {
3296 mUriEventMap.put(uri, what);
3297 final ContentResolver resolver = mContext.getContentResolver();
3298 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003299 }
3300
3301 @Override
3302 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003303 Slog.wtf(TAG, "Should never be reached.");
3304 }
3305
3306 @Override
3307 public void onChange(boolean selfChange, Uri uri) {
3308 final Integer what = mUriEventMap.get(uri);
3309 if (what != null) {
3310 mHandler.obtainMessage(what.intValue()).sendToTarget();
3311 } else {
3312 loge("No matching event to send for URI=" + uri);
3313 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003314 }
3315 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003316
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003317 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003318 Slog.d(TAG, s);
3319 }
3320
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003321 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003322 Slog.e(TAG, s);
3323 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003324
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003325 private static void loge(String s, Throwable t) {
3326 Slog.e(TAG, s, t);
3327 }
3328
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003329 private static <T> T checkNotNull(T value, String message) {
3330 if (value == null) {
3331 throw new NullPointerException(message);
3332 }
3333 return value;
3334 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003335
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003336 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003337 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003338 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3339 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3340 *
3341 * @param oldPackage Package name of the application which currently controls VPN, which will
3342 * be replaced. If there is no such application, this should should either be
3343 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3344 * @param newPackage Package name of the application which should gain control of VPN, or
3345 * {@code null} to disable.
3346 * @param userId User for whom to prepare the new VPN.
3347 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003348 * @hide
3349 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003350 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003351 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3352 int userId) {
3353 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003354 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003355
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003356 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003357 Vpn vpn = mVpns.get(userId);
3358 if (vpn != null) {
3359 return vpn.prepare(oldPackage, newPackage);
3360 } else {
3361 return false;
3362 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003363 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003364 }
3365
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003366 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003367 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3368 * This method is used by system-privileged apps.
3369 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3370 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3371 *
3372 * @param packageName The package for which authorization state should change.
3373 * @param userId User for whom {@code packageName} is installed.
3374 * @param authorized {@code true} if this app should be able to start a VPN connection without
3375 * explicit user approval, {@code false} if not.
3376 *
Jeff Davidson05542602014-08-11 14:07:27 -07003377 * @hide
3378 */
3379 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003380 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3381 enforceCrossUserPermission(userId);
3382
Jeff Davidson05542602014-08-11 14:07:27 -07003383 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003384 Vpn vpn = mVpns.get(userId);
3385 if (vpn != null) {
3386 vpn.setPackageAuthorization(packageName, authorized);
3387 }
Jeff Davidson05542602014-08-11 14:07:27 -07003388 }
3389 }
3390
3391 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003392 * Configure a TUN interface and return its file descriptor. Parameters
3393 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003394 * and not available in ConnectivityManager. Permissions are checked in
3395 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003396 * @hide
3397 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003398 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003399 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003400 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003401 int user = UserHandle.getUserId(Binder.getCallingUid());
3402 synchronized(mVpns) {
3403 return mVpns.get(user).establish(config);
3404 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003405 }
3406
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003407 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003408 * Start legacy VPN, controlling native daemons as needed. Creates a
3409 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003410 */
3411 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003412 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003413 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003414 final LinkProperties egress = getActiveLinkProperties();
3415 if (egress == null) {
3416 throw new IllegalStateException("Missing active network connection");
3417 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003418 int user = UserHandle.getUserId(Binder.getCallingUid());
3419 synchronized(mVpns) {
3420 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3421 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003422 }
3423
3424 /**
3425 * Return the information of the ongoing legacy VPN. This method is used
3426 * by VpnSettings and not available in ConnectivityManager. Permissions
3427 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003428 */
3429 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003430 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3431 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003432
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003433 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003434 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003435 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003436 }
3437
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003438 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003439 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3440 * and not available in ConnectivityManager.
3441 */
3442 @Override
3443 public VpnInfo[] getAllVpnInfo() {
3444 enforceConnectivityInternalPermission();
3445 if (mLockdownEnabled) {
3446 return new VpnInfo[0];
3447 }
3448
3449 synchronized(mVpns) {
3450 List<VpnInfo> infoList = new ArrayList<>();
3451 for (int i = 0; i < mVpns.size(); i++) {
3452 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3453 if (info != null) {
3454 infoList.add(info);
3455 }
3456 }
3457 return infoList.toArray(new VpnInfo[infoList.size()]);
3458 }
3459 }
3460
3461 /**
3462 * @return VPN information for accounting, or null if we can't retrieve all required
3463 * information, e.g primary underlying iface.
3464 */
3465 @Nullable
3466 private VpnInfo createVpnInfo(Vpn vpn) {
3467 VpnInfo info = vpn.getVpnInfo();
3468 if (info == null) {
3469 return null;
3470 }
3471 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3472 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3473 // the underlyingNetworks list.
3474 if (underlyingNetworks == null) {
3475 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3476 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3477 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3478 }
3479 } else if (underlyingNetworks.length > 0) {
3480 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3481 if (linkProperties != null) {
3482 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3483 }
3484 }
3485 return info.primaryUnderlyingIface == null ? null : info;
3486 }
3487
3488 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003489 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3490 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003491 * Permissions are checked in Vpn class.
3492 * @hide
3493 */
3494 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003495 public VpnConfig getVpnConfig(int userId) {
3496 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003497 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003498 Vpn vpn = mVpns.get(userId);
3499 if (vpn != null) {
3500 return vpn.getVpnConfig();
3501 } else {
3502 return null;
3503 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003504 }
3505 }
3506
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003507 @Override
3508 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003509 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3510 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3511 return false;
3512 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003513
3514 // Tear down existing lockdown if profile was removed
3515 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3516 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003517 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3518 if (profileTag == null) {
3519 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3520 return false;
3521 }
3522 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003523 final VpnProfile profile = VpnProfile.decode(
3524 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003525 if (profile == null) {
3526 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3527 setLockdownTracker(null);
3528 return true;
3529 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003530 int user = UserHandle.getUserId(Binder.getCallingUid());
3531 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003532 Vpn vpn = mVpns.get(user);
3533 if (vpn == null) {
3534 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3535 return false;
3536 }
3537 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003538 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003539 } else {
3540 setLockdownTracker(null);
3541 }
3542
3543 return true;
3544 }
3545
3546 /**
3547 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3548 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3549 */
3550 private void setLockdownTracker(LockdownVpnTracker tracker) {
3551 // Shutdown any existing tracker
3552 final LockdownVpnTracker existing = mLockdownTracker;
3553 mLockdownTracker = null;
3554 if (existing != null) {
3555 existing.shutdown();
3556 }
3557
3558 try {
3559 if (tracker != null) {
3560 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003561 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003562 mLockdownTracker = tracker;
3563 mLockdownTracker.init();
3564 } else {
3565 mNetd.setFirewallEnabled(false);
3566 }
3567 } catch (RemoteException e) {
3568 // ignored; NMS lives inside system_server
3569 }
3570 }
3571
3572 private void throwIfLockdownEnabled() {
3573 if (mLockdownEnabled) {
3574 throw new IllegalStateException("Unavailable in lockdown mode");
3575 }
3576 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003577
Robin Lee244ce8e2016-01-05 18:03:46 +00003578 /**
Robin Lee17e61832016-05-09 13:46:28 +01003579 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3580 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003581 *
Robin Lee17e61832016-05-09 13:46:28 +01003582 * @return {@code true} if the service was started, the service was already connected, or there
3583 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003584 */
Robin Lee17e61832016-05-09 13:46:28 +01003585 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003586 synchronized (mVpns) {
3587 Vpn vpn = mVpns.get(userId);
3588 if (vpn == null) {
3589 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3590 // exists already.
3591 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3592 return false;
3593 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003594
Robin Lee812800c2016-05-13 15:38:08 +01003595 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003596 }
3597 }
3598
3599 @Override
Robin Leedc679712016-05-03 13:23:03 +01003600 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003601 enforceConnectivityInternalPermission();
3602 enforceCrossUserPermission(userId);
3603
3604 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3605 if (LockdownVpnTracker.isEnabled()) {
3606 return false;
3607 }
3608
Robin Lee244ce8e2016-01-05 18:03:46 +00003609 synchronized (mVpns) {
3610 Vpn vpn = mVpns.get(userId);
3611 if (vpn == null) {
3612 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3613 return false;
3614 }
Robin Lee17e61832016-05-09 13:46:28 +01003615 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003616 return false;
3617 }
Robin Lee17e61832016-05-09 13:46:28 +01003618 if (!startAlwaysOnVpn(userId)) {
3619 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003620 return false;
3621 }
3622 }
3623 return true;
3624 }
3625
3626 @Override
3627 public String getAlwaysOnVpnPackage(int userId) {
3628 enforceConnectivityInternalPermission();
3629 enforceCrossUserPermission(userId);
3630
3631 synchronized (mVpns) {
3632 Vpn vpn = mVpns.get(userId);
3633 if (vpn == null) {
3634 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3635 return null;
3636 }
3637 return vpn.getAlwaysOnPackage();
3638 }
3639 }
3640
Wink Savilleab9321d2013-06-29 21:10:57 -07003641 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003642 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003643 // TODO: Remove? Any reason to trigger a provisioning check?
3644 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003645 }
3646
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003647 /** Location to an updatable file listing carrier provisioning urls.
3648 * An example:
3649 *
3650 * <?xml version="1.0" encoding="utf-8"?>
3651 * <provisioningUrls>
3652 * <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 -07003653 * </provisioningUrls>
3654 */
3655 private static final String PROVISIONING_URL_PATH =
3656 "/data/misc/radio/provisioning_urls.xml";
3657 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003658
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003659 /** XML tag for root element. */
3660 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3661 /** XML tag for individual url */
3662 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003663 /** XML attribute for mcc */
3664 private static final String ATTR_MCC = "mcc";
3665 /** XML attribute for mnc */
3666 private static final String ATTR_MNC = "mnc";
3667
Paul Jensen434dde82015-06-11 09:43:30 -04003668 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003669 FileReader fileReader = null;
3670 XmlPullParser parser = null;
3671 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003672
3673 try {
3674 fileReader = new FileReader(mProvisioningUrlFile);
3675 parser = Xml.newPullParser();
3676 parser.setInput(fileReader);
3677 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3678
3679 while (true) {
3680 XmlUtils.nextElement(parser);
3681
3682 String element = parser.getName();
3683 if (element == null) break;
3684
Paul Jensen434dde82015-06-11 09:43:30 -04003685 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003686 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3687 try {
3688 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3689 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3690 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3691 parser.next();
3692 if (parser.getEventType() == XmlPullParser.TEXT) {
3693 return parser.getText();
3694 }
3695 }
3696 }
3697 } catch (NumberFormatException e) {
3698 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3699 }
3700 }
3701 }
3702 return null;
3703 } catch (FileNotFoundException e) {
3704 loge("Carrier Provisioning Urls file not found");
3705 } catch (XmlPullParserException e) {
3706 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3707 } catch (IOException e) {
3708 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3709 } finally {
3710 if (fileReader != null) {
3711 try {
3712 fileReader.close();
3713 } catch (IOException e) {}
3714 }
3715 }
3716 return null;
3717 }
3718
Wink Saville42d4f082013-07-20 20:31:59 -07003719 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003720 public String getMobileProvisioningUrl() {
3721 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003722 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003723 if (TextUtils.isEmpty(url)) {
3724 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003725 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003726 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003727 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003728 }
Wink Saville8cf35602013-07-10 23:00:07 -07003729 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003730 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003731 String phoneNumber = mTelephonyManager.getLine1Number();
3732 if (TextUtils.isEmpty(phoneNumber)) {
3733 phoneNumber = "0000000000";
3734 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003735 url = String.format(url,
3736 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3737 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003738 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003739 }
3740
Wink Savilleab9321d2013-06-29 21:10:57 -07003741 return url;
3742 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003743
Wink Saville948282b2013-08-29 08:55:16 -07003744 @Override
3745 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003746 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003747 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003748 final long ident = Binder.clearCallingIdentity();
3749 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003750 // Concatenate the range of types onto the range of NetIDs.
3751 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3752 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003753 } finally {
3754 Binder.restoreCallingIdentity(ident);
3755 }
Wink Saville948282b2013-08-29 08:55:16 -07003756 }
Wink Saville7788c612013-08-29 14:57:08 -07003757
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003758 @Override
3759 public void setAirplaneMode(boolean enable) {
3760 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003761 final long ident = Binder.clearCallingIdentity();
3762 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003763 final ContentResolver cr = mContext.getContentResolver();
3764 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3765 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3766 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003767 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003768 } finally {
3769 Binder.restoreCallingIdentity(ident);
3770 }
3771 }
3772
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003773 private void onUserStart(int userId) {
3774 synchronized(mVpns) {
3775 Vpn userVpn = mVpns.get(userId);
3776 if (userVpn != null) {
3777 loge("Starting user already has a VPN");
3778 return;
3779 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003780 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003781 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003782 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003783 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3784 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003785 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003786 }
3787
3788 private void onUserStop(int userId) {
3789 synchronized(mVpns) {
3790 Vpn userVpn = mVpns.get(userId);
3791 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003792 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003793 return;
3794 }
Robin Lee17e61832016-05-09 13:46:28 +01003795 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003796 mVpns.delete(userId);
3797 }
3798 }
3799
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003800 private void onUserAdded(int userId) {
3801 synchronized(mVpns) {
3802 final int vpnsSize = mVpns.size();
3803 for (int i = 0; i < vpnsSize; i++) {
3804 Vpn vpn = mVpns.valueAt(i);
3805 vpn.onUserAdded(userId);
3806 }
3807 }
3808 }
3809
3810 private void onUserRemoved(int userId) {
3811 synchronized(mVpns) {
3812 final int vpnsSize = mVpns.size();
3813 for (int i = 0; i < vpnsSize; i++) {
3814 Vpn vpn = mVpns.valueAt(i);
3815 vpn.onUserRemoved(userId);
3816 }
3817 }
3818 }
3819
Robin Lee89e7a692016-02-29 14:38:17 +00003820 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003821 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3822 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3823 updateLockdownVpn();
3824 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003825 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003826 }
3827 }
3828
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003829 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3830 @Override
3831 public void onReceive(Context context, Intent intent) {
3832 final String action = intent.getAction();
3833 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3834 if (userId == UserHandle.USER_NULL) return;
3835
Robin Lee323f29d2016-05-04 16:38:06 +01003836 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003837 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003838 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003839 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003840 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3841 onUserAdded(userId);
3842 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3843 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003844 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3845 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003846 }
3847 }
3848 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003849
Robin Lee95204e02017-01-27 11:59:22 +00003850 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3851 @Override
3852 public void onReceive(Context context, Intent intent) {
3853 // Try creating lockdown tracker, since user present usually means
3854 // unlocked keystore.
3855 updateLockdownVpn();
3856 mContext.unregisterReceiver(this);
3857 }
3858 };
3859
Robert Greenwalta67be032014-05-16 15:49:14 -07003860 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3861 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003862 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3863 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003864
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003865 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3866 // Map from UID to number of NetworkRequests that UID has filed.
3867 @GuardedBy("mUidToNetworkRequestCount")
3868 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3869
Robert Greenwalta67be032014-05-16 15:49:14 -07003870 private static class NetworkFactoryInfo {
3871 public final String name;
3872 public final Messenger messenger;
3873 public final AsyncChannel asyncChannel;
3874
3875 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3876 this.name = name;
3877 this.messenger = messenger;
3878 this.asyncChannel = asyncChannel;
3879 }
3880 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003881
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003882 private void ensureNetworkRequestHasType(NetworkRequest request) {
3883 if (request.type == NetworkRequest.Type.NONE) {
3884 throw new IllegalArgumentException(
3885 "All NetworkRequests in ConnectivityService must have a type");
3886 }
3887 }
3888
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003889 /**
3890 * Tracks info about the requester.
3891 * Also used to notice when the calling process dies so we can self-expire
3892 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003893 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003894 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003895 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003896 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003897 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003898 final int mPid;
3899 final int mUid;
3900 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003901
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003902 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003903 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003904 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003905 mPendingIntent = pi;
3906 messenger = null;
3907 mBinder = null;
3908 mPid = getCallingPid();
3909 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003910 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003911 }
3912
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003913 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003914 super();
3915 messenger = m;
3916 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003917 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003918 mBinder = binder;
3919 mPid = getCallingPid();
3920 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003921 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003922 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003923
3924 try {
3925 mBinder.linkToDeath(this, 0);
3926 } catch (RemoteException e) {
3927 binderDied();
3928 }
3929 }
3930
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003931 private void enforceRequestCountLimit() {
3932 synchronized (mUidToNetworkRequestCount) {
3933 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3934 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3935 throw new IllegalArgumentException("Too many NetworkRequests filed");
3936 }
3937 mUidToNetworkRequestCount.put(mUid, networkRequests);
3938 }
3939 }
3940
Robert Greenwalt9258c642014-03-26 16:47:06 -07003941 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003942 if (mBinder != null) {
3943 mBinder.unlinkToDeath(this, 0);
3944 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003945 }
3946
3947 public void binderDied() {
3948 log("ConnectivityService NetworkRequestInfo binderDied(" +
3949 request + ", " + mBinder + ")");
3950 releaseNetworkRequest(request);
3951 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003952
3953 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003954 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003955 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003956 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003957 }
3958
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003959 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3960 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3961 if (badCapability != null) {
3962 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003963 }
3964 }
3965
Erik Kline9d598e12015-07-13 16:37:51 +09003966 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003967 final SortedSet<Integer> thresholds = new TreeSet();
3968 synchronized (nai) {
3969 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3970 if (nri.request.networkCapabilities.hasSignalStrength() &&
3971 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3972 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3973 }
3974 }
3975 }
Erik Kline9d598e12015-07-13 16:37:51 +09003976 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003977 }
3978
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003979 private void updateSignalStrengthThresholds(
3980 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3981 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003982 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003983 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3984
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09003985 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003986 String detail;
3987 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3988 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3989 } else {
3990 detail = reason;
3991 }
3992 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3993 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3994 }
3995
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003996 nai.asyncChannel.sendMessage(
3997 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003998 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003999 }
4000
Robert Greenwalt9258c642014-03-26 16:47:06 -07004001 @Override
4002 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004003 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004004 final NetworkRequest.Type type = (networkCapabilities == null)
4005 ? NetworkRequest.Type.TRACK_DEFAULT
4006 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004007 // If the requested networkCapabilities is null, take them instead from
4008 // the default network request. This allows callers to keep track of
4009 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004010 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004011 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4012 enforceAccessPermission();
4013 } else {
4014 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4015 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004016 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4017 // of the app when the request is filed, but we never change the request if the app
4018 // changes network state. http://b/29964605
4019 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004020 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004021 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004022
Etan Cohenba07c8c2017-02-05 10:42:27 -08004023 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004024 throw new IllegalArgumentException("Bad timeout specified");
4025 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004026
Etan Cohena7434272017-04-03 12:17:51 -07004027 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4028 networkCapabilities.getNetworkSpecifier());
Etan Cohenddb9ef02015-11-18 10:56:15 -08004029
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004030 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004031 nextNetworkRequestId(), type);
4032 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004033 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004034
4035 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004036 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004037 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004038 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004039 }
4040 return networkRequest;
4041 }
4042
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004043 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004044 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004045 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004046 } else {
4047 enforceChangePermission();
4048 }
4049 }
4050
fenglub15e72b2015-03-20 11:29:56 -07004051 @Override
fengludb571472015-04-21 17:12:05 -07004052 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004053 enforceAccessPermission();
4054 NetworkAgentInfo nai = null;
4055 if (network == null) {
4056 return false;
4057 }
4058 synchronized (mNetworkForNetId) {
4059 nai = mNetworkForNetId.get(network.netId);
4060 }
4061 if (nai != null) {
4062 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4063 return true;
4064 }
4065 return false;
4066 }
4067
Felipe Lemeee27cab2016-06-20 16:36:29 -07004068 private boolean isSystem(int uid) {
4069 return uid < Process.FIRST_APPLICATION_UID;
4070 }
fenglub15e72b2015-03-20 11:29:56 -07004071
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004072 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004073 final int uid = Binder.getCallingUid();
4074 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004075 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004076 return;
4077 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004078 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4079 // Policy already enforced.
4080 return;
4081 }
4082 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4083 // If UID is restricted, don't allow them to bring up metered APNs.
4084 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004085 }
4086 }
4087
Robert Greenwalt9258c642014-03-26 16:47:06 -07004088 @Override
4089 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4090 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004091 checkNotNull(operation, "PendingIntent cannot be null.");
4092 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4093 enforceNetworkRequestPermissions(networkCapabilities);
4094 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004095 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004096
Etan Cohena7434272017-04-03 12:17:51 -07004097 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4098 networkCapabilities.getNetworkSpecifier());
4099
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004100 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004101 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4102 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004103 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004104 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4105 nri));
4106 return networkRequest;
4107 }
4108
Jeremy Joslin79294842014-12-03 17:15:28 -08004109 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4110 mHandler.sendMessageDelayed(
4111 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4112 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4113 }
4114
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004115 @Override
4116 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004117 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004118 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4119 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004120 }
4121
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004122 // In order to implement the compatibility measure for pre-M apps that call
4123 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4124 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4125 // This ensures it has permission to do so.
4126 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4127 if (nc == null) {
4128 return false;
4129 }
4130 int[] transportTypes = nc.getTransportTypes();
4131 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4132 return false;
4133 }
4134 try {
4135 mContext.enforceCallingOrSelfPermission(
4136 android.Manifest.permission.ACCESS_WIFI_STATE,
4137 "ConnectivityService");
4138 } catch (SecurityException e) {
4139 return false;
4140 }
4141 return true;
4142 }
4143
Robert Greenwalt9258c642014-03-26 16:47:06 -07004144 @Override
4145 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4146 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004147 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4148 enforceAccessPermission();
4149 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004150
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004151 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4152 if (!ConnectivityManager.checkChangePermission(mContext)) {
4153 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4154 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4155 // onLost and onAvailable callbacks when networks move in and out of the background.
4156 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4157 // can't request networks.
4158 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4159 }
4160
Etan Cohena7434272017-04-03 12:17:51 -07004161 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4162 networkCapabilities.getNetworkSpecifier());
4163
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004164 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004165 NetworkRequest.Type.LISTEN);
4166 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004167 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004168
4169 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4170 return networkRequest;
4171 }
4172
4173 @Override
4174 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4175 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004176 checkNotNull(operation, "PendingIntent cannot be null.");
4177 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4178 enforceAccessPermission();
4179 }
4180
Etan Cohena7434272017-04-03 12:17:51 -07004181 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(
4182 networkCapabilities.getNetworkSpecifier());
4183
Erik Kline7523eb32015-07-09 18:24:03 +09004184 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004185 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4186 NetworkRequest.Type.LISTEN);
4187 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004188 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004189
4190 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004191 }
4192
Erik Klineacdd6392016-07-07 16:50:58 +09004193 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004195 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004196 mHandler.sendMessage(mHandler.obtainMessage(
4197 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004198 }
4199
4200 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004201 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004202 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004203 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4204 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004205 }
4206
Robert Greenwalta67be032014-05-16 15:49:14 -07004207 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004208 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004209 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4210 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4211 }
4212
4213 @Override
4214 public void unregisterNetworkFactory(Messenger messenger) {
4215 enforceConnectivityInternalPermission();
4216 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4217 }
4218
4219 private void handleUnregisterNetworkFactory(Messenger messenger) {
4220 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4221 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004222 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004223 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004224 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004225 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004226 }
4227
Robert Greenwalt7b816022014-04-18 15:25:25 -07004228 /**
4229 * NetworkAgentInfo supporting a request by requestId.
4230 * These have already been vetted (their Capabilities satisfy the request)
4231 * and the are the highest scored network available.
4232 * the are keyed off the Requests requestId.
4233 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004234 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004235 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4236 new SparseArray<NetworkAgentInfo>();
4237
Paul Jensen31a94f42015-02-13 14:18:39 -05004238 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4239 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004240 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4241 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004242 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4243 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4244 // there may not be a strict 1:1 correlation between the two.
4245 @GuardedBy("mNetworkForNetId")
4246 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004247
Robert Greenwalt7b816022014-04-18 15:25:25 -07004248 // NetworkAgentInfo keyed off its connecting messenger
4249 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004250 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004251 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4252 new HashMap<Messenger, NetworkAgentInfo>();
4253
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004254 @GuardedBy("mBlockedAppUids")
4255 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4256
Paul Jensen2c311d62014-11-17 12:34:51 -05004257 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004258 private final NetworkRequest mDefaultRequest;
4259
Erik Klineda4bfa82015-04-30 12:58:40 +09004260 // Request used to optionally keep mobile data active even when higher
4261 // priority networks like Wi-Fi are active.
4262 private final NetworkRequest mDefaultMobileDataRequest;
4263
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004264 private NetworkAgentInfo getDefaultNetwork() {
4265 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4266 }
4267
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004268 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004269 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004270 }
4271
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004272 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4273 return nri.request.requestId == mDefaultRequest.requestId;
4274 }
4275
Paul Jensen31a94f42015-02-13 14:18:39 -05004276 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004277 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004278 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004279 enforceConnectivityInternalPermission();
4280
Paul Jensen2c311d62014-11-17 12:34:51 -05004281 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4282 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004283 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004284 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4285 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004286 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004287 synchronized (this) {
4288 nai.networkMonitor.systemReady = mSystemReady;
4289 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004290 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4291 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004292 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004293 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004294 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004295 }
4296
4297 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4298 if (VDBG) log("Got NetworkAgent Messenger");
4299 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004300 synchronized (mNetworkForNetId) {
4301 mNetworkForNetId.put(na.network.netId, na);
4302 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004303 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4304 NetworkInfo networkInfo = na.networkInfo;
4305 na.networkInfo = null;
4306 updateNetworkInfo(na, networkInfo);
4307 }
4308
4309 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4310 LinkProperties newLp = networkAgent.linkProperties;
4311 int netId = networkAgent.network.netId;
4312
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004313 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4314 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004315 if (networkAgent.clatd != null) {
4316 networkAgent.clatd.fixupLinkProperties(oldLp);
4317 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004318
Paul Jensen992f2522014-04-28 10:33:11 -04004319 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004320 updateMtu(newLp, oldLp);
4321 // TODO - figure out what to do for clat
4322// for (LinkProperties lp : newLp.getStackedLinks()) {
4323// updateMtu(lp, null);
4324// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004325 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004326
Erik Kline94887872016-04-05 13:30:49 +09004327 updateRoutes(newLp, oldLp, netId);
4328 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004329
Paul Jensen3b759822014-05-13 11:44:01 -04004330 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004331 if (isDefaultNetwork(networkAgent)) {
4332 handleApplyDefaultProxy(newLp.getHttpProxy());
4333 } else {
4334 updateProxy(newLp, oldLp, networkAgent);
4335 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004336 // TODO - move this check to cover the whole function
4337 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004338 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004339 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4340 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004341
4342 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004343 }
4344
Lorenzo Colitti95439462014-10-09 13:44:48 +09004345 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4346 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4347 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004348
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004349 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004350 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4351 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004352 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004353 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004354 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004355 }
Paul Jensen992f2522014-04-28 10:33:11 -04004356
4357 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4358 CompareResult<String> interfaceDiff = new CompareResult<String>();
4359 if (oldLp != null) {
4360 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4361 } else if (newLp != null) {
4362 interfaceDiff.added = newLp.getAllInterfaceNames();
4363 }
4364 for (String iface : interfaceDiff.added) {
4365 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004366 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004367 mNetd.addInterfaceToNetwork(iface, netId);
4368 } catch (Exception e) {
4369 loge("Exception adding interface: " + e);
4370 }
4371 }
4372 for (String iface : interfaceDiff.removed) {
4373 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004374 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004375 mNetd.removeInterfaceFromNetwork(iface, netId);
4376 } catch (Exception e) {
4377 loge("Exception removing interface: " + e);
4378 }
4379 }
4380 }
4381
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004382 /**
4383 * Have netd update routes from oldLp to newLp.
4384 * @return true if routes changed between oldLp and newLp
4385 */
4386 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004387 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4388 if (oldLp != null) {
4389 routeDiff = oldLp.compareAllRoutes(newLp);
4390 } else if (newLp != null) {
4391 routeDiff.added = newLp.getAllRoutes();
4392 }
4393
4394 // add routes before removing old in case it helps with continuous connectivity
4395
4396 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4397 for (RouteInfo route : routeDiff.added) {
4398 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004399 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004400 try {
4401 mNetd.addRoute(netId, route);
4402 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004403 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4404 loge("Exception in addRoute for non-gateway: " + e);
4405 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004406 }
4407 }
4408 for (RouteInfo route : routeDiff.added) {
4409 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004410 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004411 try {
4412 mNetd.addRoute(netId, route);
4413 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004414 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4415 loge("Exception in addRoute for gateway: " + e);
4416 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004417 }
4418 }
4419
4420 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004421 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004422 try {
4423 mNetd.removeRoute(netId, route);
4424 } catch (Exception e) {
4425 loge("Exception in removeRoute: " + e);
4426 }
4427 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004428 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004429 }
Erik Kline41368502015-06-17 13:19:54 +09004430
Erik Kline94887872016-04-05 13:30:49 +09004431 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4432 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4433 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004434 }
Erik Kline94887872016-04-05 13:30:49 +09004435
4436 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004437 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004438 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004439 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004440 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4441 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004442 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004443 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004444 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4445 if (defaultNai != null && defaultNai.network.netId == netId) {
4446 setDefaultDnsSystemProperties(dnses);
4447 }
Erik Kline94887872016-04-05 13:30:49 +09004448 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004449 }
4450
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004451 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4452 int last = 0;
4453 for (InetAddress dns : dnses) {
4454 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004455 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004456 }
4457 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004458 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004459 }
4460 mNumDnsEntries = last;
4461 }
4462
Erik Kline4edba012017-04-07 15:29:29 +09004463 private void setNetDnsProperty(int which, String value) {
4464 final String key = "net.dns" + which;
4465 // Log and forget errors setting unsupported properties.
4466 try {
4467 mSystemProperties.set(key, value);
4468 } catch (Exception e) {
4469 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4470 }
4471 }
4472
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004473 private String getNetworkPermission(NetworkCapabilities nc) {
4474 // TODO: make these permission strings AIDL constants instead.
4475 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4476 return NetworkManagementService.PERMISSION_SYSTEM;
4477 }
4478 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4479 return NetworkManagementService.PERMISSION_NETWORK;
4480 }
4481 return null;
4482 }
4483
Paul Jensen3d194ea2015-06-16 14:27:36 -04004484 /**
4485 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4486 * augmented with any stateful capabilities implied from {@code networkAgent}
4487 * (e.g., validated status and captive portal status).
4488 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004489 * @param oldScore score of the network before any of the changes that prompted us
4490 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004491 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004492 * @param networkCapabilities the new network capabilities.
4493 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004494 private void updateCapabilities(
4495 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004496 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4497 networkCapabilities)) {
4498 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4499 + nai.networkCapabilities + " -> " + networkCapabilities);
4500 }
4501
Paul Jensen3d194ea2015-06-16 14:27:36 -04004502 // Don't modify caller's NetworkCapabilities.
4503 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004504 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004505 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4506 } else {
4507 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4508 }
Paul Jensene0988542015-06-25 15:30:08 -04004509 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004510 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4511 } else {
4512 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4513 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004514 if (nai.isBackgroundNetwork()) {
4515 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4516 } else {
4517 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4518 }
4519
4520 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4521
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004522 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4523 final String newPermission = getNetworkPermission(networkCapabilities);
4524 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004525 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004526 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004527 } catch (RemoteException e) {
4528 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004529 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004530 }
4531
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004532 final NetworkCapabilities prevNc = nai.networkCapabilities;
4533 synchronized (nai) {
4534 nai.networkCapabilities = networkCapabilities;
4535 }
4536 if (nai.getCurrentScore() == oldScore &&
4537 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4538 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4539 // the change we're processing can't affect any requests, it can only affect the listens
4540 // on this network. We might have been called by rematchNetworkAndRequests when a
4541 // network changed foreground state.
4542 processListenRequests(nai, true);
4543 } else {
4544 // If the requestable capabilities have changed or the score changed, we can't have been
4545 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004546 rematchAllNetworksAndRequests(nai, oldScore);
4547 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004548 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004549 }
4550
Paul Jensenc8b9a742014-09-30 15:37:41 -04004551 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004552 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4553 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004554 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004555 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004556 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4557 }
4558 }
4559
Robert Greenwalt7b816022014-04-18 15:25:25 -07004560 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4561 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004562 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004563 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4564 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004565 }
4566 }
4567
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004568 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4569 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004570 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004571 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004572 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4573 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004574 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004575 sendIntent(nri.mPendingIntent, intent);
4576 }
4577 // else not handled
4578 }
4579
4580 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4581 mPendingIntentWakeLock.acquire();
4582 try {
4583 if (DBG) log("Sending " + pendingIntent);
4584 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4585 } catch (PendingIntent.CanceledException e) {
4586 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4587 mPendingIntentWakeLock.release();
4588 releasePendingNetworkRequest(pendingIntent);
4589 }
4590 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4591 }
4592
4593 @Override
4594 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4595 String resultData, Bundle resultExtras) {
4596 if (DBG) log("Finished sending " + pendingIntent);
4597 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004598 // Release with a delay so the receiving client has an opportunity to put in its
4599 // own request.
4600 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004601 }
4602
Robert Greenwalt9258c642014-03-26 16:47:06 -07004603 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004604 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004605 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004606 Bundle bundle = new Bundle();
4607 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4608 new NetworkRequest(nri.request));
4609 Message msg = Message.obtain();
4610 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4611 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4612 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4613 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004614 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004615 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004616 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004617 break;
4618 }
4619 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4620 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4621 new NetworkCapabilities(networkAgent.networkCapabilities));
4622 break;
4623 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004624 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004625 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4626 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004627 break;
4628 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004629 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004630 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004631 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004632 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004633 if (VDBG) {
4634 log("sending notification " + notifyTypeToName(notificationType) +
4635 " for " + nri.request);
4636 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004637 nri.messenger.send(msg);
4638 } catch (RemoteException e) {
4639 // may occur naturally in the race of binder death.
4640 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4641 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004642 }
4643
Paul Jensenc8b9a742014-09-30 15:37:41 -04004644 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004645 if (nai.numRequestNetworkRequests() != 0) {
4646 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4647 NetworkRequest nr = nai.requestAt(i);
4648 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004649 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004650 loge("Dead network still had at least " + nr);
4651 break;
4652 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004653 }
4654 nai.asyncChannel.disconnect();
4655 }
4656
Robert Greenwalt7b816022014-04-18 15:25:25 -07004657 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4658 if (oldNetwork == null) {
4659 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4660 return;
4661 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004662 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004663
4664 // If we get here it means that the last linger timeout for this network expired. So there
4665 // must be no other active linger timers, and we must stop lingering.
4666 oldNetwork.clearLingerState();
4667
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004668 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004669 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004670 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004671 } else {
4672 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004673 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4674 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004675 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004676 }
4677
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004678 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004679 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004680 setupDataActivityTracking(newNetwork);
4681 try {
4682 mNetd.setDefaultNetId(newNetwork.network.netId);
4683 } catch (Exception e) {
4684 loge("Exception setting default network :" + e);
4685 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004686 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004687 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004688 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004689 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004690 }
4691
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004692 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004693 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4694 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4695 NetworkRequest nr = nri.request;
4696 if (!nr.isListen()) continue;
4697 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4698 nai.removeRequest(nri.request.requestId);
4699 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4700 }
4701 }
4702
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004703 if (capabilitiesChanged) {
4704 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4705 }
4706
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004707 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4708 NetworkRequest nr = nri.request;
4709 if (!nr.isListen()) continue;
4710 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4711 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004712 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004713 }
4714 }
4715 }
4716
Paul Jensen2161a8e2014-09-11 11:00:39 -04004717 // Handles a network appearing or improving its score.
4718 //
4719 // - Evaluates all current NetworkRequests that can be
4720 // satisfied by newNetwork, and reassigns to newNetwork
4721 // any such requests for which newNetwork is the best.
4722 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004723 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004724 // needed. A network is needed if it is the best network for
4725 // one or more NetworkRequests, or if it is a VPN.
4726 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004727 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004728 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004729 //
4730 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4731 // networks that have no chance (i.e. even if validated)
4732 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004733 //
4734 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4735 // it does not remove NetworkRequests that other Networks could better satisfy.
4736 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4737 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4738 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004739 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004740 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004741 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4742 // performed to tear down unvalidated networks that have no chance (i.e. even if
4743 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004744 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004745 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004746 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004747 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004748 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004749 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004750
4751 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4752 final int score = newNetwork.getCurrentScore();
4753
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004754 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004755
Paul Jensen2161a8e2014-09-11 11:00:39 -04004756 // Find and migrate to this Network any NetworkRequests for
4757 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004758 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004759 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004760 NetworkCapabilities nc = newNetwork.networkCapabilities;
4761 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004762 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004763 // Process requests in the first pass and listens in the second pass. This allows us to
4764 // change a network's capabilities depending on which requests it has. This is only
4765 // correct if the change in capabilities doesn't affect whether the network satisfies
4766 // requests or not, and doesn't affect the network's score.
4767 if (nri.request.isListen()) continue;
4768
Paul Jensencf4c2c62015-07-01 14:16:32 -04004769 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4770 final boolean satisfies = newNetwork.satisfies(nri.request);
4771 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004772 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004773 log("Network " + newNetwork.name() + " was already satisfying" +
4774 " request " + nri.request.requestId + ". No change.");
4775 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004776 keep = true;
4777 continue;
4778 }
4779
4780 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004781 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004782 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004783 // next check if it's better than any current network we're using for
4784 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004785 if (VDBG) {
4786 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004787 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004788 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004789 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004790 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004791 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004792 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004793 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004794 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004795 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004796 affectedNetworks.add(currentNetwork);
4797 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004798 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004799 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004800 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004801 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004802 if (!newNetwork.addRequest(nri.request)) {
4803 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4804 }
4805 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004806 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004807 // Tell NetworkFactories about the new score, so they can stop
4808 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004809 // TODO - this could get expensive if we have alot of requests for this
4810 // network. Think about if there is a way to reduce this. Push
4811 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004812 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004813 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004814 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004815 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004816 if (currentNetwork != null) {
4817 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4818 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004819 }
4820 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004821 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004822 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4823 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004824 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004825 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4826 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4827 // This means this code doesn't have to handle the case where "currentNetwork" no
4828 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4829 if (DBG) {
4830 log("Network " + newNetwork.name() + " stopped satisfying" +
4831 " request " + nri.request.requestId);
4832 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004833 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004834 if (currentNetwork == newNetwork) {
4835 mNetworkForRequestId.remove(nri.request.requestId);
4836 sendUpdatedScoreToFactories(nri.request, 0);
4837 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004838 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4839 newNetwork.name() +
4840 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004841 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004842 // TODO: Technically, sending CALLBACK_LOST here is
4843 // incorrect if there is a replacement network currently
4844 // connected that can satisfy nri, which is a request
4845 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004846 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4847 // so this code is only incorrect for a network that loses
4848 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004849 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004850 }
4851 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004852 if (isNewDefault) {
4853 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004854 makeDefault(newNetwork);
4855 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4856 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004857 // Have a new default network, release the transition wakelock in
4858 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004859 }
4860
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004861 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4862 Slog.wtf(TAG, String.format(
4863 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4864 nc, newNetwork.networkCapabilities));
4865 }
4866 if (newNetwork.getCurrentScore() != score) {
4867 Slog.wtf(TAG, String.format(
4868 "BUG: %s changed score during rematch: %d -> %d",
4869 score, newNetwork.getCurrentScore()));
4870 }
4871
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004872 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004873 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4874 // If the network went from background to foreground or vice versa, we need to update
4875 // its foreground state. It is safe to do this after rematching the requests because
4876 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4877 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004878 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004879 } else {
4880 processListenRequests(newNetwork, false);
4881 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004882
Paul Jensencf4c2c62015-07-01 14:16:32 -04004883 // do this after the default net is switched, but
4884 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09004885 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004886
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004887 // Linger any networks that are no longer needed. This should be done after sending the
4888 // available callback for newNetwork.
4889 for (NetworkAgentInfo nai : affectedNetworks) {
4890 updateLingerState(nai, now);
4891 }
4892 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4893 // does not need to be done in any particular order.
4894 updateLingerState(newNetwork, now);
4895
Paul Jensencf4c2c62015-07-01 14:16:32 -04004896 if (isNewDefault) {
4897 // Maintain the illusion: since the legacy API only
4898 // understands one network at a time, we must pretend
4899 // that the current default network disconnected before
4900 // the new one connected.
4901 if (oldDefaultNetwork != null) {
4902 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4903 oldDefaultNetwork, true);
4904 }
4905 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4906 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4907 notifyLockdownVpn(newNetwork);
4908 }
4909
Robert Greenwalt7b816022014-04-18 15:25:25 -07004910 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004911 // Notify battery stats service about this network, both the normal
4912 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004913 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004914 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004915 final IBatteryStats bs = BatteryStatsService.getService();
4916 final int type = newNetwork.networkInfo.getType();
4917
4918 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4919 bs.noteNetworkInterfaceType(baseIface, type);
4920 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4921 final String stackedIface = stacked.getInterfaceName();
4922 bs.noteNetworkInterfaceType(stackedIface, type);
4923 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4924 }
4925 } catch (RemoteException ignored) {
4926 }
4927
Robert Greenwalt152ed372014-12-17 17:19:53 -08004928 // This has to happen after the notifyNetworkCallbacks as that tickles each
4929 // ConnectivityManager instance so that legacy requests correctly bind dns
4930 // requests to this network. The legacy users are listening for this bcast
4931 // and will generally do a dns request so they can ensureRouteToHost and if
4932 // they do that before the callbacks happen they'll use the default network.
4933 //
4934 // TODO: Is there still a race here? We send the broadcast
4935 // after sending the callback, but if the app can receive the
4936 // broadcast before the callback, it might still break.
4937 //
4938 // This *does* introduce a race where if the user uses the new api
4939 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4940 // they may get old info. Reverse this after the old startUsing api is removed.
4941 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004942 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4943 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004944 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004945 // legacy type tracker filters out repeat adds
4946 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4947 }
4948 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004949
4950 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4951 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4952 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4953 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4954 if (newNetwork.isVPN()) {
4955 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4956 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004957 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004958 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4959 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004960 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004961 if (nai.getLingerExpiry() > 0) {
4962 // This network has active linger timers and no requests, but is not
4963 // lingering. Linger it.
4964 //
4965 // One way (the only way?) this can happen if this network is unvalidated
4966 // and became unneeded due to another network improving its score to the
4967 // point where this network will no longer be able to satisfy any requests
4968 // even if it validates.
4969 updateLingerState(nai, now);
4970 } else {
4971 if (DBG) log("Reaping " + nai.name());
4972 teardownUnneededNetwork(nai);
4973 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004974 }
4975 }
4976 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004977 }
4978
Paul Jensen1c7ba022015-06-16 14:27:36 -04004979 /**
4980 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4981 * being disconnected.
4982 * @param changed If only one Network's score or capabilities have been modified since the last
4983 * time this function was called, pass this Network in this argument, otherwise pass
4984 * null.
4985 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4986 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4987 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4988 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4989 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004990 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004991 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004992 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4993 // to avoid the slowness. It is not simply enough to process just "changed", for
4994 // example in the case where "changed"'s score decreases and another network should begin
4995 // satifying a NetworkRequest that "changed" currently satisfies.
4996
4997 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4998 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4999 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005000 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005001 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005002 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005003 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005004 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5005 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5006 // Rematch higher scoring networks first to prevent requests first matching a lower
5007 // scoring network and then a higher scoring network, which could produce multiple
5008 // callbacks and inadvertently unlinger networks.
5009 Arrays.sort(nais);
5010 for (NetworkAgentInfo nai : nais) {
5011 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005012 // Only reap the last time through the loop. Reaping before all rematching
5013 // is complete could incorrectly teardown a network that hasn't yet been
5014 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005015 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005016 : ReapUnvalidatedNetworks.REAP,
5017 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005018 }
5019 }
5020 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005021
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005022 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005023 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005024 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005025 // For now only update icons for default connection.
5026 // TODO: Update WiFi and cellular icons separately. b/17237507
5027 if (!isDefaultNetwork(nai)) return;
5028
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005029 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005030 // Don't repeat publish.
5031 if (newInetCondition == mDefaultInetConditionPublished) return;
5032
5033 mDefaultInetConditionPublished = newInetCondition;
5034 sendInetConditionBroadcast(nai.networkInfo);
5035 }
5036
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005037 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5038 if (mLockdownTracker != null) {
5039 if (nai != null && nai.isVPN()) {
5040 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5041 } else {
5042 mLockdownTracker.onNetworkInfoChanged();
5043 }
5044 }
5045 }
5046
Robert Greenwalt7b816022014-04-18 15:25:25 -07005047 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005048 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005049 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005050 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005051 synchronized (networkAgent) {
5052 oldInfo = networkAgent.networkInfo;
5053 networkAgent.networkInfo = newInfo;
5054 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005055 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005056
5057 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005058 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5059 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5060 notifyIfacesChangedForNetworkStats();
5061 } else if (VDBG) log("ignoring duplicate network state non-change");
5062 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005063 return;
5064 }
5065 if (DBG) {
5066 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5067 (oldInfo == null ? "null" : oldInfo.getState()) +
5068 " to " + state);
5069 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005070
Robin Lee585e2482016-05-01 23:00:00 +01005071 if (!networkAgent.created
5072 && (state == NetworkInfo.State.CONNECTED
5073 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005074
5075 // A network that has just connected has zero requests and is thus a foreground network.
5076 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5077
Robert Greenwalt7b816022014-04-18 15:25:25 -07005078 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005079 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005080 if (networkAgent.isVPN()) {
5081 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005082 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5083 (networkAgent.networkMisc == null ||
5084 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005085 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005086 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005087 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005088 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005089 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005090 loge("Error creating network " + networkAgent.network.netId + ": "
5091 + e.getMessage());
5092 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005093 }
Paul Jenseneec75412014-08-04 12:21:19 -04005094 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005095 }
5096
5097 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5098 networkAgent.everConnected = true;
5099
Robert Greenwalt7b816022014-04-18 15:25:25 -07005100 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005101 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005102
Paul Jensenca8f16a2014-05-09 12:47:55 -04005103 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005104 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005105
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005106 if (networkAgent.isVPN()) {
5107 // Temporarily disable the default proxy (not global).
5108 synchronized (mProxyLock) {
5109 if (!mDefaultProxyDisabled) {
5110 mDefaultProxyDisabled = true;
5111 if (mGlobalProxy == null && mDefaultProxy != null) {
5112 sendProxyBroadcast(null);
5113 }
5114 }
5115 }
5116 // TODO: support proxy per network.
5117 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005118
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005119 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5120 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5121 // capabilities, so it only needs to be done once on initial connect, not every time the
5122 // network's capabilities change. Note that we do this before rematching the network,
5123 // so we could decide to tear it down immediately afterwards. That's fine though - on
5124 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5125 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005126 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005127
Paul Jensen2161a8e2014-09-11 11:00:39 -04005128 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005129 final long now = SystemClock.elapsedRealtime();
5130 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005131
5132 // This has to happen after matching the requests, because callbacks are just requests.
5133 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005134 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005135 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005136 if (networkAgent.isVPN()) {
5137 synchronized (mProxyLock) {
5138 if (mDefaultProxyDisabled) {
5139 mDefaultProxyDisabled = false;
5140 if (mGlobalProxy == null && mDefaultProxy != null) {
5141 sendProxyBroadcast(mDefaultProxy);
5142 }
5143 }
5144 }
5145 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005146 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5147 state == NetworkInfo.State.SUSPENDED) {
5148 // going into or coming out of SUSPEND: rescore and notify
5149 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005150 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005151 }
5152 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5153 ConnectivityManager.CALLBACK_SUSPENDED :
5154 ConnectivityManager.CALLBACK_RESUMED));
5155 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005156 }
5157 }
5158
Robert Greenwaltac96c522014-06-03 16:43:57 -07005159 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005160 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005161 if (score < 0) {
5162 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5163 "). Bumping score to min of 0");
5164 score = 0;
5165 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005166
Paul Jensen2161a8e2014-09-11 11:00:39 -04005167 final int oldScore = nai.getCurrentScore();
5168 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005169
Paul Jensen85cf78e2015-06-25 13:25:07 -04005170 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005171
Paul Jensenc8b9a742014-09-30 15:37:41 -04005172 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005173 }
5174
Erik Klinec75d4fa2017-02-15 19:59:17 +09005175 // Notify only this one new request of the current state. Transfer all the
5176 // current state by calling NetworkCapabilities and LinkProperties callbacks
5177 // so that callers can be guaranteed to have as close to atomicity in state
5178 // transfer as can be supported by this current API.
5179 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005180 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005181 if (nri.mPendingIntent != null) {
5182 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5183 // Attempt no subsequent state pushes where intents are involved.
5184 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005185 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005186
5187 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5188 // Whether a network is currently suspended is also an important
5189 // element of state to be transferred (it would not otherwise be
5190 // delivered by any currently available mechanism).
5191 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5192 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5193 }
5194 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5195 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005196 }
5197
Robert Greenwalt8d482522015-06-24 13:23:42 -07005198 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005199 // The NetworkInfo we actually send out has no bearing on the real
5200 // state of affairs. For example, if the default connection is mobile,
5201 // and a request for HIPRI has just gone away, we need to pretend that
5202 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5203 // the state to DISCONNECTED, even though the network is of type MOBILE
5204 // and is still connected.
5205 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5206 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005207 if (state != DetailedState.DISCONNECTED) {
5208 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005209 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005210 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005211 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005212 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5213 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5214 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5215 if (info.isFailover()) {
5216 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5217 nai.networkInfo.setFailover(false);
5218 }
5219 if (info.getReason() != null) {
5220 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5221 }
5222 if (info.getExtraInfo() != null) {
5223 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5224 }
5225 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005226 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005227 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005228 if (newDefaultAgent != null) {
5229 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5230 newDefaultAgent.networkInfo);
5231 } else {
5232 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5233 }
5234 }
5235 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5236 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005237 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005238 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005239 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005240 }
5241 }
5242 }
5243
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005244 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005245 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005246 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5247 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005248 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5249 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005250 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5251 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005252 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005253 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005254 } else {
5255 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5256 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005257 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005258 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005259
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005260 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5261 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5262 }
5263
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005264 private String notifyTypeToName(int notifyType) {
5265 switch (notifyType) {
5266 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5267 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5268 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5269 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5270 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5271 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5272 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5273 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5274 }
5275 return "UNKNOWN";
5276 }
5277
Jeff Sharkey69736342014-12-08 14:50:12 -08005278 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005279 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5280 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005281 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005282 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005283 try {
5284 mStatsService.forceUpdateIfaces();
5285 } catch (Exception ignored) {
5286 }
5287 }
5288
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005289 @Override
5290 public boolean addVpnAddress(String address, int prefixLength) {
5291 throwIfLockdownEnabled();
5292 int user = UserHandle.getUserId(Binder.getCallingUid());
5293 synchronized (mVpns) {
5294 return mVpns.get(user).addAddress(address, prefixLength);
5295 }
5296 }
5297
5298 @Override
5299 public boolean removeVpnAddress(String address, int prefixLength) {
5300 throwIfLockdownEnabled();
5301 int user = UserHandle.getUserId(Binder.getCallingUid());
5302 synchronized (mVpns) {
5303 return mVpns.get(user).removeAddress(address, prefixLength);
5304 }
5305 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005306
5307 @Override
5308 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5309 throwIfLockdownEnabled();
5310 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005311 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005312 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005313 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005314 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005315 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005316 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005317 }
5318 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005319 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005320
5321 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005322 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005323 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005324 }
5325
5326 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005327 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5328 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5329 enforceKeepalivePermission();
5330 mKeepaliveTracker.startNattKeepalive(
5331 getNetworkAgentInfoForNetwork(network),
5332 intervalSeconds, messenger, binder,
5333 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5334 }
5335
5336 @Override
5337 public void stopKeepalive(Network network, int slot) {
5338 mHandler.sendMessage(mHandler.obtainMessage(
5339 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5340 }
5341
5342 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005343 public void factoryReset() {
5344 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005345
5346 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5347 return;
5348 }
5349
Robin Lee3b3dd942015-05-12 18:14:58 +01005350 final int userId = UserHandle.getCallingUserId();
5351
Stuart Scottf1fb3972015-04-02 18:00:02 -07005352 // Turn airplane mode off
5353 setAirplaneMode(false);
5354
Stuart Scotte3e314d2015-04-20 14:07:45 -07005355 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5356 // Untether
5357 for (String tether : getTetheredIfaces()) {
5358 untether(tether);
5359 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005360 }
5361
Stuart Scotte3e314d2015-04-20 14:07:45 -07005362 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005363 // Remove always-on package
5364 synchronized (mVpns) {
5365 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5366 if (alwaysOnPackage != null) {
5367 setAlwaysOnVpnPackage(userId, null, false);
5368 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5369 }
5370 }
5371
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005372 // Turn Always-on VPN off
5373 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5374 final long ident = Binder.clearCallingIdentity();
5375 try {
5376 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5377 mLockdownEnabled = false;
5378 setLockdownTracker(null);
5379 } finally {
5380 Binder.restoreCallingIdentity(ident);
5381 }
5382 }
5383
Stuart Scotte3e314d2015-04-20 14:07:45 -07005384 // Turn VPN off
5385 VpnConfig vpnConfig = getVpnConfig(userId);
5386 if (vpnConfig != null) {
5387 if (vpnConfig.legacy) {
5388 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5389 } else {
5390 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5391 // in the future without user intervention.
5392 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005393
Victor Changb04a5ea2016-05-30 20:36:30 +01005394 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005395 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005396 }
5397 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005398
5399 Settings.Global.putString(mContext.getContentResolver(),
5400 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005401 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005402
5403 @VisibleForTesting
5404 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5405 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5406 return new NetworkMonitor(context, handler, nai, defaultRequest);
5407 }
Erik Kline48f12f22016-04-14 17:30:59 +09005408
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005409 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005410 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5411 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005412 }
5413
5414 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005415 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5416 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5417 }
5418
Hugo Benichicfddd682016-05-31 16:28:06 +09005419 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005420 int newNetid = NETID_UNSET;
5421 int prevNetid = NETID_UNSET;
5422 int[] transports = new int[0];
5423 boolean hadIPv4 = false;
5424 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005425
Hugo Benichi5f16f762016-04-20 12:09:33 +09005426 if (newNai != null) {
5427 newNetid = newNai.network.netId;
5428 transports = newNai.networkCapabilities.getTransportTypes();
5429 }
5430 if (prevNai != null) {
5431 prevNetid = prevNai.network.netId;
5432 final LinkProperties lp = prevNai.linkProperties;
5433 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5434 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5435 }
5436
Hugo Benichicfddd682016-05-31 16:28:06 +09005437 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5438 }
5439
5440 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5441 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005442 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005443}