blob: a1a0880062716a52f34497b7b8686f3d47bf7496 [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;
Hugo Benichia0385682017-03-22 17:07:57 +090032import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033
Wenchao Tongf5ea3402015-03-04 13:26:38 -080034import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080035import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090036import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070038import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.ContentResolver;
40import android.content.Context;
41import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070044import android.content.res.Configuration;
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;
Hugo Benichib577d652017-06-27 15:13:20 +090055import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070056import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070057import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070058import android.net.NetworkCapabilities;
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;
Etan Cohen859748f2017-04-03 17:42:34 -070065import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070066import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070067import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070068import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040069import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070070import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040071import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040072import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090073import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090074import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090075import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090076import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080078import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070079import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040080import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070082import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070083import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070084import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Looper;
86import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070087import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070088import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090089import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070090import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070091import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070092import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080093import android.os.ResultReceiver;
Hugo Benichicb883232017-05-11 13:16:17 +090094import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090095import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070096import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040097import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070099import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700100import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700101import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700102import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700103import android.util.LocalLog;
104import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600105import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800106import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700107import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500108import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700109import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700110import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Wink Savilleab9321d2013-06-29 21:10:57 -0700112import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400113import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400114import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700115import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700116import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700117import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700118import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800119import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700120import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700121import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600122import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700123import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900124import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900125import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700126import com.android.internal.util.XmlUtils;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900127import com.android.server.LocalServices;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700128import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400129import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900130import com.android.server.connectivity.KeepaliveTracker;
Charles Hea0a87e82017-05-15 17:07:18 +0100131import com.android.server.connectivity.LingerMonitor;
Christopher Wiley497c1472016-10-11 13:26:03 -0700132import com.android.server.connectivity.MockableSystemProperties;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700133import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600134import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400135import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900136import com.android.server.connectivity.NetworkNotificationManager;
137import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400138import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700139import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800140import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700141import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900142import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700143import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700144import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900145import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600146
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700147import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700148
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700149import org.xmlpull.v1.XmlPullParser;
150import org.xmlpull.v1.XmlPullParserException;
151
152import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700154import java.io.FileNotFoundException;
155import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700156import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700158import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700159import java.net.InetAddress;
160import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700161import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700162import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700163import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700164import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700165import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700166import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700167import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700168import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700169import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600170import java.util.SortedSet;
171import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
173/**
174 * @hide
175 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800176public class ConnectivityService extends IConnectivityManager.Stub
177 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900178 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Erik Kline7747fd42017-05-12 16:52:48 +0900180 public static final String DIAG_ARG = "--diag";
181 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900182 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900183
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900184 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700185 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186
Jake Hamby786e71a2014-02-06 14:43:50 -0800187 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900188 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700189
Jeff Sharkey899223b2012-08-04 15:24:58 -0700190 // TODO: create better separation between radio types and network types
191
Robert Greenwalt42acef32009-08-12 16:08:25 -0700192 // how long to wait before switching back to a radio's default network
193 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
194 // system property that can override the above value
195 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
196 "android.telephony.apn-restore";
197
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900198 // How long to wait before putting up a "This network doesn't have an Internet connection,
199 // connect anyway?" dialog after the user selects a network that doesn't validate.
200 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
201
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900202 // Default to 30s linger time-out. Modifiable only for testing.
203 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
204 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
205 @VisibleForTesting
206 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
207
Jeremy Joslin79294842014-12-03 17:15:28 -0800208 // How long to delay to removal of a pending intent based request.
209 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
210 private final int mReleasePendingIntentDelayMs;
211
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900212 private MockableSystemProperties mSystemProperties;
213
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800214 private Tethering mTethering;
215
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700216 private final PermissionMonitor mPermissionMonitor;
217
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700218 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700219
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700220 @GuardedBy("mVpns")
221 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700222
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700223 private boolean mLockdownEnabled;
224 private LockdownVpnTracker mLockdownTracker;
225
Erik Klineda4bfa82015-04-30 12:58:40 +0900226 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700228 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700229 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800230
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800231 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800232
233 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700234 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800235
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700236 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800237 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700238 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900239 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700240
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700241 private String mCurrentTcpBufferSizes;
242
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700243 private static final int ENABLED = 1;
244 private static final int DISABLED = 0;
245
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900246 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900247 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
248 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900249
Paul Jensenb10e37f2014-11-25 12:33:08 -0500250 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400251 // Tear down networks that have no chance (e.g. even if validated) of becoming
252 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500253 // all networks have been rematched against all NetworkRequests.
254 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400255 // Don't reap networks. This should be passed when some networks have not yet been
256 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500257 DONT_REAP
258 };
259
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900260 private enum UnneededFor {
261 LINGER, // Determine whether this network is unneeded and should be lingered.
262 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
263 }
264
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700265 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266 * used internally to change our mobile data enabled flag
267 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700268 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700269
270 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700271 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700272 * from one net to another. Clear happens when we get a new
273 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
274 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700275 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700276 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700277
Robert Greenwalt434203a2010-10-11 16:00:27 -0700278 /**
279 * used internally to reload global proxy settings
280 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700281 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700282
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700283 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400284 * PAC manager has received new port.
285 */
286 private static final int EVENT_PROXY_HAS_CHANGED = 16;
287
Robert Greenwalte049c232014-04-11 15:53:27 -0700288 /**
289 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700290 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700291 */
292 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
293
Robert Greenwalt7b816022014-04-18 15:25:25 -0700294 /**
295 * used internally when registering NetworkAgents
296 * obj = Messenger
297 */
298 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
299
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 /**
301 * used to add a network request
302 * includes a NetworkRequestInfo
303 */
304 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
305
306 /**
307 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900308 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700309 * cancel it.
310 * includes a NetworkRequestInfo
311 */
312 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
313
314 /**
315 * used to add a network listener - no request
316 * includes a NetworkRequestInfo
317 */
318 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
319
320 /**
321 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400322 * arg1 = UID of caller
323 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700324 */
325 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
326
Robert Greenwalta67be032014-05-16 15:49:14 -0700327 /**
328 * used internally when registering NetworkFactories
329 * obj = Messenger
330 */
331 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
332
Robert Greenwalt27711812014-06-25 16:45:57 -0700333 /**
334 * used internally to expire a wakelock when transitioning
335 * from one net to another. Expire happens when we fail to find
336 * a new network (typically after 1 minute) -
337 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
338 * a replacement network.
339 */
340 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
341
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700342 /**
343 * Used internally to indicate the system is ready.
344 */
345 private static final int EVENT_SYSTEM_READY = 25;
346
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800347 /**
348 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400349 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800350 */
351 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
352
353 /**
354 * used to remove a pending intent and its associated network request.
355 * arg1 = UID of caller
356 * obj = PendingIntent
357 */
358 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
359
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900360 /**
361 * used to specify whether a network should be used even if unvalidated.
362 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
363 * arg2 = whether to remember this choice in the future (1 or 0)
364 * obj = network
365 */
366 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
367
368 /**
369 * used to ask the user to confirm a connection to an unvalidated network.
370 * obj = network
371 */
372 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700373
Erik Klineda4bfa82015-04-30 12:58:40 +0900374 /**
375 * used internally to (re)configure mobile data always-on settings.
376 */
377 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
378
Paul Jensen694f2b82015-06-17 14:15:39 -0400379 /**
380 * used to add a network listener with a pending intent
381 * obj = NetworkRequestInfo
382 */
383 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
384
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900385 /**
386 * used to specify whether a network should not be penalized when it becomes unvalidated.
387 */
388 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
389
390 /**
391 * used to trigger revalidation of a network.
392 */
393 private static final int EVENT_REVALIDATE_NETWORK = 36;
394
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900395 private static String eventName(int what) {
396 return sMagicDecoderRing.get(what, Integer.toString(what));
397 }
398
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900399 /** Handler thread used for both of the handlers below. */
400 @VisibleForTesting
401 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700402 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700403 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700404 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700405 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700406
Mike Lockwood0f79b542009-08-14 14:18:49 -0400407 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800408 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400409
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700410 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700411 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800412 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700413
Robert Greenwalt434203a2010-10-11 16:00:27 -0700414 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400415 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700416 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700417 private boolean mDefaultProxyDisabled = false;
418
Robert Greenwalt434203a2010-10-11 16:00:27 -0700419 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400420 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700421
Jason Monk602b2322013-07-03 17:04:33 -0400422 private PacManager mPacManager = null;
423
Erik Klineda4bfa82015-04-30 12:58:40 +0900424 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700425
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400426 private UserManager mUserManager;
427
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700428 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700429 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700430
Robert Greenwalt50393202011-06-21 17:26:14 -0700431 // the set of network types that can only be enabled by system/sig apps
432 List mProtectedNetworks;
433
John Spurlockbf991a82013-06-24 14:20:23 -0400434 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700435
Wink Savilleab9321d2013-06-29 21:10:57 -0700436 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400437
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900438 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900439 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900440 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900441
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700442 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
443 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700444 private final static int MAX_NET_ID = 65535;
445 private int mNextNetId = MIN_NET_ID;
446
Robert Greenwalt34524f02014-05-18 16:22:10 -0700447 // sequence number of NetworkRequests
448 private int mNextNetworkRequestId = 1;
449
Erik Kline7523eb32015-07-09 18:24:03 +0900450 // NetworkRequest activity String log entries.
451 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
452 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
453
Hugo Benichic2ae2872016-07-11 11:05:12 +0900454 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900455 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900456 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
457
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900458 private static final int MAX_WAKELOCK_LOGS = 20;
459 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900460 private int mTotalWakelockAcquisitions = 0;
461 private int mTotalWakelockReleases = 0;
462 private long mTotalWakelockDurationMs = 0;
463 private long mMaxWakelockDurationMs = 0;
464 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900465
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700466 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
467 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400468 private static class ValidationLog {
469 final Network mNetwork;
470 final String mNetworkExtraInfo;
471 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700472
Paul Jensen0808eb82016-06-03 13:51:21 -0400473 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
474 mNetwork = network;
475 mNetworkExtraInfo = networkExtraInfo;
476 mLog = log;
477 }
478 }
479 private final ArrayDeque<ValidationLog> mValidationLogs =
480 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
481
482 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900483 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700484 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
485 mValidationLogs.removeLast();
486 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400487 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700488 }
489 }
490
Hugo Benichif9fdf872016-07-28 17:53:06 +0900491 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900492
Erik Kline065ab6e2016-10-02 18:02:14 +0900493 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900494 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900495
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700496 /**
497 * Implements support for the legacy "one network per network type" model.
498 *
499 * We used to have a static array of NetworkStateTrackers, one for each
500 * network type, but that doesn't work any more now that we can have,
501 * for example, more that one wifi network. This class stores all the
502 * NetworkAgentInfo objects that support a given type, but the legacy
503 * API will only see the first one.
504 *
505 * It serves two main purposes:
506 *
507 * 1. Provide information about "the network for a given type" (since this
508 * API only supports one).
509 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
510 * the first network for a given type changes, or if the default network
511 * changes.
512 */
513 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900514
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900515 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900517
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700518 /**
519 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
520 * Each list holds references to all NetworkAgentInfos that are used to
521 * satisfy requests for that network type.
522 *
523 * This array is built out at startup such that an unsupported network
524 * doesn't get an ArrayList instance, making this a tristate:
525 * unsupported, supported but not active and active.
526 *
527 * The actual lists are populated when we scan the network types that
528 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900529 *
530 * Threading model:
531 * - addSupportedType() is only called in the constructor
532 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
533 * They are therefore not thread-safe with respect to each other.
534 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
535 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
536 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700537 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900538 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700539
540 public LegacyTypeTracker() {
541 mTypeLists = (ArrayList<NetworkAgentInfo>[])
542 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
543 }
544
545 public void addSupportedType(int type) {
546 if (mTypeLists[type] != null) {
547 throw new IllegalStateException(
548 "legacy list for type " + type + "already initialized");
549 }
550 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
551 }
552
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700553 public boolean isTypeSupported(int type) {
554 return isNetworkTypeValid(type) && mTypeLists[type] != null;
555 }
556
557 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900558 synchronized (mTypeLists) {
559 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
560 return mTypeLists[type].get(0);
561 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900563 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 }
565
Robert Greenwalt8d482522015-06-24 13:23:42 -0700566 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900567 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900568 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700569 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900570 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900571 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900572 }
573 }
574
575 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700576 public void add(int type, NetworkAgentInfo nai) {
577 if (!isTypeSupported(type)) {
578 return; // Invalid network type.
579 }
580 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
581
582 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
583 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700584 return;
585 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900586 synchronized (mTypeLists) {
587 list.add(nai);
588 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900589
590 // 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 +0900591 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900592 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700593 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
594 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700595 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 }
597
Lorenzo Colittia793a672014-07-31 23:20:17 +0900598 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900599 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900600 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
601 if (list == null || list.isEmpty()) {
602 return;
603 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900604 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900605
Hugo Benichi78caa2582016-06-21 09:48:07 +0900606 synchronized (mTypeLists) {
607 if (!list.remove(nai)) {
608 return;
609 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900610 }
611
Robert Greenwalt8d482522015-06-24 13:23:42 -0700612 final DetailedState state = DetailedState.DISCONNECTED;
613
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900614 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700615 maybeLogBroadcast(nai, state, type, wasDefault);
616 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900617 }
618
619 if (!list.isEmpty() && wasFirstNetwork) {
620 if (DBG) log("Other network available for type " + type +
621 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900622 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700623 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
624 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900625 }
626 }
627
628 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900629 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
630 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700631 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900632 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700633 }
634 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700635
Robert Greenwalt8d482522015-06-24 13:23:42 -0700636 // send out another legacy broadcast - currently only used for suspend/unsuspend
637 // toggle
638 public void update(NetworkAgentInfo nai) {
639 final boolean isDefault = isDefaultNetwork(nai);
640 final DetailedState state = nai.networkInfo.getDetailedState();
641 for (int type = 0; type < mTypeLists.length; type++) {
642 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700643 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900644 final boolean isFirst = contains && (nai == list.get(0));
645 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700646 maybeLogBroadcast(nai, state, type, isDefault);
647 sendLegacyNetworkBroadcast(nai, state, type);
648 }
649 }
650 }
651
Lorenzo Colittia793a672014-07-31 23:20:17 +0900652 private String naiToString(NetworkAgentInfo nai) {
653 String name = (nai != null) ? nai.name() : "null";
654 String state = (nai.networkInfo != null) ?
655 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
656 "???/???";
657 return name + " " + state;
658 }
659
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700660 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900661 pw.println("mLegacyTypeTracker:");
662 pw.increaseIndent();
663 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700664 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900665 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700666 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900667 pw.println();
668 pw.println("Current state:");
669 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900670 synchronized (mTypeLists) {
671 for (int type = 0; type < mTypeLists.length; type++) {
672 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
673 for (NetworkAgentInfo nai : mTypeLists[type]) {
674 pw.println(type + " " + naiToString(nai));
675 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900676 }
677 }
678 pw.decreaseIndent();
679 pw.decreaseIndent();
680 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700681 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700682 }
683 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
684
Jeff Sharkey899223b2012-08-04 15:24:58 -0700685 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700686 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900687 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
688 }
689
690 @VisibleForTesting
691 protected ConnectivityService(Context context, INetworkManagementService netManager,
692 INetworkStatsService statsService, INetworkPolicyManager policyManager,
693 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800694 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800695
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900696 mSystemProperties = getSystemProperties();
697
Hugo Benichif9fdf872016-07-28 17:53:06 +0900698 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900699 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900700 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900701 mNetworkRequests.put(mDefaultRequest, defaultNRI);
702 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900703
704 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900705 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700706
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900707 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900708 mHandlerThread.start();
709 mHandler = new InternalHandler(mHandlerThread.getLooper());
710 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700711
Jeremy Joslin79294842014-12-03 17:15:28 -0800712 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
713 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
714
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900715 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900716
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700717 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700718 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800719 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700720 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900721 mPolicyManagerInternal = checkNotNull(
722 LocalServices.getService(NetworkPolicyManagerInternal.class),
723 "missing NetworkPolicyManagerInternal");
724
Jeff Sharkey82f85212012-08-24 11:17:25 -0700725 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700726 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700727
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700728 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900729 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700730 } catch (RemoteException e) {
731 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700732 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700733 }
734
735 final PowerManager powerManager = (PowerManager) context.getSystemService(
736 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700737 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
738 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
739 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800740 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700741
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700742 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700743
Wink Saville51f456f2013-04-23 14:26:51 -0700744 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900745 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700746 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700747 String[] naStrings = context.getResources().getStringArray(
748 com.android.internal.R.array.networkAttributes);
749 for (String naString : naStrings) {
750 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700751 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700752 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700753 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800754 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700755 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700756 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700757 }
Wink Saville51f456f2013-04-23 14:26:51 -0700758 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
759 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
760 n.type);
761 continue;
762 }
Wink Saville975c8482011-04-07 14:23:45 -0700763 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800764 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700765 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700766 continue;
767 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700768 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700769
Wink Saville975c8482011-04-07 14:23:45 -0700770 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700771 mNetworksDefined++;
772 } catch(Exception e) {
773 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700774 }
775 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700776
777 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
778 if (mNetConfigs[TYPE_VPN] == null) {
779 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
780 // don't need to add TYPE_VPN to mNetConfigs.
781 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
782 mNetworksDefined++; // used only in the log() statement below.
783 }
784
Wink Saville5e56bc52013-07-29 15:00:57 -0700785 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700786
Robert Greenwalt50393202011-06-21 17:26:14 -0700787 mProtectedNetworks = new ArrayList<Integer>();
788 int[] protectedNetworks = context.getResources().getIntArray(
789 com.android.internal.R.array.config_protectedNetworks);
790 for (int p : protectedNetworks) {
791 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
792 mProtectedNetworks.add(p);
793 } else {
794 if (DBG) loge("Ignoring protectedNetwork " + p);
795 }
796 }
797
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900798 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
799 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700800
Erik Kline47222fc2017-04-30 19:36:15 +0900801 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800802
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700803 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
804
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700805 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700806 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100807 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700808 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700809 intentFilter.addAction(Intent.ACTION_USER_ADDED);
810 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000811 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700812 mContext.registerReceiverAsUser(
813 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000814 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
815 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900816
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700817 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700818 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700819 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700820 } catch (RemoteException e) {
821 loge("Error registering observer :" + e);
822 }
823
Erik Klineda4bfa82015-04-30 12:58:40 +0900824 mSettingsObserver = new SettingsObserver(mContext, mHandler);
825 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800826
John Spurlockbf991a82013-06-24 14:20:23 -0400827 mDataConnectionStats = new DataConnectionStats(mContext);
828 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400829
Jason Monkdecd2952013-10-10 14:02:51 -0400830 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700831
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400832 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900833
834 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900835 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
836 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900837
838 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
839 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
840 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
841 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
842 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
843 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
844 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900845
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900846 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900847 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900848 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700850
Erik Kline47222fc2017-04-30 19:36:15 +0900851 private Tethering makeTethering() {
852 // TODO: Move other elements into @Overridden getters.
853 final TetheringDependencies deps = new TetheringDependencies();
854 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
855 IoThread.get().getLooper(), new MockableSystemProperties(),
856 deps);
857 }
858
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900859 private NetworkRequest createInternetRequestForTransport(
860 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900861 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900862 netCap.addCapability(NET_CAPABILITY_INTERNET);
863 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900864 if (transportType > -1) {
865 netCap.addTransportType(transportType);
866 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900867 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900868 }
869
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900870 // Used only for testing.
871 // TODO: Delete this and either:
872 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
873 // changing ContentResolver to make registerContentObserver non-final).
874 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
875 // by subclassing SettingsObserver.
876 @VisibleForTesting
877 void updateMobileDataAlwaysOn() {
878 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
879 }
880
Erik Klineda4bfa82015-04-30 12:58:40 +0900881 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900882 final boolean enable = toBool(Settings.Global.getInt(
883 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900884 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
885 if (enable == isEnabled) {
886 return; // Nothing to do.
887 }
888
889 if (enable) {
890 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900891 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900892 } else {
893 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
894 }
895 }
896
897 private void registerSettingsCallbacks() {
898 // Watch for global HTTP proxy changes.
899 mSettingsObserver.observe(
900 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
901 EVENT_APPLY_GLOBAL_HTTP_PROXY);
902
903 // Watch for whether or not to keep mobile data always on.
904 mSettingsObserver.observe(
905 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
906 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
907 }
908
Robert Greenwalt34524f02014-05-18 16:22:10 -0700909 private synchronized int nextNetworkRequestId() {
910 return mNextNetworkRequestId++;
911 }
912
Paul Jensen67b0b072015-06-10 11:22:17 -0400913 @VisibleForTesting
914 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400915 synchronized (mNetworkForNetId) {
916 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
917 int netId = mNextNetId;
918 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
919 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500920 if (!mNetIdInUse.get(netId)) {
921 mNetIdInUse.put(netId, true);
922 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400923 }
924 }
925 }
926 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700927 }
928
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600929 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800930 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600931 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
932 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800933 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600934 state = nai.getNetworkState();
935 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600937 final NetworkInfo info = new NetworkInfo(networkType, 0,
938 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
940 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600941 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
942 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800943 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600944 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600945 return state;
946 } else {
947 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400949 }
950
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
952 if (network == null) {
953 return null;
954 }
955 synchronized (mNetworkForNetId) {
956 return mNetworkForNetId.get(network.netId);
957 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600958 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800959
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900960 private Network[] getVpnUnderlyingNetworks(int uid) {
961 if (!mLockdownEnabled) {
962 int user = UserHandle.getUserId(uid);
963 synchronized (mVpns) {
964 Vpn vpn = mVpns.get(user);
965 if (vpn != null && vpn.appliesToUid(uid)) {
966 return vpn.getUnderlyingNetworks();
967 }
968 }
969 }
970 return null;
971 }
972
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800973 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400974 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800975
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900976 final Network[] networks = getVpnUnderlyingNetworks(uid);
977 if (networks != null) {
978 // getUnderlyingNetworks() returns:
979 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
980 // empty array => the VPN explicitly said "no default network".
981 // non-empty array => the VPN specified one or more default networks; we use the
982 // first one.
983 if (networks.length > 0) {
984 nai = getNetworkAgentInfoForNetwork(networks[0]);
985 } else {
986 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800987 }
988 }
989
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800990 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600991 return nai.getNetworkState();
992 } else {
993 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800994 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400995 }
996
997 /**
998 * Check if UID should be blocked from using the network with the given LinkProperties.
999 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001000 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1001 boolean ignoreBlocked) {
1002 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001003 if (ignoreBlocked) {
1004 return false;
1005 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001006 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001007 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1008 if (isSystem(uid)) {
1009 return false;
1010 }
Robin Lee17e61832016-05-09 13:46:28 +01001011 synchronized (mVpns) {
1012 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1013 if (vpn != null && vpn.isBlockingUid(uid)) {
1014 return true;
1015 }
1016 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001017 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001018 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 }
1020
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001021 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001022 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1023 return;
1024 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001025 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001026 synchronized (mBlockedAppUids) {
1027 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001028 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001029 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001030 blocked = false;
1031 } else {
1032 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001033 }
1034 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001035 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1036 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1037 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001038 }
1039
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001040 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001041 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1042 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1043 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1044 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001045 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001046 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001047 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1048
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001049 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001050 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001051 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001052 if (mLockdownTracker != null) {
1053 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001054 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001055
1056 // TODO: apply metered state closer to NetworkAgentInfo
1057 final long token = Binder.clearCallingIdentity();
1058 try {
1059 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1060 } catch (RemoteException e) {
1061 } finally {
1062 Binder.restoreCallingIdentity(token);
1063 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001064 }
1065
1066 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 * Return NetworkInfo for the active (i.e., connected) network interface.
1068 * It is assumed that at most one network is active at a time. If more
1069 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001070 * @return the info for the active network, or {@code null} if none is
1071 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001073 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001075 enforceAccessPermission();
1076 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001077 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001078 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001079 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1080 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001081 }
1082
Paul Jensen31a94f42015-02-13 14:18:39 -05001083 @Override
1084 public Network getActiveNetwork() {
1085 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001086 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001087 }
1088
1089 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001090 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001091 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001092 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001093 }
1094
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001095 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001096 final int user = UserHandle.getUserId(uid);
1097 int vpnNetId = NETID_UNSET;
1098 synchronized (mVpns) {
1099 final Vpn vpn = mVpns.get(user);
1100 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1101 }
1102 NetworkAgentInfo nai;
1103 if (vpnNetId != NETID_UNSET) {
1104 synchronized (mNetworkForNetId) {
1105 nai = mNetworkForNetId.get(vpnNetId);
1106 }
1107 if (nai != null) return nai.network;
1108 }
1109 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001110 if (nai != null
1111 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1112 nai = null;
1113 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001114 return nai != null ? nai.network : null;
1115 }
1116
Lorenzo Colitti18660282016-07-04 12:55:44 +09001117 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001118 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1119 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001120 final int uid = Binder.getCallingUid();
1121 NetworkState state = getUnfilteredActiveNetworkState(uid);
1122 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001123 }
1124
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001125 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001126 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001127 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001128 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001129 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001130 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001131 }
1132
1133 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001134 public NetworkInfo getNetworkInfo(int networkType) {
1135 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001136 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001137 if (getVpnUnderlyingNetworks(uid) != null) {
1138 // A VPN is active, so we may need to return one of its underlying networks. This
1139 // information is not available in LegacyTypeTracker, so we have to get it from
1140 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001141 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001142 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001143 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001144 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001145 }
1146 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001147 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001148 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001149 }
1150
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001151 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001152 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001153 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001154 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001156 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001157 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001158 return state.networkInfo;
1159 } else {
1160 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001161 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 }
1163
1164 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001165 public NetworkInfo[] getAllNetworkInfo() {
1166 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001167 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001168 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1169 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170 NetworkInfo info = getNetworkInfo(networkType);
1171 if (info != null) {
1172 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001173 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001174 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001175 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001176 }
1177
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001178 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001179 public Network getNetworkForType(int networkType) {
1180 enforceAccessPermission();
1181 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001182 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1183 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001184 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001185 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001187 }
1188
1189 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001190 public Network[] getAllNetworks() {
1191 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001192 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001193 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001194 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001195 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001196 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001197 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001198 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001199 }
1200
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001201 @Override
1202 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1203 // The basic principle is: if an app's traffic could possibly go over a
1204 // network, without the app doing anything multinetwork-specific,
1205 // (hence, by "default"), then include that network's capabilities in
1206 // the array.
1207 //
1208 // In the normal case, app traffic only goes over the system's default
1209 // network connection, so that's the only network returned.
1210 //
1211 // With a VPN in force, some app traffic may go into the VPN, and thus
1212 // over whatever underlying networks the VPN specifies, while other app
1213 // traffic may go over the system default network (e.g.: a split-tunnel
1214 // VPN, or an app disallowed by the VPN), so the set of networks
1215 // returned includes the VPN's underlying networks and the system
1216 // default.
1217 enforceAccessPermission();
1218
1219 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1220
1221 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001222 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001223 if (nc != null) {
1224 result.put(nai.network, nc);
1225 }
1226
1227 if (!mLockdownEnabled) {
1228 synchronized (mVpns) {
1229 Vpn vpn = mVpns.get(userId);
1230 if (vpn != null) {
1231 Network[] networks = vpn.getUnderlyingNetworks();
1232 if (networks != null) {
1233 for (Network network : networks) {
1234 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001235 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001236 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001237 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001238 }
1239 }
1240 }
1241 }
1242 }
1243 }
1244
1245 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1246 out = result.values().toArray(out);
1247 return out;
1248 }
1249
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001250 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001251 public boolean isNetworkSupported(int networkType) {
1252 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001253 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001254 }
1255
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001256 /**
1257 * Return LinkProperties for the active (i.e., connected) default
1258 * network interface. It is assumed that at most one default network
1259 * is active at a time. If more than one is active, it is indeterminate
1260 * which will be returned.
1261 * @return the ip properties for the active network, or {@code null} if
1262 * none is active
1263 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001264 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001265 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001266 enforceAccessPermission();
1267 final int uid = Binder.getCallingUid();
1268 NetworkState state = getUnfilteredActiveNetworkState(uid);
1269 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001270 }
1271
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001272 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001273 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001274 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001275 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1276 if (nai != null) {
1277 synchronized (nai) {
1278 return new LinkProperties(nai.linkProperties);
1279 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001280 }
1281 return null;
1282 }
1283
Robert Greenwalt12e67352014-05-13 21:41:06 -07001284 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001285 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001286 public LinkProperties getLinkProperties(Network network) {
1287 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001288 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1289 }
1290
1291 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1292 if (nai == null) {
1293 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001294 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001295 synchronized (nai) {
1296 return new LinkProperties(nai.linkProperties);
1297 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001298 }
1299
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001300 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001301 if (nai != null) {
1302 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001303 if (nai.networkCapabilities != null) {
1304 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001305 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001306 }
1307 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001308 return null;
1309 }
1310
1311 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001312 public NetworkCapabilities getNetworkCapabilities(Network network) {
1313 enforceAccessPermission();
1314 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1315 }
1316
1317 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001318 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001319 // Require internal since we're handing out IMSI details
1320 enforceConnectivityInternalPermission();
1321
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001322 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001323 for (Network network : getAllNetworks()) {
1324 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1325 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001326 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001327 }
1328 }
1329 return result.toArray(new NetworkState[result.size()]);
1330 }
1331
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001332 @Override
1333 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1334 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001335 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001336 final long token = Binder.clearCallingIdentity();
1337 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001338 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1339 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001340 try {
1341 return mPolicyManager.getNetworkQuotaInfo(state);
1342 } catch (RemoteException e) {
1343 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001344 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001345 return null;
1346 } finally {
1347 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001348 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001349 }
1350
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001351 @Override
1352 public boolean isActiveNetworkMetered() {
1353 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001354
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001355 final NetworkInfo info = getActiveNetworkInfo();
1356 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001357 }
1358
Jeff Sharkey216c1812012-08-05 14:29:23 -07001359 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1360 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001361 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001362 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001363 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001364 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001365 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001366
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001367 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001368 * Ensure that a network route exists to deliver traffic to the specified
1369 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001370 * @param networkType the type of the network over which traffic to the
1371 * specified host is to be routed
1372 * @param hostAddress the IP address of the host to which the route is
1373 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 * @return {@code true} on success, {@code false} on failure
1375 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001376 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001377 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001379 if (mProtectedNetworks.contains(networkType)) {
1380 enforceConnectivityInternalPermission();
1381 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001382
Chad Brubakerc0234532014-02-14 13:24:29 -08001383 InetAddress addr;
1384 try {
1385 addr = InetAddress.getByAddress(hostAddress);
1386 } catch (UnknownHostException e) {
1387 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1388 return false;
1389 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001392 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001393 return false;
1394 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001395
1396 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1397 if (nai == null) {
1398 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1399 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1400 } else {
1401 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1402 }
1403 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001404 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001405
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001406 DetailedState netState;
1407 synchronized (nai) {
1408 netState = nai.networkInfo.getDetailedState();
1409 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001410
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001411 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001412 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001413 log("requestRouteToHostAddress on down network "
1414 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001415 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001416 }
1417 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001418 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001419
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001420 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001421 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001422 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001423 LinkProperties lp;
1424 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001425 synchronized (nai) {
1426 lp = nai.linkProperties;
1427 netId = nai.network.netId;
1428 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001429 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001430 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1431 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001432 } finally {
1433 Binder.restoreCallingIdentity(token);
1434 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001435 }
1436
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001437 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001438 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001439 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001440 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001441 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001442 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001443 if (bestRoute.getGateway().equals(addr)) {
1444 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001445 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001446 } else {
1447 // if we will connect to this through another route, add a direct route
1448 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001449 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001450 }
1451 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001452 if (DBG) log("Adding legacy route " + bestRoute +
1453 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001454 try {
1455 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1456 } catch (Exception e) {
1457 // never crash - catch them all
1458 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001459 return false;
1460 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001461 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001462 }
1463
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001464 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001465 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001466 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001467 // TODO: notify UID when it has requested targeted updates
1468 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001469 @Override
1470 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001471 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001472 @Override
1473 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001474 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001475 if (restrictBackground) {
1476 log("onRestrictBackgroundChanged(true): disabling tethering");
1477 mTethering.untetherAll();
1478 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001479 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001480 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001481 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001482 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001483 };
1484
Robin Lee3b3dd942015-05-12 18:14:58 +01001485 /**
1486 * Require that the caller is either in the same user or has appropriate permission to interact
1487 * across users.
1488 *
1489 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1490 */
1491 private void enforceCrossUserPermission(int userId) {
1492 if (userId == UserHandle.getCallingUserId()) {
1493 // Not a cross-user call.
1494 return;
1495 }
1496 mContext.enforceCallingOrSelfPermission(
1497 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1498 "ConnectivityService");
1499 }
1500
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001501 private void enforceInternetPermission() {
1502 mContext.enforceCallingOrSelfPermission(
1503 android.Manifest.permission.INTERNET,
1504 "ConnectivityService");
1505 }
1506
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001508 mContext.enforceCallingOrSelfPermission(
1509 android.Manifest.permission.ACCESS_NETWORK_STATE,
1510 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512
1513 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001514 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001515 }
1516
Charles Hea0a87e82017-05-15 17:07:18 +01001517 private void enforceSettingsPermission() {
1518 mContext.enforceCallingOrSelfPermission(
1519 android.Manifest.permission.NETWORK_SETTINGS,
1520 "ConnectivityService");
1521 }
1522
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001523 private void enforceTetherAccessPermission() {
1524 mContext.enforceCallingOrSelfPermission(
1525 android.Manifest.permission.ACCESS_NETWORK_STATE,
1526 "ConnectivityService");
1527 }
1528
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001529 private void enforceConnectivityInternalPermission() {
1530 mContext.enforceCallingOrSelfPermission(
1531 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1532 "ConnectivityService");
1533 }
1534
Hugo Benichi514da602016-07-19 15:59:27 +09001535 private void enforceConnectivityRestrictedNetworksPermission() {
1536 try {
1537 mContext.enforceCallingOrSelfPermission(
1538 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1539 "ConnectivityService");
1540 return;
1541 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1542 enforceConnectivityInternalPermission();
1543 }
1544
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001545 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001546 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001547 }
1548
Lorenzo Colitti18660282016-07-04 12:55:44 +09001549 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001550 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001551 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001552 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001553 }
1554
1555 private void sendInetConditionBroadcast(NetworkInfo info) {
1556 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1557 }
1558
Wink Saville628b0852011-08-04 15:01:58 -07001559 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001560 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001561 info = new NetworkInfo(info);
1562 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001563 }
1564
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001565 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001566 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001567 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 if (info.isFailover()) {
1569 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1570 info.setFailover(false);
1571 }
1572 if (info.getReason() != null) {
1573 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1574 }
1575 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001576 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1577 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001578 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001579 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001580 return intent;
1581 }
1582
1583 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1584 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1585 }
1586
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001587 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001588 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1589 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1590 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001591 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001592 final long ident = Binder.clearCallingIdentity();
1593 try {
1594 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1595 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1596 } finally {
1597 Binder.restoreCallingIdentity(ident);
1598 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001599 }
1600
Mike Lockwood0f79b542009-08-14 14:18:49 -04001601 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001602 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001603 if (!mSystemReady) {
1604 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001605 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001606 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001607 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001608 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001609 }
1610
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001611 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001612 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001613 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001614 final NetworkInfo ni = intent.getParcelableExtra(
1615 ConnectivityManager.EXTRA_NETWORK_INFO);
1616 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1617 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1618 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001619 } else {
1620 BroadcastOptions opts = BroadcastOptions.makeBasic();
1621 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1622 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001623 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001624 final IBatteryStats bs = BatteryStatsService.getService();
1625 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001626 bs.noteConnectivityChanged(intent.getIntExtra(
1627 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1628 ni != null ? ni.getState().toString() : "?");
1629 } catch (RemoteException e) {
1630 }
1631 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001632 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001633 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001634 } finally {
1635 Binder.restoreCallingIdentity(ident);
1636 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001637 }
1638 }
1639
1640 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001641 loadGlobalProxy();
1642
Hugo Benichi20035e02017-04-26 14:53:28 +09001643 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001644 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001645 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001646 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001647 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001648 }
1649 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001650 // load the global proxy at startup
1651 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001652
Robin Lee244ce8e2016-01-05 18:03:46 +00001653 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1654 // for user to unlock device too.
1655 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001656
Erik Klineda4bfa82015-04-30 12:58:40 +09001657 // Configure whether mobile data is always on.
1658 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1659
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001660 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001661
1662 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001663 }
1664
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001665 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001666 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001667 *
1668 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001669 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001670 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001671 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1672 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001673
1674 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001675 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001676
Robert Greenwalt7b816022014-04-18 15:25:25 -07001677 if (networkAgent.networkCapabilities.hasTransport(
1678 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001679 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1680 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001681 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001682 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001683 } else if (networkAgent.networkCapabilities.hasTransport(
1684 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001685 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1686 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001687 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001688 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001689 } else {
1690 // do not track any other networks
1691 timeout = 0;
1692 }
1693
Robert Greenwalt7b816022014-04-18 15:25:25 -07001694 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001695 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001696 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001697 } catch (Exception e) {
1698 // You shall not crash!
1699 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001700 }
1701 }
1702 }
1703
1704 /**
1705 * Remove data activity tracking when network disconnects.
1706 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001707 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1708 final String iface = networkAgent.linkProperties.getInterfaceName();
1709 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001710
Robert Greenwalt7b816022014-04-18 15:25:25 -07001711 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1712 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001713 try {
1714 // the call fails silently if no idletimer setup for this interface
1715 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001716 } catch (Exception e) {
1717 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001718 }
1719 }
1720 }
1721
1722 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001723 * Reads the network specific MTU size from reources.
1724 * and set it on it's iface.
1725 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001726 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1727 final String iface = newLp.getInterfaceName();
1728 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001729 if (oldLp == null && mtu == 0) {
1730 // Silently ignore unset MTU value.
1731 return;
1732 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001733 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1734 if (VDBG) log("identical MTU - not setting");
1735 return;
1736 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001737 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001738 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001739 return;
1740 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001741
w1997615afd812014-08-05 15:18:11 -07001742 // Cannot set MTU without interface name
1743 if (TextUtils.isEmpty(iface)) {
1744 loge("Setting MTU size with null iface.");
1745 return;
1746 }
1747
Robert Greenwalt7b816022014-04-18 15:25:25 -07001748 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001749 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001750 mNetd.setMtu(iface, mtu);
1751 } catch (Exception e) {
1752 Slog.e(TAG, "exception in setMtu()" + e);
1753 }
1754 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001755
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001756 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001757 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1758
1759 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001760 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001761 protected MockableSystemProperties getSystemProperties() {
1762 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001763 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001764
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001765 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1766 if (isDefaultNetwork(nai) == false) {
1767 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001768 }
1769
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001770 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1771 String[] values = null;
1772 if (tcpBufferSizes != null) {
1773 values = tcpBufferSizes.split(",");
1774 }
1775
1776 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001777 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001778 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1779 values = tcpBufferSizes.split(",");
1780 }
1781
1782 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1783
1784 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001785 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001786
1787 final String prefix = "/sys/kernel/ipv4/tcp_";
1788 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1789 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1790 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1791 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1792 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1793 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1794 mCurrentTcpBufferSizes = tcpBufferSizes;
1795 } catch (IOException e) {
1796 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001797 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001798
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001799 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001800 Settings.Global.TCP_DEFAULT_INIT_RWND,
1801 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001802 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1803 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001804 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001805 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001806 }
1807
Mattias Falk8b47b362011-08-23 14:15:13 +02001808 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001809 /*
1810 * Tell the VMs to toss their DNS caches
1811 */
1812 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1813 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001814 /*
1815 * Connectivity events can happen before boot has completed ...
1816 */
1817 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001818 final long ident = Binder.clearCallingIdentity();
1819 try {
1820 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1821 } finally {
1822 Binder.restoreCallingIdentity(ident);
1823 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001824 }
1825
Robert Greenwalt562cc542014-05-15 18:07:26 -07001826 @Override
1827 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001828 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001829 NETWORK_RESTORE_DELAY_PROP_NAME);
1830 if(restoreDefaultNetworkDelayStr != null &&
1831 restoreDefaultNetworkDelayStr.length() != 0) {
1832 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001833 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001834 } catch (NumberFormatException e) {
1835 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001836 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001837 // if the system property isn't set, use the value for the apn type
1838 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1839
1840 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1841 (mNetConfigs[networkType] != null)) {
1842 ret = mNetConfigs[networkType].restoreTime;
1843 }
1844 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 }
1846
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001847 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001848 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001849 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001850 }
1851 return false;
1852 }
1853
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001854 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1855 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1856 final long DIAG_TIME_MS = 5000;
1857 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1858 // Start gathering diagnostic information.
1859 netDiags.add(new NetworkDiagnostics(
1860 nai.network,
1861 new LinkProperties(nai.linkProperties), // Must be a copy.
1862 DIAG_TIME_MS));
1863 }
1864
1865 for (NetworkDiagnostics netDiag : netDiags) {
1866 pw.println();
1867 netDiag.waitForMeasurements();
1868 netDiag.dump(pw);
1869 }
1870 }
1871
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001873 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1874 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001875 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001876
Erik Kline7747fd42017-05-12 16:52:48 +09001877 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001878 dumpNetworkDiagnostics(pw);
1879 return;
Erik Klineee363c42017-05-29 09:11:03 +09001880 } else if (argsContain(args, TETHERING_ARG)) {
1881 mTethering.dump(fd, pw, args);
1882 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001883 }
Erik Kline379747a2015-06-05 17:47:34 +09001884
Lorenzo Colittie3805462015-06-03 11:18:24 +09001885 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001886 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001887 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001888 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001889 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001890 pw.println();
1891
Paul Jensen85cf78e2015-06-25 13:25:07 -04001892 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001893 pw.print("Active default network: ");
1894 if (defaultNai == null) {
1895 pw.println("none");
1896 } else {
1897 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001898 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001899 pw.println();
1900
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001901 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001902 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001903 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1904 pw.println(nai.toString());
1905 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001906 pw.println(String.format(
1907 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1908 nai.numForegroundNetworkRequests(),
1909 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1910 nai.numBackgroundNetworkRequests(),
1911 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001912 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001913 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1914 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001915 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001916 pw.decreaseIndent();
1917 pw.println("Lingered:");
1918 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001919 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001920 pw.decreaseIndent();
1921 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001922 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001923 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001924 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001925
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001926 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001927 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001928 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1929 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001930 }
1931 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001932 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001933
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001934 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001935
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001936 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001937 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001938
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001939 pw.println();
1940 mKeepaliveTracker.dump(pw);
1941
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001942 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001943 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001944
Erik Kline7747fd42017-05-12 16:52:48 +09001945 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001946 pw.println();
1947 synchronized (mValidationLogs) {
1948 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001949 for (ValidationLog p : mValidationLogs) {
1950 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001951 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001952 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001953 pw.decreaseIndent();
1954 }
1955 }
Erik Kline7523eb32015-07-09 18:24:03 +09001956
1957 pw.println();
1958 pw.println("mNetworkRequestInfoLogs (most recent first):");
1959 pw.increaseIndent();
1960 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1961 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001962
1963 pw.println();
1964 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1965 pw.increaseIndent();
1966 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1967 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001968
1969 pw.println();
1970 pw.println("NetTransition WakeLock activity (most recent first):");
1971 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09001972 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1973 pw.println("total releases: " + mTotalWakelockReleases);
1974 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1975 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1976 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1977 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1978 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1979 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001980 mWakelockLogs.reverseDump(fd, pw, args);
1981 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001982 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001983 }
1984
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001985 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001986 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001987 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001988 if (officialNai != null && officialNai.equals(nai)) return true;
1989 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001990 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001991 " - " + nai);
1992 }
1993 return false;
1994 }
1995
Robert Greenwalt42acef32009-08-12 16:08:25 -07001996 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001997 private class NetworkStateTrackerHandler extends Handler {
1998 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001999 super(looper);
2000 }
2001
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002002 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002003 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002004 default:
2005 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002006 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002007 handleAsyncChannelHalfConnect(msg);
2008 break;
2009 }
2010 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2011 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2012 if (nai != null) nai.asyncChannel.disconnect();
2013 break;
2014 }
2015 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2016 handleAsyncChannelDisconnected(msg);
2017 break;
2018 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002019 }
2020 return true;
2021 }
2022
2023 private void maybeHandleNetworkAgentMessage(Message msg) {
2024 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2025 if (nai == null) {
2026 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002027 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002028 }
2029 return;
2030 }
2031
2032 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002033 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002034 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2035 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002036 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2037 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002038 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002039 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002040 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002041 break;
2042 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002043 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002044 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002045 break;
2046 }
2047 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002048 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002049 updateNetworkInfo(nai, info);
2050 break;
2051 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002052 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002053 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002054 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002055 break;
2056 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002057 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002058 try {
2059 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002060 } catch (Exception e) {
2061 // Never crash!
2062 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002063 }
2064 break;
2065 }
2066 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002067 try {
2068 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002069 } catch (Exception e) {
2070 // Never crash!
2071 loge("Exception in removeVpnUidRanges: " + e);
2072 }
2073 break;
2074 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002075 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002076 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2077 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002078 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002079 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002080 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002081 break;
2082 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002083 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002084 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2085 break;
2086 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002087 }
2088 }
2089
2090 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2091 switch (msg.what) {
2092 default:
2093 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002094 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002095 final NetworkAgentInfo nai;
2096 synchronized (mNetworkForNetId) {
2097 nai = mNetworkForNetId.get(msg.arg2);
2098 }
2099 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002100 final boolean valid =
2101 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002102 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002103 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2104 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002105 if (valid != nai.lastValidated) {
2106 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002107 nai.lastValidated = valid;
2108 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002109 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002110 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2111 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002112 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002113 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002114 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002115 Bundle redirectUrlBundle = new Bundle();
2116 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002117 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002118 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002119 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002120 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002121 if (wasValidated && !nai.lastValidated) {
2122 handleNetworkUnvalidated(nai);
2123 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002124 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002125 break;
2126 }
Paul Jensen869868be2014-05-15 10:33:05 -04002127 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002128 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002129 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002130 final NetworkAgentInfo nai;
2131 synchronized (mNetworkForNetId) {
2132 nai = mNetworkForNetId.get(netId);
2133 }
Calvin Onbe96da12016-10-11 15:10:46 -07002134 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002135 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002136 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002137 nai.lastCaptivePortalDetected = visible;
2138 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002139 if (nai.lastCaptivePortalDetected &&
2140 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2141 if (DBG) log("Avoiding captive portal network: " + nai.name());
2142 nai.asyncChannel.sendMessage(
2143 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2144 teardownUnneededNetwork(nai);
2145 break;
2146 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002147 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002148 }
2149 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002150 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002151 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002152 if (nai == null) {
2153 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2154 break;
2155 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002156 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002157 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002158 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002159 }
Paul Jensen869868be2014-05-15 10:33:05 -04002160 }
Paul Jensen869868be2014-05-15 10:33:05 -04002161 break;
2162 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002163 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002164 return true;
2165 }
2166
Calvin Onbe96da12016-10-11 15:10:46 -07002167 private int getCaptivePortalMode() {
2168 return Settings.Global.getInt(mContext.getContentResolver(),
2169 Settings.Global.CAPTIVE_PORTAL_MODE,
2170 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2171 }
2172
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002173 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2174 switch (msg.what) {
2175 default:
2176 return false;
2177 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2178 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2179 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2180 handleLingerComplete(nai);
2181 }
2182 break;
2183 }
2184 }
2185 return true;
2186 }
2187
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002188 @Override
2189 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002190 if (!maybeHandleAsyncChannelMessage(msg) &&
2191 !maybeHandleNetworkMonitorMessage(msg) &&
2192 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002193 maybeHandleNetworkAgentMessage(msg);
2194 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002195 }
2196 }
2197
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002198 private void updateLingerState(NetworkAgentInfo nai, long now) {
2199 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2200 // 2. If the network was lingering and there are now requests, unlinger it.
2201 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2202 // one lingered request, start lingering.
2203 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002204 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002205 if (DBG) log("Unlingering " + nai.name());
2206 nai.unlinger();
2207 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002208 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002209 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002210 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002211 nai.linger();
2212 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2213 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2214 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002215 }
2216
Robert Greenwalt7b816022014-04-18 15:25:25 -07002217 private void handleAsyncChannelHalfConnect(Message msg) {
2218 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002219 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002220 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2221 if (VDBG) log("NetworkFactory connected");
2222 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002223 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002224 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002225 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002226 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002227 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002228 }
2229 } else {
2230 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002231 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002232 }
2233 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2234 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2235 if (VDBG) log("NetworkAgent connected");
2236 // A network agent has requested a connection. Establish the connection.
2237 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2238 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2239 } else {
2240 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002241 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002242 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002243 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002244 synchronized (mNetworkForNetId) {
2245 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002246 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002247 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002248 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002249 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002250 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002251 }
2252 }
2253 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002254
Robert Greenwalt7b816022014-04-18 15:25:25 -07002255 private void handleAsyncChannelDisconnected(Message msg) {
2256 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2257 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002258 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002259 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002260 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002261 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002262 // TODO - if we move the logic to the network agent (have them disconnect
2263 // because they lost all their requests or because their score isn't good)
2264 // then they would disconnect organically, report their new state and then
2265 // disconnect the channel.
2266 if (nai.networkInfo.isConnected()) {
2267 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2268 null, null);
2269 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002270 final boolean wasDefault = isDefaultNetwork(nai);
2271 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002272 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002273 // Log default network disconnection before required book-keeping.
2274 // Let rematchAllNetworksAndRequests() below record a new default network event
2275 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2276 // whose timestamps tell how long it takes to recover a default network.
2277 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002278 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002279 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002280 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2281 // by other networks that are already connected. Perhaps that can be done by
2282 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2283 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002284 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002285 mKeepaliveTracker.handleStopAllKeepalives(nai,
2286 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002287 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2288 // Disable wakeup packet monitoring for each interface.
2289 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2290 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002291 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002292 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002293 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002294 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002295 // Remove the NetworkAgent, but don't mark the netId as
2296 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002297 mNetworkForNetId.remove(nai.network.netId);
2298 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002299 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002300 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2301 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002302 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2303 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2304 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002305 sendUpdatedScoreToFactories(request, 0);
2306 }
2307 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002308 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002309 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002310 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002311 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002312 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002313 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002314 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002315 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002316 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002317 if (nai.created) {
2318 // Tell netd to clean up the configuration for this network
2319 // (routing rules, DNS, etc).
2320 // This may be slow as it requires a lot of netd shelling out to ip and
2321 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2322 // after we've rematched networks with requests which should make a potential
2323 // fallback network the default or requested a new network from the
2324 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2325 // long time.
2326 try {
2327 mNetd.removeNetwork(nai.network.netId);
2328 } catch (Exception e) {
2329 loge("Exception removing network: " + e);
2330 }
2331 }
2332 synchronized (mNetworkForNetId) {
2333 mNetIdInUse.delete(nai.network.netId);
2334 }
2335 } else {
2336 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2337 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002338 }
2339 }
2340
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002341 // If this method proves to be too slow then we can maintain a separate
2342 // pendingIntent => NetworkRequestInfo map.
2343 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2344 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2345 Intent intent = pendingIntent.getIntent();
2346 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2347 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2348 if (existingPendingIntent != null &&
2349 existingPendingIntent.getIntent().filterEquals(intent)) {
2350 return entry.getValue();
2351 }
2352 }
2353 return null;
2354 }
2355
2356 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2357 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2358
2359 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2360 if (existingRequest != null) { // remove the existing request.
2361 if (DBG) log("Replacing " + existingRequest.request + " with "
2362 + nri.request + " because their intents matched.");
2363 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2364 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002365 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002366 }
2367
Erik Klineda4bfa82015-04-30 12:58:40 +09002368 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002369 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002370 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002371 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002372 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002373 if (nri.request.networkCapabilities.hasSignalStrength() &&
2374 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2375 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002376 }
2377 }
2378 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002379 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002380 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002381 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002382 }
2383 }
2384
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002385 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2386 int callingUid) {
2387 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2388 if (nri != null) {
2389 handleReleaseNetworkRequest(nri.request, callingUid);
2390 }
2391 }
2392
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002393 // Determines whether the network is the best (or could become the best, if it validated), for
2394 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2395 // on the value of reason:
2396 //
2397 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2398 // then it should be torn down.
2399 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2400 // then it should be lingered.
2401 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2402 final int numRequests;
2403 switch (reason) {
2404 case TEARDOWN:
2405 numRequests = nai.numRequestNetworkRequests();
2406 break;
2407 case LINGER:
2408 numRequests = nai.numForegroundNetworkRequests();
2409 break;
2410 default:
2411 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2412 return true;
2413 }
2414
2415 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002416 return false;
2417 }
Paul Jensene0988542015-06-25 15:30:08 -04002418 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002419 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2420 // Background requests don't affect lingering.
2421 continue;
2422 }
2423
Paul Jensene0988542015-06-25 15:30:08 -04002424 // If this Network is already the highest scoring Network for a request, or if
2425 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002426 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002427 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002428 // Note that this catches two important cases:
2429 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2430 // is currently satisfying the request. This is desirable when
2431 // cellular ends up validating but WiFi does not.
2432 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002433 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002434 // WiFi ends up validating and out scoring cellular.
2435 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2436 nai.getCurrentScoreAsValidated())) {
2437 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002438 }
2439 }
Paul Jensene0988542015-06-25 15:30:08 -04002440 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002441 }
2442
Erik Klineacdd6392016-07-07 16:50:58 +09002443 private NetworkRequestInfo getNriForAppRequest(
2444 NetworkRequest request, int callingUid, String requestedOperation) {
2445 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2446
Robert Greenwalt9258c642014-03-26 16:47:06 -07002447 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002448 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002449 log(String.format("UID %d attempted to %s for unowned request %s",
2450 callingUid, requestedOperation, nri));
2451 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002452 }
Erik Klineacdd6392016-07-07 16:50:58 +09002453 }
2454
2455 return nri;
2456 }
2457
Erik Kline57faba92015-11-25 12:49:38 +09002458 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002459 if (mNetworkRequests.get(nri.request) == null) {
2460 return;
Erik Kline57faba92015-11-25 12:49:38 +09002461 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002462 if (mNetworkForRequestId.get(nri.request.requestId) != null) {
2463 return;
2464 }
2465 if (VDBG || (DBG && nri.request.isRequest())) {
2466 log("releasing " + nri.request + " (timeout)");
2467 }
2468 handleRemoveNetworkRequest(nri);
2469 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002470 }
2471
Erik Klineacdd6392016-07-07 16:50:58 +09002472 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002473 final NetworkRequestInfo nri =
2474 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2475 if (nri == null) {
2476 return;
Erik Kline57faba92015-11-25 12:49:38 +09002477 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002478 if (VDBG || (DBG && nri.request.isRequest())) {
2479 log("releasing " + nri.request + " (release request)");
2480 }
2481 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002482 }
Erik Klineacdd6392016-07-07 16:50:58 +09002483
Hugo Benichidba33db2017-03-23 22:40:44 +09002484 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002485 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002486 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002487 synchronized (mUidToNetworkRequestCount) {
2488 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2489 if (requests < 1) {
2490 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2491 nri.mUid);
2492 } else if (requests == 1) {
2493 mUidToNetworkRequestCount.removeAt(
2494 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2495 } else {
2496 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2497 }
2498 }
2499 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2500 if (nri.request.isRequest()) {
2501 boolean wasKept = false;
2502 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2503 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002504 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002505 nai.removeRequest(nri.request.requestId);
2506 if (VDBG) {
2507 log(" Removing from current network " + nai.name() +
2508 ", leaving " + nai.numNetworkRequests() + " requests.");
2509 }
2510 // If there are still lingered requests on this network, don't tear it down,
2511 // but resume lingering instead.
2512 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002513 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002514 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2515 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002516 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002517 wasKept = true;
2518 }
2519 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002520 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2521 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002522 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002523 }
Erik Klineacdd6392016-07-07 16:50:58 +09002524 }
2525
2526 // TODO: remove this code once we know that the Slog.wtf is never hit.
2527 //
2528 // Find all networks that are satisfying this request and remove the request
2529 // from their request lists.
2530 // TODO - it's my understanding that for a request there is only a single
2531 // network satisfying it, so this loop is wasteful
2532 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2533 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2534 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2535 otherNai.name() + ", but mNetworkAgentInfos says " +
2536 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002537 }
2538 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002539
Erik Klineacdd6392016-07-07 16:50:58 +09002540 // Maintain the illusion. When this request arrived, we might have pretended
2541 // that a network connected to serve it, even though the network was already
2542 // connected. Now that this request has gone away, we might have to pretend
2543 // that the network disconnected. LegacyTypeTracker will generate that
2544 // phantom disconnect for this type.
2545 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2546 boolean doRemove = true;
2547 if (wasKept) {
2548 // check if any of the remaining requests for this network are for the
2549 // same legacy type - if so, don't remove the nai
2550 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2551 NetworkRequest otherRequest = nai.requestAt(i);
2552 if (otherRequest.legacyType == nri.request.legacyType &&
2553 otherRequest.isRequest()) {
2554 if (DBG) log(" still have other legacy request - leaving");
2555 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002556 }
2557 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002558 }
2559
Erik Klineacdd6392016-07-07 16:50:58 +09002560 if (doRemove) {
2561 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002562 }
2563 }
Erik Klineacdd6392016-07-07 16:50:58 +09002564
2565 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2566 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2567 nri.request);
2568 }
2569 } else {
2570 // listens don't have a singular affectedNetwork. Check all networks to see
2571 // if this listen request applies and remove it.
2572 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2573 nai.removeRequest(nri.request.requestId);
2574 if (nri.request.networkCapabilities.hasSignalStrength() &&
2575 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2576 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2577 }
2578 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002579 }
2580 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002581
Lorenzo Colitti18660282016-07-04 12:55:44 +09002582 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002583 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2584 enforceConnectivityInternalPermission();
2585 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002586 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002587 }
2588
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002589 @Override
2590 public void setAvoidUnvalidated(Network network) {
2591 enforceConnectivityInternalPermission();
2592 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2593 }
2594
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002595 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2596 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2597 " accept=" + accept + " always=" + always);
2598
2599 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2600 if (nai == null) {
2601 // Nothing to do.
2602 return;
2603 }
2604
2605 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002606 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002607 return;
2608 }
2609
2610 if (!nai.networkMisc.explicitlySelected) {
2611 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2612 }
2613
2614 if (accept != nai.networkMisc.acceptUnvalidated) {
2615 int oldScore = nai.getCurrentScore();
2616 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002617 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002618 sendUpdatedScoreToFactories(nai);
2619 }
2620
2621 if (always) {
2622 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002623 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002624 }
2625
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002626 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002627 // Tell the NetworkAgent to not automatically reconnect to the network.
2628 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2629 // Teardown the nework.
2630 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002631 }
2632
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002633 }
2634
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002635 private void handleSetAvoidUnvalidated(Network network) {
2636 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2637 if (nai == null || nai.lastValidated) {
2638 // Nothing to do. The network either disconnected or revalidated.
2639 return;
2640 }
2641 if (!nai.avoidUnvalidated) {
2642 int oldScore = nai.getCurrentScore();
2643 nai.avoidUnvalidated = true;
2644 rematchAllNetworksAndRequests(nai, oldScore);
2645 sendUpdatedScoreToFactories(nai);
2646 }
2647 }
2648
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002649 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002650 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002651 mHandler.sendMessageDelayed(
2652 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2653 PROMPT_UNVALIDATED_DELAY_MS);
2654 }
2655
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002656 @Override
2657 public void startCaptivePortalApp(Network network) {
2658 enforceConnectivityInternalPermission();
2659 mHandler.post(() -> {
2660 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2661 if (nai == null) return;
2662 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2663 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2664 });
2665 }
2666
Hugo Benichic8e9e122016-09-14 23:23:08 +00002667 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002668 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002669 }
2670
Erik Kline065ab6e2016-10-02 18:02:14 +09002671 private void rematchForAvoidBadWifiUpdate() {
2672 rematchAllNetworksAndRequests(null, 0);
2673 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2674 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2675 sendUpdatedScoreToFactories(nai);
2676 }
2677 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002678 }
2679
Erik Kline065ab6e2016-10-02 18:02:14 +09002680 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002681 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002682 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002683 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002684 if (!configRestrict) {
2685 pw.println("Bad Wi-Fi avoidance: unrestricted");
2686 return;
2687 }
2688
2689 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2690 pw.increaseIndent();
2691 pw.println("Config restrict: " + configRestrict);
2692
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002693 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002694 String description;
2695 // Can't use a switch statement because strings are legal case labels, but null is not.
2696 if ("0".equals(value)) {
2697 description = "get stuck";
2698 } else if (value == null) {
2699 description = "prompt";
2700 } else if ("1".equals(value)) {
2701 description = "avoid";
2702 } else {
2703 description = value + " (?)";
2704 }
2705 pw.println("User setting: " + description);
2706 pw.println("Network overrides:");
2707 pw.increaseIndent();
2708 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2709 if (nai.avoidUnvalidated) {
2710 pw.println(nai.name());
2711 }
2712 }
2713 pw.decreaseIndent();
2714 pw.decreaseIndent();
2715 }
2716
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002717 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2718 final String action;
2719 switch (type) {
2720 case NO_INTERNET:
2721 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2722 break;
2723 case LOST_INTERNET:
2724 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2725 break;
2726 default:
2727 Slog.wtf(TAG, "Unknown notification type " + type);
2728 return;
2729 }
2730
2731 Intent intent = new Intent(action);
2732 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2733 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2734 intent.setClassName("com.android.settings",
2735 "com.android.settings.wifi.WifiNoInternetDialog");
2736
2737 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2738 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2739 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2740 }
2741
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002742 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002743 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002744 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2745
2746 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2747 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002748 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002749 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002750 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2751 return;
2752 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002753 showValidationNotification(nai, NotificationType.NO_INTERNET);
2754 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002755
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002756 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2757 NetworkCapabilities nc = nai.networkCapabilities;
2758 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002759
Erik Kline065ab6e2016-10-02 18:02:14 +09002760 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002761 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002762 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2763 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002764 }
2765
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002766 @Override
2767 public int getMultipathPreference(Network network) {
2768 enforceAccessPermission();
2769
2770 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2771 if (nai != null && !nai.networkInfo.isMetered()) {
2772 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2773 }
2774
2775 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2776 }
2777
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002778 private class InternalHandler extends Handler {
2779 public InternalHandler(Looper looper) {
2780 super(looper);
2781 }
2782
2783 @Override
2784 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002785 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002786 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002787 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002788 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002789 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002790 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002791 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002792 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002793 break;
2794 }
Jason Monkdecd2952013-10-10 14:02:51 -04002795 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002796 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002797 break;
2798 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002799 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002800 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2801 break;
2802 }
2803 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2804 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002805 break;
2806 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002807 case EVENT_REGISTER_NETWORK_AGENT: {
2808 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2809 break;
2810 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002811 case EVENT_REGISTER_NETWORK_REQUEST:
2812 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002813 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002814 break;
2815 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002816 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2817 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002818 handleRegisterNetworkRequestWithIntent(msg);
2819 break;
2820 }
Erik Kline57faba92015-11-25 12:49:38 +09002821 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2822 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2823 handleTimedOutNetworkRequest(nri);
2824 break;
2825 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002826 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2827 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2828 break;
2829 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002830 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002831 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002832 break;
2833 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002834 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002835 Network network = (Network) msg.obj;
2836 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002837 break;
2838 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002839 case EVENT_SET_AVOID_UNVALIDATED: {
2840 handleSetAvoidUnvalidated((Network) msg.obj);
2841 break;
2842 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002843 case EVENT_PROMPT_UNVALIDATED: {
2844 handlePromptUnvalidated((Network) msg.obj);
2845 break;
2846 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002847 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2848 handleMobileDataAlwaysOn();
2849 break;
2850 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002851 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2852 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2853 mKeepaliveTracker.handleStartKeepalive(msg);
2854 break;
2855 }
2856 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2857 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2858 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2859 int slot = msg.arg1;
2860 int reason = msg.arg2;
2861 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2862 break;
2863 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002864 case EVENT_SYSTEM_READY: {
2865 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2866 nai.networkMonitor.systemReady = true;
2867 }
2868 break;
2869 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002870 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002871 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002872 break;
2873 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002874 }
2875 }
2876 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002877
2878 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002879 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002880 public int tether(String iface, String callerPkg) {
2881 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002882 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002883 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002884 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002885 } else {
2886 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2887 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002888 }
2889
2890 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002891 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002892 public int untether(String iface, String callerPkg) {
2893 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002894
2895 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002896 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002897 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002898 } else {
2899 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2900 }
2901 }
2902
2903 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002904 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002905 public int getLastTetherError(String iface) {
2906 enforceTetherAccessPermission();
2907
2908 if (isTetheringSupported()) {
2909 return mTethering.getLastTetherError(iface);
2910 } else {
2911 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2912 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002913 }
2914
2915 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002916 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002917 public String[] getTetherableUsbRegexs() {
2918 enforceTetherAccessPermission();
2919 if (isTetheringSupported()) {
2920 return mTethering.getTetherableUsbRegexs();
2921 } else {
2922 return new String[0];
2923 }
2924 }
2925
Lorenzo Colitti18660282016-07-04 12:55:44 +09002926 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002927 public String[] getTetherableWifiRegexs() {
2928 enforceTetherAccessPermission();
2929 if (isTetheringSupported()) {
2930 return mTethering.getTetherableWifiRegexs();
2931 } else {
2932 return new String[0];
2933 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002934 }
2935
Lorenzo Colitti18660282016-07-04 12:55:44 +09002936 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002937 public String[] getTetherableBluetoothRegexs() {
2938 enforceTetherAccessPermission();
2939 if (isTetheringSupported()) {
2940 return mTethering.getTetherableBluetoothRegexs();
2941 } else {
2942 return new String[0];
2943 }
2944 }
2945
Lorenzo Colitti18660282016-07-04 12:55:44 +09002946 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002947 public int setUsbTethering(boolean enable, String callerPkg) {
2948 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002949 if (isTetheringSupported()) {
2950 return mTethering.setUsbTethering(enable);
2951 } else {
2952 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2953 }
2954 }
2955
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002956 // TODO - move iface listing, queries, etc to new module
2957 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002958 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002959 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002960 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002961 return mTethering.getTetherableIfaces();
2962 }
2963
Lorenzo Colitti18660282016-07-04 12:55:44 +09002964 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002965 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002966 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002967 return mTethering.getTetheredIfaces();
2968 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002969
Lorenzo Colitti18660282016-07-04 12:55:44 +09002970 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002971 public String[] getTetheringErroredIfaces() {
2972 enforceTetherAccessPermission();
2973 return mTethering.getErroredIfaces();
2974 }
2975
Lorenzo Colitti18660282016-07-04 12:55:44 +09002976 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002977 public String[] getTetheredDhcpRanges() {
2978 enforceConnectivityInternalPermission();
2979 return mTethering.getTetheredDhcpRanges();
2980 }
2981
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002982 // if ro.tether.denied = true we default to no tethering
2983 // gservices could set the secure setting to 1 though to enable it on a build where it
2984 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002985 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002986 public boolean isTetheringSupported() {
2987 enforceTetherAccessPermission();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002988 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
2989 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
2990 Settings.Global.TETHER_SUPPORTED, defaultVal));
2991 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002992 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07002993
2994 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
2995 boolean adminUser = false;
2996 final long token = Binder.clearCallingIdentity();
2997 try {
2998 adminUser = mUserManager.isAdminUser();
2999 } finally {
3000 Binder.restoreCallingIdentity(token);
3001 }
3002
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003003 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08003004 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003005
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003006 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003007 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3008 String callerPkg) {
3009 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003010 if (!isTetheringSupported()) {
3011 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3012 return;
3013 }
3014 mTethering.startTethering(type, receiver, showProvisioningUi);
3015 }
3016
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003017 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003018 public void stopTethering(int type, String callerPkg) {
3019 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003020 mTethering.stopTethering(type);
3021 }
3022
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003023 // Called when we lose the default network and have no replacement yet.
3024 // This will automatically be cleared after X seconds or a new default network
3025 // becomes CONNECTED, whichever happens first. The timer is started by the
3026 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003027 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003028 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003029 if (mNetTransitionWakeLock.isHeld()) {
3030 return;
3031 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003032 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003033 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3034 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003035 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003036 mWakelockLogs.log("ACQUIRE for " + forWhom);
3037 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3038 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003039 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003040
Hugo Benichi4c31b342017-03-30 23:18:10 +09003041 // Called when we gain a new default network to release the network transition wakelock in a
3042 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3043 // message is cancelled.
3044 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003045 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003046 if (!mNetTransitionWakeLock.isHeld()) {
3047 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003048 }
3049 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003050 // Cancel self timeout on wakelock hold.
3051 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3052 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3053 mHandler.sendMessageDelayed(msg, 1000);
3054 }
3055
3056 // Called when either message of ensureNetworkTransitionWakelock or
3057 // scheduleReleaseNetworkTransitionWakelock is processed.
3058 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3059 String event = eventName(eventId);
3060 synchronized (this) {
3061 if (!mNetTransitionWakeLock.isHeld()) {
3062 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3063 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3064 return;
3065 }
3066 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003067 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3068 mTotalWakelockDurationMs += lockDuration;
3069 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3070 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003071 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003072 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003073 }
3074
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003075 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003076 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003077 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003078 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003079 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003080 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003081 }
3082
Lorenzo Colitti18660282016-07-04 12:55:44 +09003083 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003084 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003085 enforceAccessPermission();
3086 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003087 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003088 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003089 mHandler.sendMessage(
3090 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3091 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003092
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003093 private void handleReportNetworkConnectivity(
3094 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003095 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003096 if (network == null) {
3097 nai = getDefaultNetwork();
3098 } else {
3099 nai = getNetworkAgentInfoForNetwork(network);
3100 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003101 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3102 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3103 return;
3104 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003105 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003106 if (hasConnectivity == nai.lastValidated) {
3107 return;
3108 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003109 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003110 int netid = nai.network.netId;
3111 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003112 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003113 // Validating a network that has not yet connected could result in a call to
3114 // rematchNetworkAndRequests() which is not meant to work on such networks.
3115 if (!nai.everConnected) {
3116 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003117 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003118 LinkProperties lp = getLinkProperties(nai);
3119 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3120 return;
3121 }
3122 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003123 }
3124
Paul Jensencee9b512015-05-06 07:32:40 -04003125 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003126 // this information is already available as a world read/writable jvm property
3127 // so this API change wouldn't have a benifit. It also breaks the passing
3128 // of proxy info to all the JVMs.
3129 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003130 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003131 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003132 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3133 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003134 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003135 }
3136
Lorenzo Colitti18660282016-07-04 12:55:44 +09003137 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003138 public ProxyInfo getProxyForNetwork(Network network) {
3139 if (network == null) return getDefaultProxy();
3140 final ProxyInfo globalProxy = getGlobalProxy();
3141 if (globalProxy != null) return globalProxy;
3142 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3143 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3144 // caller may not have.
3145 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3146 if (nai == null) return null;
3147 synchronized (nai) {
3148 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3149 if (proxyInfo == null) return null;
3150 return new ProxyInfo(proxyInfo);
3151 }
3152 }
3153
Paul Jensene0bef712014-12-10 15:12:18 -05003154 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3155 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3156 // proxy is null then there is no proxy in place).
3157 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3158 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3159 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3160 proxy = null;
3161 }
3162 return proxy;
3163 }
3164
3165 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3166 // better for determining if a new proxy broadcast is necessary:
3167 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3168 // avoid unnecessary broadcasts.
3169 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3170 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3171 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3172 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3173 // all set.
3174 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3175 a = canonicalizeProxyInfo(a);
3176 b = canonicalizeProxyInfo(b);
3177 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3178 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3179 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3180 }
3181
Jason Monk207900c2014-04-25 15:00:09 -04003182 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003183 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003184
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003185 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003186 if (proxyProperties == mGlobalProxy) return;
3187 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3188 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3189
3190 String host = "";
3191 int port = 0;
3192 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003193 String pacFileUrl = "";
3194 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003195 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003196 if (!proxyProperties.isValid()) {
3197 if (DBG)
3198 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3199 return;
3200 }
Jason Monk207900c2014-04-25 15:00:09 -04003201 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003202 host = mGlobalProxy.getHost();
3203 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003204 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003205 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003206 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003207 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003208 } else {
3209 mGlobalProxy = null;
3210 }
3211 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003212 final long token = Binder.clearCallingIdentity();
3213 try {
3214 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3215 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3216 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3217 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003218 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003219 } finally {
3220 Binder.restoreCallingIdentity(token);
3221 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003222
Jason Monkcf0f97a2014-10-02 15:39:38 -04003223 if (mGlobalProxy == null) {
3224 proxyProperties = mDefaultProxy;
3225 }
3226 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003227 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003228 }
3229
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003230 private void loadGlobalProxy() {
3231 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003232 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3233 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3234 String exclList = Settings.Global.getString(res,
3235 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003236 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3237 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003238 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003239 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003240 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003241 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003242 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003243 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003244 if (!proxyProperties.isValid()) {
3245 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3246 return;
3247 }
3248
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003249 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003250 mGlobalProxy = proxyProperties;
3251 }
3252 }
3253 }
3254
Jason Monk207900c2014-04-25 15:00:09 -04003255 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003256 // this information is already available as a world read/writable jvm property
3257 // so this API change wouldn't have a benifit. It also breaks the passing
3258 // of proxy info to all the JVMs.
3259 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003260 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003261 return mGlobalProxy;
3262 }
3263 }
3264
Jason Monk207900c2014-04-25 15:00:09 -04003265 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003266 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003267 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003268 proxy = null;
3269 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003270 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003271 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003272 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003273 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003274 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3275 return;
3276 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003277
3278 // This call could be coming from the PacManager, containing the port of the local
3279 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3280 // global (to get the correct local port), and send a broadcast.
3281 // TODO: Switch PacManager to have its own message to send back rather than
3282 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003283 if ((mGlobalProxy != null) && (proxy != null)
3284 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003285 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3286 mGlobalProxy = proxy;
3287 sendProxyBroadcast(mGlobalProxy);
3288 return;
3289 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003290 mDefaultProxy = proxy;
3291
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003292 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003293 if (!mDefaultProxyDisabled) {
3294 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003295 }
3296 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003297 }
3298
Paul Jensene0bef712014-12-10 15:12:18 -05003299 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3300 // This method gets called when any network changes proxy, but the broadcast only ever contains
3301 // the default proxy (even if it hasn't changed).
3302 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3303 // world where an app might be bound to a non-default network.
3304 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3305 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3306 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3307
3308 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3309 sendProxyBroadcast(getDefaultProxy());
3310 }
3311 }
3312
Robert Greenwalt434203a2010-10-11 16:00:27 -07003313 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003314 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3315 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003316 if (!TextUtils.isEmpty(proxy)) {
3317 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003318 if (data.length == 0) {
3319 return;
3320 }
3321
Robert Greenwalt434203a2010-10-11 16:00:27 -07003322 String proxyHost = data[0];
3323 int proxyPort = 8080;
3324 if (data.length > 1) {
3325 try {
3326 proxyPort = Integer.parseInt(data[1]);
3327 } catch (NumberFormatException e) {
3328 return;
3329 }
3330 }
Jason Monk207900c2014-04-25 15:00:09 -04003331 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003332 setGlobalProxy(p);
3333 }
3334 }
3335
Jason Monk207900c2014-04-25 15:00:09 -04003336 private void sendProxyBroadcast(ProxyInfo proxy) {
3337 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003338 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003339 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003340 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003341 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3342 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003343 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003344 final long ident = Binder.clearCallingIdentity();
3345 try {
3346 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3347 } finally {
3348 Binder.restoreCallingIdentity(ident);
3349 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003350 }
3351
3352 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003353 final private HashMap<Uri, Integer> mUriEventMap;
3354 final private Context mContext;
3355 final private Handler mHandler;
3356
3357 SettingsObserver(Context context, Handler handler) {
3358 super(null);
3359 mUriEventMap = new HashMap<Uri, Integer>();
3360 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003361 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003362 }
3363
Erik Klineda4bfa82015-04-30 12:58:40 +09003364 void observe(Uri uri, int what) {
3365 mUriEventMap.put(uri, what);
3366 final ContentResolver resolver = mContext.getContentResolver();
3367 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003368 }
3369
3370 @Override
3371 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003372 Slog.wtf(TAG, "Should never be reached.");
3373 }
3374
3375 @Override
3376 public void onChange(boolean selfChange, Uri uri) {
3377 final Integer what = mUriEventMap.get(uri);
3378 if (what != null) {
3379 mHandler.obtainMessage(what.intValue()).sendToTarget();
3380 } else {
3381 loge("No matching event to send for URI=" + uri);
3382 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003383 }
3384 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003385
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003386 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003387 Slog.d(TAG, s);
3388 }
3389
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003390 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003391 Slog.e(TAG, s);
3392 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003393
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003394 private static void loge(String s, Throwable t) {
3395 Slog.e(TAG, s, t);
3396 }
3397
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003398 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003399 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003400 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3401 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3402 *
3403 * @param oldPackage Package name of the application which currently controls VPN, which will
3404 * be replaced. If there is no such application, this should should either be
3405 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3406 * @param newPackage Package name of the application which should gain control of VPN, or
3407 * {@code null} to disable.
3408 * @param userId User for whom to prepare the new VPN.
3409 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003410 * @hide
3411 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003412 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003413 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3414 int userId) {
3415 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003416 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003417
Hugo Benichi20035e02017-04-26 14:53:28 +09003418 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003419 Vpn vpn = mVpns.get(userId);
3420 if (vpn != null) {
3421 return vpn.prepare(oldPackage, newPackage);
3422 } else {
3423 return false;
3424 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003425 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003426 }
3427
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003428 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003429 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3430 * This method is used by system-privileged apps.
3431 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3432 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3433 *
3434 * @param packageName The package for which authorization state should change.
3435 * @param userId User for whom {@code packageName} is installed.
3436 * @param authorized {@code true} if this app should be able to start a VPN connection without
3437 * explicit user approval, {@code false} if not.
3438 *
Jeff Davidson05542602014-08-11 14:07:27 -07003439 * @hide
3440 */
3441 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003442 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3443 enforceCrossUserPermission(userId);
3444
Hugo Benichi20035e02017-04-26 14:53:28 +09003445 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003446 Vpn vpn = mVpns.get(userId);
3447 if (vpn != null) {
3448 vpn.setPackageAuthorization(packageName, authorized);
3449 }
Jeff Davidson05542602014-08-11 14:07:27 -07003450 }
3451 }
3452
3453 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003454 * Configure a TUN interface and return its file descriptor. Parameters
3455 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003456 * and not available in ConnectivityManager. Permissions are checked in
3457 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003458 * @hide
3459 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003460 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003461 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003462 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003463 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003464 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003465 return mVpns.get(user).establish(config);
3466 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003467 }
3468
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003469 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003470 * Start legacy VPN, controlling native daemons as needed. Creates a
3471 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003472 */
3473 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003474 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003475 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003476 final LinkProperties egress = getActiveLinkProperties();
3477 if (egress == null) {
3478 throw new IllegalStateException("Missing active network connection");
3479 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003480 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003481 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003482 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3483 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003484 }
3485
3486 /**
3487 * Return the information of the ongoing legacy VPN. This method is used
3488 * by VpnSettings and not available in ConnectivityManager. Permissions
3489 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003490 */
3491 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003492 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3493 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003494
Hugo Benichi20035e02017-04-26 14:53:28 +09003495 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003496 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003497 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003498 }
3499
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003500 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003501 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3502 * and not available in ConnectivityManager.
3503 */
3504 @Override
3505 public VpnInfo[] getAllVpnInfo() {
3506 enforceConnectivityInternalPermission();
3507 if (mLockdownEnabled) {
3508 return new VpnInfo[0];
3509 }
3510
Hugo Benichi20035e02017-04-26 14:53:28 +09003511 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003512 List<VpnInfo> infoList = new ArrayList<>();
3513 for (int i = 0; i < mVpns.size(); i++) {
3514 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3515 if (info != null) {
3516 infoList.add(info);
3517 }
3518 }
3519 return infoList.toArray(new VpnInfo[infoList.size()]);
3520 }
3521 }
3522
3523 /**
3524 * @return VPN information for accounting, or null if we can't retrieve all required
3525 * information, e.g primary underlying iface.
3526 */
3527 @Nullable
3528 private VpnInfo createVpnInfo(Vpn vpn) {
3529 VpnInfo info = vpn.getVpnInfo();
3530 if (info == null) {
3531 return null;
3532 }
3533 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3534 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3535 // the underlyingNetworks list.
3536 if (underlyingNetworks == null) {
3537 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3538 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3539 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3540 }
3541 } else if (underlyingNetworks.length > 0) {
3542 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3543 if (linkProperties != null) {
3544 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3545 }
3546 }
3547 return info.primaryUnderlyingIface == null ? null : info;
3548 }
3549
3550 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003551 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3552 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003553 * Permissions are checked in Vpn class.
3554 * @hide
3555 */
3556 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003557 public VpnConfig getVpnConfig(int userId) {
3558 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003559 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003560 Vpn vpn = mVpns.get(userId);
3561 if (vpn != null) {
3562 return vpn.getVpnConfig();
3563 } else {
3564 return null;
3565 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003566 }
3567 }
3568
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003569 @Override
3570 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003571 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3572 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3573 return false;
3574 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003575
3576 // Tear down existing lockdown if profile was removed
3577 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3578 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003579 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3580 if (profileTag == null) {
3581 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3582 return false;
3583 }
3584 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003585 final VpnProfile profile = VpnProfile.decode(
3586 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003587 if (profile == null) {
3588 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3589 setLockdownTracker(null);
3590 return true;
3591 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003592 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003593 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003594 Vpn vpn = mVpns.get(user);
3595 if (vpn == null) {
3596 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3597 return false;
3598 }
3599 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003600 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003601 } else {
3602 setLockdownTracker(null);
3603 }
3604
3605 return true;
3606 }
3607
3608 /**
3609 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3610 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3611 */
3612 private void setLockdownTracker(LockdownVpnTracker tracker) {
3613 // Shutdown any existing tracker
3614 final LockdownVpnTracker existing = mLockdownTracker;
3615 mLockdownTracker = null;
3616 if (existing != null) {
3617 existing.shutdown();
3618 }
3619
Robin Leec3736bc2017-03-10 16:19:54 +00003620 if (tracker != null) {
3621 mLockdownTracker = tracker;
3622 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003623 }
3624 }
3625
3626 private void throwIfLockdownEnabled() {
3627 if (mLockdownEnabled) {
3628 throw new IllegalStateException("Unavailable in lockdown mode");
3629 }
3630 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003631
Robin Lee244ce8e2016-01-05 18:03:46 +00003632 /**
Robin Lee17e61832016-05-09 13:46:28 +01003633 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3634 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003635 *
Robin Lee17e61832016-05-09 13:46:28 +01003636 * @return {@code true} if the service was started, the service was already connected, or there
3637 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003638 */
Robin Lee17e61832016-05-09 13:46:28 +01003639 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003640 synchronized (mVpns) {
3641 Vpn vpn = mVpns.get(userId);
3642 if (vpn == null) {
3643 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3644 // exists already.
3645 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3646 return false;
3647 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003648
Robin Lee812800c2016-05-13 15:38:08 +01003649 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003650 }
3651 }
3652
3653 @Override
Charles Hea0a87e82017-05-15 17:07:18 +01003654 public boolean isAlwaysOnVpnPackageSupported(int userId, String packageName) {
3655 enforceSettingsPermission();
3656 enforceCrossUserPermission(userId);
3657
3658 synchronized (mVpns) {
3659 Vpn vpn = mVpns.get(userId);
3660 if (vpn == null) {
3661 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3662 return false;
3663 }
3664 return vpn.isAlwaysOnPackageSupported(packageName);
3665 }
3666 }
3667
3668 @Override
Robin Leedc679712016-05-03 13:23:03 +01003669 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003670 enforceConnectivityInternalPermission();
3671 enforceCrossUserPermission(userId);
3672
3673 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3674 if (LockdownVpnTracker.isEnabled()) {
3675 return false;
3676 }
3677
Robin Lee244ce8e2016-01-05 18:03:46 +00003678 synchronized (mVpns) {
3679 Vpn vpn = mVpns.get(userId);
3680 if (vpn == null) {
3681 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3682 return false;
3683 }
Robin Lee17e61832016-05-09 13:46:28 +01003684 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003685 return false;
3686 }
Robin Lee17e61832016-05-09 13:46:28 +01003687 if (!startAlwaysOnVpn(userId)) {
3688 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003689 return false;
3690 }
3691 }
3692 return true;
3693 }
3694
3695 @Override
3696 public String getAlwaysOnVpnPackage(int userId) {
3697 enforceConnectivityInternalPermission();
3698 enforceCrossUserPermission(userId);
3699
3700 synchronized (mVpns) {
3701 Vpn vpn = mVpns.get(userId);
3702 if (vpn == null) {
3703 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3704 return null;
3705 }
3706 return vpn.getAlwaysOnPackage();
3707 }
3708 }
3709
Wink Savilleab9321d2013-06-29 21:10:57 -07003710 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003711 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003712 // TODO: Remove? Any reason to trigger a provisioning check?
3713 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003714 }
3715
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003716 /** Location to an updatable file listing carrier provisioning urls.
3717 * An example:
3718 *
3719 * <?xml version="1.0" encoding="utf-8"?>
3720 * <provisioningUrls>
3721 * <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 -07003722 * </provisioningUrls>
3723 */
3724 private static final String PROVISIONING_URL_PATH =
3725 "/data/misc/radio/provisioning_urls.xml";
3726 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003727
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003728 /** XML tag for root element. */
3729 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3730 /** XML tag for individual url */
3731 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003732 /** XML attribute for mcc */
3733 private static final String ATTR_MCC = "mcc";
3734 /** XML attribute for mnc */
3735 private static final String ATTR_MNC = "mnc";
3736
Paul Jensen434dde82015-06-11 09:43:30 -04003737 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003738 FileReader fileReader = null;
3739 XmlPullParser parser = null;
3740 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003741
3742 try {
3743 fileReader = new FileReader(mProvisioningUrlFile);
3744 parser = Xml.newPullParser();
3745 parser.setInput(fileReader);
3746 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3747
3748 while (true) {
3749 XmlUtils.nextElement(parser);
3750
3751 String element = parser.getName();
3752 if (element == null) break;
3753
Paul Jensen434dde82015-06-11 09:43:30 -04003754 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003755 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3756 try {
3757 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3758 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3759 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3760 parser.next();
3761 if (parser.getEventType() == XmlPullParser.TEXT) {
3762 return parser.getText();
3763 }
3764 }
3765 }
3766 } catch (NumberFormatException e) {
3767 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3768 }
3769 }
3770 }
3771 return null;
3772 } catch (FileNotFoundException e) {
3773 loge("Carrier Provisioning Urls file not found");
3774 } catch (XmlPullParserException e) {
3775 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3776 } catch (IOException e) {
3777 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3778 } finally {
3779 if (fileReader != null) {
3780 try {
3781 fileReader.close();
3782 } catch (IOException e) {}
3783 }
3784 }
3785 return null;
3786 }
3787
Wink Saville42d4f082013-07-20 20:31:59 -07003788 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003789 public String getMobileProvisioningUrl() {
3790 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003791 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003792 if (TextUtils.isEmpty(url)) {
3793 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003794 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003795 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003796 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003797 }
Wink Saville8cf35602013-07-10 23:00:07 -07003798 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003799 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003800 String phoneNumber = mTelephonyManager.getLine1Number();
3801 if (TextUtils.isEmpty(phoneNumber)) {
3802 phoneNumber = "0000000000";
3803 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003804 url = String.format(url,
3805 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3806 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003807 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003808 }
3809
Wink Savilleab9321d2013-06-29 21:10:57 -07003810 return url;
3811 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003812
Wink Saville948282b2013-08-29 08:55:16 -07003813 @Override
3814 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003815 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003816 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003817 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3818 return;
3819 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003820 final long ident = Binder.clearCallingIdentity();
3821 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003822 // Concatenate the range of types onto the range of NetIDs.
3823 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3824 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003825 } finally {
3826 Binder.restoreCallingIdentity(ident);
3827 }
Wink Saville948282b2013-08-29 08:55:16 -07003828 }
Wink Saville7788c612013-08-29 14:57:08 -07003829
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003830 @Override
3831 public void setAirplaneMode(boolean enable) {
3832 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003833 final long ident = Binder.clearCallingIdentity();
3834 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003835 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003836 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003837 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3838 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003839 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003840 } finally {
3841 Binder.restoreCallingIdentity(ident);
3842 }
3843 }
3844
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003845 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003846 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003847 Vpn userVpn = mVpns.get(userId);
3848 if (userVpn != null) {
3849 loge("Starting user already has a VPN");
3850 return;
3851 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003852 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003853 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003854 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003855 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3856 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003857 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003858 }
3859
3860 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003861 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003862 Vpn userVpn = mVpns.get(userId);
3863 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003864 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003865 return;
3866 }
Robin Lee17e61832016-05-09 13:46:28 +01003867 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003868 mVpns.delete(userId);
3869 }
3870 }
3871
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003872 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003873 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003874 final int vpnsSize = mVpns.size();
3875 for (int i = 0; i < vpnsSize; i++) {
3876 Vpn vpn = mVpns.valueAt(i);
3877 vpn.onUserAdded(userId);
3878 }
3879 }
3880 }
3881
3882 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003883 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003884 final int vpnsSize = mVpns.size();
3885 for (int i = 0; i < vpnsSize; i++) {
3886 Vpn vpn = mVpns.valueAt(i);
3887 vpn.onUserRemoved(userId);
3888 }
3889 }
3890 }
3891
Robin Lee89e7a692016-02-29 14:38:17 +00003892 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003893 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3894 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3895 updateLockdownVpn();
3896 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003897 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003898 }
3899 }
3900
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003901 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3902 @Override
3903 public void onReceive(Context context, Intent intent) {
3904 final String action = intent.getAction();
3905 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3906 if (userId == UserHandle.USER_NULL) return;
3907
Robin Lee323f29d2016-05-04 16:38:06 +01003908 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003909 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003910 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003911 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003912 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3913 onUserAdded(userId);
3914 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3915 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003916 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3917 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003918 }
3919 }
3920 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003921
Robin Lee95204e02017-01-27 11:59:22 +00003922 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3923 @Override
3924 public void onReceive(Context context, Intent intent) {
3925 // Try creating lockdown tracker, since user present usually means
3926 // unlocked keystore.
3927 updateLockdownVpn();
3928 mContext.unregisterReceiver(this);
3929 }
3930 };
3931
Robert Greenwalta67be032014-05-16 15:49:14 -07003932 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3933 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003934 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3935 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003936
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003937 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3938 // Map from UID to number of NetworkRequests that UID has filed.
3939 @GuardedBy("mUidToNetworkRequestCount")
3940 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3941
Robert Greenwalta67be032014-05-16 15:49:14 -07003942 private static class NetworkFactoryInfo {
3943 public final String name;
3944 public final Messenger messenger;
3945 public final AsyncChannel asyncChannel;
3946
3947 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3948 this.name = name;
3949 this.messenger = messenger;
3950 this.asyncChannel = asyncChannel;
3951 }
3952 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003953
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003954 private void ensureNetworkRequestHasType(NetworkRequest request) {
3955 if (request.type == NetworkRequest.Type.NONE) {
3956 throw new IllegalArgumentException(
3957 "All NetworkRequests in ConnectivityService must have a type");
3958 }
3959 }
3960
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003961 /**
3962 * Tracks info about the requester.
3963 * Also used to notice when the calling process dies so we can self-expire
3964 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003965 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003966 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003967 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003968 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003969 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003970 final int mPid;
3971 final int mUid;
3972 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003973
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003974 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003975 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003976 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003977 mPendingIntent = pi;
3978 messenger = null;
3979 mBinder = null;
3980 mPid = getCallingPid();
3981 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003982 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003983 }
3984
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003985 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003986 super();
3987 messenger = m;
3988 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003989 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003990 mBinder = binder;
3991 mPid = getCallingPid();
3992 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003993 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003994 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003995
3996 try {
3997 mBinder.linkToDeath(this, 0);
3998 } catch (RemoteException e) {
3999 binderDied();
4000 }
4001 }
4002
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004003 private void enforceRequestCountLimit() {
4004 synchronized (mUidToNetworkRequestCount) {
4005 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
4006 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09004007 throw new ServiceSpecificException(
4008 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04004009 }
4010 mUidToNetworkRequestCount.put(mUid, networkRequests);
4011 }
4012 }
4013
Robert Greenwalt9258c642014-03-26 16:47:06 -07004014 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004015 if (mBinder != null) {
4016 mBinder.unlinkToDeath(this, 0);
4017 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004018 }
4019
4020 public void binderDied() {
4021 log("ConnectivityService NetworkRequestInfo binderDied(" +
4022 request + ", " + mBinder + ")");
4023 releaseNetworkRequest(request);
4024 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004025
4026 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004027 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004028 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004029 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004030 }
4031
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004032 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4033 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4034 if (badCapability != null) {
4035 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004036 }
4037 }
4038
Erik Kline9d598e12015-07-13 16:37:51 +09004039 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004040 final SortedSet<Integer> thresholds = new TreeSet();
4041 synchronized (nai) {
4042 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4043 if (nri.request.networkCapabilities.hasSignalStrength() &&
4044 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4045 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4046 }
4047 }
4048 }
Erik Kline9d598e12015-07-13 16:37:51 +09004049 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004050 }
4051
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004052 private void updateSignalStrengthThresholds(
4053 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4054 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004055 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004056 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4057
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004058 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004059 String detail;
4060 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4061 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4062 } else {
4063 detail = reason;
4064 }
4065 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4066 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4067 }
4068
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004069 nai.asyncChannel.sendMessage(
4070 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004071 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004072 }
4073
Etan Cohen859748f2017-04-03 17:42:34 -07004074 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4075 if (nc == null) {
4076 return;
4077 }
4078 NetworkSpecifier ns = nc.getNetworkSpecifier();
4079 if (ns == null) {
4080 return;
4081 }
4082 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4083 ns.assertValidFromUid(Binder.getCallingUid());
4084 }
4085
Robert Greenwalt9258c642014-03-26 16:47:06 -07004086 @Override
4087 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004088 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004089 final NetworkRequest.Type type = (networkCapabilities == null)
4090 ? NetworkRequest.Type.TRACK_DEFAULT
4091 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004092 // If the requested networkCapabilities is null, take them instead from
4093 // the default network request. This allows callers to keep track of
4094 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004095 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004096 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4097 enforceAccessPermission();
4098 } else {
4099 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4100 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004101 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4102 // of the app when the request is filed, but we never change the request if the app
4103 // changes network state. http://b/29964605
4104 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004105 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004106 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004107
Etan Cohenba07c8c2017-02-05 10:42:27 -08004108 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004109 throw new IllegalArgumentException("Bad timeout specified");
4110 }
Etan Cohen859748f2017-04-03 17:42:34 -07004111 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004112
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004113 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004114 nextNetworkRequestId(), type);
4115 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004116 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117
4118 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004119 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004120 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004121 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004122 }
4123 return networkRequest;
4124 }
4125
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004126 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004127 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004128 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004129 } else {
4130 enforceChangePermission();
4131 }
4132 }
4133
fenglub15e72b2015-03-20 11:29:56 -07004134 @Override
fengludb571472015-04-21 17:12:05 -07004135 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004136 enforceAccessPermission();
4137 NetworkAgentInfo nai = null;
4138 if (network == null) {
4139 return false;
4140 }
4141 synchronized (mNetworkForNetId) {
4142 nai = mNetworkForNetId.get(network.netId);
4143 }
4144 if (nai != null) {
4145 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4146 return true;
4147 }
4148 return false;
4149 }
4150
Felipe Lemeee27cab2016-06-20 16:36:29 -07004151 private boolean isSystem(int uid) {
4152 return uid < Process.FIRST_APPLICATION_UID;
4153 }
fenglub15e72b2015-03-20 11:29:56 -07004154
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004155 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004156 final int uid = Binder.getCallingUid();
4157 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004158 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004159 return;
4160 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004161 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4162 // Policy already enforced.
4163 return;
4164 }
4165 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4166 // If UID is restricted, don't allow them to bring up metered APNs.
4167 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004168 }
4169 }
4170
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 @Override
4172 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4173 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004174 checkNotNull(operation, "PendingIntent cannot be null.");
4175 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4176 enforceNetworkRequestPermissions(networkCapabilities);
4177 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004178 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004179 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004180
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004181 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004182 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4183 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004184 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004185 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4186 nri));
4187 return networkRequest;
4188 }
4189
Jeremy Joslin79294842014-12-03 17:15:28 -08004190 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4191 mHandler.sendMessageDelayed(
4192 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4193 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4194 }
4195
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004196 @Override
4197 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004198 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004199 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4200 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004201 }
4202
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004203 // In order to implement the compatibility measure for pre-M apps that call
4204 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4205 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4206 // This ensures it has permission to do so.
4207 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4208 if (nc == null) {
4209 return false;
4210 }
4211 int[] transportTypes = nc.getTransportTypes();
4212 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4213 return false;
4214 }
4215 try {
4216 mContext.enforceCallingOrSelfPermission(
4217 android.Manifest.permission.ACCESS_WIFI_STATE,
4218 "ConnectivityService");
4219 } catch (SecurityException e) {
4220 return false;
4221 }
4222 return true;
4223 }
4224
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 @Override
4226 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4227 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004228 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4229 enforceAccessPermission();
4230 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004231
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004232 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4233 if (!ConnectivityManager.checkChangePermission(mContext)) {
4234 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4235 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4236 // onLost and onAvailable callbacks when networks move in and out of the background.
4237 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4238 // can't request networks.
4239 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4240 }
Etan Cohen859748f2017-04-03 17:42:34 -07004241 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004242
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004243 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004244 NetworkRequest.Type.LISTEN);
4245 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004246 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004247
4248 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4249 return networkRequest;
4250 }
4251
4252 @Override
4253 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4254 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004255 checkNotNull(operation, "PendingIntent cannot be null.");
4256 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4257 enforceAccessPermission();
4258 }
Etan Cohen859748f2017-04-03 17:42:34 -07004259 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004260
Erik Kline7523eb32015-07-09 18:24:03 +09004261 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004262 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4263 NetworkRequest.Type.LISTEN);
4264 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004265 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004266
4267 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004268 }
4269
Erik Klineacdd6392016-07-07 16:50:58 +09004270 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004271 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004272 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004273 mHandler.sendMessage(mHandler.obtainMessage(
4274 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004275 }
4276
4277 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004278 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004279 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004280 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4281 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004282 }
4283
Robert Greenwalta67be032014-05-16 15:49:14 -07004284 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004285 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004286 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4287 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4288 }
4289
4290 @Override
4291 public void unregisterNetworkFactory(Messenger messenger) {
4292 enforceConnectivityInternalPermission();
4293 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4294 }
4295
4296 private void handleUnregisterNetworkFactory(Messenger messenger) {
4297 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4298 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004299 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004300 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004301 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004302 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004303 }
4304
Robert Greenwalt7b816022014-04-18 15:25:25 -07004305 /**
4306 * NetworkAgentInfo supporting a request by requestId.
4307 * These have already been vetted (their Capabilities satisfy the request)
4308 * and the are the highest scored network available.
4309 * the are keyed off the Requests requestId.
4310 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004311 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004312 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4313 new SparseArray<NetworkAgentInfo>();
4314
Paul Jensen31a94f42015-02-13 14:18:39 -05004315 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4316 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004317 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4318 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004319 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4320 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4321 // there may not be a strict 1:1 correlation between the two.
4322 @GuardedBy("mNetworkForNetId")
4323 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004324
Robert Greenwalt7b816022014-04-18 15:25:25 -07004325 // NetworkAgentInfo keyed off its connecting messenger
4326 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004327 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004328 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4329 new HashMap<Messenger, NetworkAgentInfo>();
4330
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004331 @GuardedBy("mBlockedAppUids")
4332 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4333
Paul Jensen2c311d62014-11-17 12:34:51 -05004334 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004335 private final NetworkRequest mDefaultRequest;
4336
Erik Klineda4bfa82015-04-30 12:58:40 +09004337 // Request used to optionally keep mobile data active even when higher
4338 // priority networks like Wi-Fi are active.
4339 private final NetworkRequest mDefaultMobileDataRequest;
4340
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004341 private NetworkAgentInfo getDefaultNetwork() {
4342 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4343 }
4344
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004345 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004346 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004347 }
4348
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004349 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4350 return nri.request.requestId == mDefaultRequest.requestId;
4351 }
4352
Paul Jensen31a94f42015-02-13 14:18:39 -05004353 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004354 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004355 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004356 enforceConnectivityInternalPermission();
4357
Rubin Xu1bb5c082017-09-05 18:40:49 +01004358 LinkProperties lp = new LinkProperties(linkProperties);
4359 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004360 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4361 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004362 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004363 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4364 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004365 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004366 synchronized (this) {
4367 nai.networkMonitor.systemReady = mSystemReady;
4368 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004369 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4370 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004371 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004372 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004373 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004374 }
4375
4376 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4377 if (VDBG) log("Got NetworkAgent Messenger");
4378 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004379 synchronized (mNetworkForNetId) {
4380 mNetworkForNetId.put(na.network.netId, na);
4381 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004382 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4383 NetworkInfo networkInfo = na.networkInfo;
4384 na.networkInfo = null;
4385 updateNetworkInfo(na, networkInfo);
4386 }
4387
4388 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4389 LinkProperties newLp = networkAgent.linkProperties;
4390 int netId = networkAgent.network.netId;
4391
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004392 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4393 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004394 if (networkAgent.clatd != null) {
4395 networkAgent.clatd.fixupLinkProperties(oldLp);
4396 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004397
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004398 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004399 updateMtu(newLp, oldLp);
4400 // TODO - figure out what to do for clat
4401// for (LinkProperties lp : newLp.getStackedLinks()) {
4402// updateMtu(lp, null);
4403// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004404 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004405
Erik Kline94887872016-04-05 13:30:49 +09004406 updateRoutes(newLp, oldLp, netId);
4407 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004408
Hugo Benichib577d652017-06-27 15:13:20 +09004409 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004410 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004411 if (isDefaultNetwork(networkAgent)) {
4412 handleApplyDefaultProxy(newLp.getHttpProxy());
4413 } else {
4414 updateProxy(newLp, oldLp, networkAgent);
4415 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004416 // TODO - move this check to cover the whole function
4417 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004418 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004419 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4420 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004421
4422 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004423 }
4424
Joel Scherpelz668370b2017-06-08 15:35:21 +09004425 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004426 // Marks are only available on WiFi interaces. Checking for
4427 // marks on unsupported interfaces is harmless.
4428 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4429 return;
4430 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004431
Joel Scherpelz668370b2017-06-08 15:35:21 +09004432 int mark = mContext.getResources().getInteger(
4433 com.android.internal.R.integer.config_networkWakeupPacketMark);
4434 int mask = mContext.getResources().getInteger(
4435 com.android.internal.R.integer.config_networkWakeupPacketMask);
4436
4437 // Mask/mark of zero will not detect anything interesting.
4438 // Don't install rules unless both values are nonzero.
4439 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004440 return;
4441 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004442
4443 final String prefix = "iface:" + iface;
4444 try {
4445 if (add) {
4446 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4447 } else {
4448 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4449 }
4450 } catch (Exception e) {
4451 loge("Exception modifying wakeup packet monitoring: " + e);
4452 }
4453
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004454 }
4455
4456 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4457 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004458 CompareResult<String> interfaceDiff = new CompareResult<String>(
4459 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4460 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004461 for (String iface : interfaceDiff.added) {
4462 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004463 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004464 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004465 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004466 } catch (Exception e) {
4467 loge("Exception adding interface: " + e);
4468 }
4469 }
4470 for (String iface : interfaceDiff.removed) {
4471 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004472 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004473 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004474 mNetd.removeInterfaceFromNetwork(iface, netId);
4475 } catch (Exception e) {
4476 loge("Exception removing interface: " + e);
4477 }
4478 }
4479 }
4480
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004481 /**
4482 * Have netd update routes from oldLp to newLp.
4483 * @return true if routes changed between oldLp and newLp
4484 */
4485 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004486 // Compare the route diff to determine which routes should be added and removed.
4487 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4488 oldLp != null ? oldLp.getAllRoutes() : null,
4489 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004490
4491 // add routes before removing old in case it helps with continuous connectivity
4492
4493 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4494 for (RouteInfo route : routeDiff.added) {
4495 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004496 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004497 try {
4498 mNetd.addRoute(netId, route);
4499 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004500 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4501 loge("Exception in addRoute for non-gateway: " + e);
4502 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004503 }
4504 }
4505 for (RouteInfo route : routeDiff.added) {
4506 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004507 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004508 try {
4509 mNetd.addRoute(netId, route);
4510 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004511 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4512 loge("Exception in addRoute for gateway: " + e);
4513 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004514 }
4515 }
4516
4517 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004518 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004519 try {
4520 mNetd.removeRoute(netId, route);
4521 } catch (Exception e) {
4522 loge("Exception in removeRoute: " + e);
4523 }
4524 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004525 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004526 }
Erik Kline41368502015-06-17 13:19:54 +09004527
Erik Kline94887872016-04-05 13:30:49 +09004528 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4529 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4530 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004531 }
Erik Kline94887872016-04-05 13:30:49 +09004532
4533 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004534 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004535 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004536 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004537 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4538 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004539 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004540 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004541 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4542 if (defaultNai != null && defaultNai.network.netId == netId) {
4543 setDefaultDnsSystemProperties(dnses);
4544 }
Erik Kline94887872016-04-05 13:30:49 +09004545 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004546 }
4547
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004548 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4549 int last = 0;
4550 for (InetAddress dns : dnses) {
4551 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004552 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004553 }
4554 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004555 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004556 }
4557 mNumDnsEntries = last;
4558 }
4559
Erik Kline4edba012017-04-07 15:29:29 +09004560 private void setNetDnsProperty(int which, String value) {
4561 final String key = "net.dns" + which;
4562 // Log and forget errors setting unsupported properties.
4563 try {
4564 mSystemProperties.set(key, value);
4565 } catch (Exception e) {
4566 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4567 }
4568 }
4569
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004570 private String getNetworkPermission(NetworkCapabilities nc) {
4571 // TODO: make these permission strings AIDL constants instead.
4572 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4573 return NetworkManagementService.PERMISSION_SYSTEM;
4574 }
4575 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4576 return NetworkManagementService.PERMISSION_NETWORK;
4577 }
4578 return null;
4579 }
4580
Paul Jensen3d194ea2015-06-16 14:27:36 -04004581 /**
4582 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4583 * augmented with any stateful capabilities implied from {@code networkAgent}
4584 * (e.g., validated status and captive portal status).
4585 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004586 * @param oldScore score of the network before any of the changes that prompted us
4587 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004588 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004589 * @param networkCapabilities the new network capabilities.
4590 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004591 private void updateCapabilities(
4592 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004593 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Hugo Benichia60c6ea2017-08-18 14:41:22 +09004594 if (nai.everConnected && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
4595 networkCapabilities)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004596 // TODO: consider not complaining when a network agent degrade its capabilities if this
4597 // does not cause any request (that is not a listen) currently matching that agent to
4598 // stop being matched by the updated agent.
Hugo Benichieae7a222017-07-25 11:40:56 +09004599 String diff = nai.networkCapabilities.describeImmutableDifferences(networkCapabilities);
4600 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004601 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004602 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004603 }
4604
Paul Jensen3d194ea2015-06-16 14:27:36 -04004605 // Don't modify caller's NetworkCapabilities.
4606 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004607 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004608 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4609 } else {
4610 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4611 }
Paul Jensene0988542015-06-25 15:30:08 -04004612 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004613 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4614 } else {
4615 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4616 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004617 if (nai.isBackgroundNetwork()) {
4618 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4619 } else {
4620 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4621 }
4622
4623 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4624
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004625 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4626 final String newPermission = getNetworkPermission(networkCapabilities);
4627 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004628 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004629 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004630 } catch (RemoteException e) {
4631 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004632 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004633 }
4634
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004635 final NetworkCapabilities prevNc = nai.networkCapabilities;
4636 synchronized (nai) {
4637 nai.networkCapabilities = networkCapabilities;
4638 }
4639 if (nai.getCurrentScore() == oldScore &&
4640 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4641 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4642 // the change we're processing can't affect any requests, it can only affect the listens
4643 // on this network. We might have been called by rematchNetworkAndRequests when a
4644 // network changed foreground state.
4645 processListenRequests(nai, true);
4646 } else {
4647 // If the requestable capabilities have changed or the score changed, we can't have been
4648 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004649 rematchAllNetworksAndRequests(nai, oldScore);
4650 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004651 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004652 }
4653
Hugo Benichief502882017-09-01 01:23:32 +00004654 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4655 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4656 // Ignore updates for disconnected networks
4657 return;
4658 }
Rubin Xu6c1f6fd2017-09-11 15:21:10 +01004659 // newLp is already a defensive copy.
4660 newLp.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004661 if (VDBG) {
4662 log("Update of LinkProperties for " + nai.name() +
4663 "; created=" + nai.created +
4664 "; everConnected=" + nai.everConnected);
4665 }
4666 LinkProperties oldLp = nai.linkProperties;
4667 synchronized (nai) {
4668 nai.linkProperties = newLp;
4669 }
4670 if (nai.everConnected) {
4671 updateLinkProperties(nai, oldLp);
4672 }
4673 }
4674
Paul Jensenc8b9a742014-09-30 15:37:41 -04004675 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004676 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4677 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004678 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004679 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004680 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4681 }
4682 }
4683
Robert Greenwalt7b816022014-04-18 15:25:25 -07004684 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4685 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004686 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004687 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4688 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004689 }
4690 }
4691
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004692 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4693 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004694 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004695 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004696 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4697 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004698 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004699 sendIntent(nri.mPendingIntent, intent);
4700 }
4701 // else not handled
4702 }
4703
4704 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4705 mPendingIntentWakeLock.acquire();
4706 try {
4707 if (DBG) log("Sending " + pendingIntent);
4708 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4709 } catch (PendingIntent.CanceledException e) {
4710 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4711 mPendingIntentWakeLock.release();
4712 releasePendingNetworkRequest(pendingIntent);
4713 }
4714 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4715 }
4716
4717 @Override
4718 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4719 String resultData, Bundle resultExtras) {
4720 if (DBG) log("Finished sending " + pendingIntent);
4721 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004722 // Release with a delay so the receiving client has an opportunity to put in its
4723 // own request.
4724 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004725 }
4726
Hugo Benichidba33db2017-03-23 22:40:44 +09004727 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004728 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004729 if (nri.messenger == null) {
4730 return; // Default request has no msgr
4731 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004732 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004733 // TODO: check if defensive copies of data is needed.
4734 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004735 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004736 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4737 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004738 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004739 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004740 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004741 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004742 break;
4743 }
4744 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004745 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004746 break;
4747 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004748 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004749 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004750 break;
4751 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004752 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004753 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004754 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004755 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004756 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004757 String notification = ConnectivityManager.getCallbackName(notificationType);
4758 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004759 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004760 nri.messenger.send(msg);
4761 } catch (RemoteException e) {
4762 // may occur naturally in the race of binder death.
4763 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4764 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004765 }
4766
Hugo Benichidba33db2017-03-23 22:40:44 +09004767 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4768 bundle.putParcelable(t.getClass().getSimpleName(), t);
4769 }
4770
Paul Jensenc8b9a742014-09-30 15:37:41 -04004771 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004772 if (nai.numRequestNetworkRequests() != 0) {
4773 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4774 NetworkRequest nr = nai.requestAt(i);
4775 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004776 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004777 loge("Dead network still had at least " + nr);
4778 break;
4779 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004780 }
4781 nai.asyncChannel.disconnect();
4782 }
4783
Robert Greenwalt7b816022014-04-18 15:25:25 -07004784 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4785 if (oldNetwork == null) {
4786 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4787 return;
4788 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004789 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004790
4791 // If we get here it means that the last linger timeout for this network expired. So there
4792 // must be no other active linger timers, and we must stop lingering.
4793 oldNetwork.clearLingerState();
4794
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004795 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004796 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004797 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004798 } else {
4799 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004800 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4801 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004802 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004803 }
4804
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004805 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004806 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004807 setupDataActivityTracking(newNetwork);
4808 try {
4809 mNetd.setDefaultNetId(newNetwork.network.netId);
4810 } catch (Exception e) {
4811 loge("Exception setting default network :" + e);
4812 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004813 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004814 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004815 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004816 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004817 }
4818
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004819 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004820 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4821 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4822 NetworkRequest nr = nri.request;
4823 if (!nr.isListen()) continue;
4824 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4825 nai.removeRequest(nri.request.requestId);
4826 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4827 }
4828 }
4829
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004830 if (capabilitiesChanged) {
4831 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4832 }
4833
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004834 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4835 NetworkRequest nr = nri.request;
4836 if (!nr.isListen()) continue;
4837 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4838 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004839 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004840 }
4841 }
4842 }
4843
Paul Jensen2161a8e2014-09-11 11:00:39 -04004844 // Handles a network appearing or improving its score.
4845 //
4846 // - Evaluates all current NetworkRequests that can be
4847 // satisfied by newNetwork, and reassigns to newNetwork
4848 // any such requests for which newNetwork is the best.
4849 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004850 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004851 // needed. A network is needed if it is the best network for
4852 // one or more NetworkRequests, or if it is a VPN.
4853 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004854 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004855 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004856 //
4857 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4858 // networks that have no chance (i.e. even if validated)
4859 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004860 //
4861 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4862 // it does not remove NetworkRequests that other Networks could better satisfy.
4863 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4864 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4865 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004866 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004867 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004868 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4869 // performed to tear down unvalidated networks that have no chance (i.e. even if
4870 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004871 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004872 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004873 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004874 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004875 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004876 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004877
4878 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4879 final int score = newNetwork.getCurrentScore();
4880
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004881 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004882
Paul Jensen2161a8e2014-09-11 11:00:39 -04004883 // Find and migrate to this Network any NetworkRequests for
4884 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004885 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004886 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004887 NetworkCapabilities nc = newNetwork.networkCapabilities;
4888 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004889 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004890 // Process requests in the first pass and listens in the second pass. This allows us to
4891 // change a network's capabilities depending on which requests it has. This is only
4892 // correct if the change in capabilities doesn't affect whether the network satisfies
4893 // requests or not, and doesn't affect the network's score.
4894 if (nri.request.isListen()) continue;
4895
Paul Jensencf4c2c62015-07-01 14:16:32 -04004896 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4897 final boolean satisfies = newNetwork.satisfies(nri.request);
4898 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004899 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004900 log("Network " + newNetwork.name() + " was already satisfying" +
4901 " request " + nri.request.requestId + ". No change.");
4902 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004903 keep = true;
4904 continue;
4905 }
4906
4907 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004908 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004909 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004910 // next check if it's better than any current network we're using for
4911 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004912 if (VDBG) {
4913 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004914 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004915 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004916 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004917 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004918 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004919 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004920 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004921 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004922 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004923 affectedNetworks.add(currentNetwork);
4924 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004925 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004926 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004927 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004928 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004929 if (!newNetwork.addRequest(nri.request)) {
4930 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4931 }
4932 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004933 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004934 // Tell NetworkFactories about the new score, so they can stop
4935 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004936 // TODO - this could get expensive if we have alot of requests for this
4937 // network. Think about if there is a way to reduce this. Push
4938 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004939 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004940 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004941 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004942 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004943 if (currentNetwork != null) {
4944 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4945 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004946 }
4947 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004948 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004949 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4950 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004951 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004952 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4953 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4954 // This means this code doesn't have to handle the case where "currentNetwork" no
4955 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4956 if (DBG) {
4957 log("Network " + newNetwork.name() + " stopped satisfying" +
4958 " request " + nri.request.requestId);
4959 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004960 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004961 if (currentNetwork == newNetwork) {
4962 mNetworkForRequestId.remove(nri.request.requestId);
4963 sendUpdatedScoreToFactories(nri.request, 0);
4964 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004965 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4966 newNetwork.name() +
4967 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004968 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004969 // TODO: Technically, sending CALLBACK_LOST here is
4970 // incorrect if there is a replacement network currently
4971 // connected that can satisfy nri, which is a request
4972 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004973 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4974 // so this code is only incorrect for a network that loses
4975 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004976 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004977 }
4978 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004979 if (isNewDefault) {
4980 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004981 makeDefault(newNetwork);
4982 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4983 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004984 // Have a new default network, release the transition wakelock in
4985 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004986 }
4987
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004988 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4989 Slog.wtf(TAG, String.format(
4990 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07004991 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004992 }
4993 if (newNetwork.getCurrentScore() != score) {
4994 Slog.wtf(TAG, String.format(
4995 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08004996 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004997 }
4998
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004999 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005000 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
5001 // If the network went from background to foreground or vice versa, we need to update
5002 // its foreground state. It is safe to do this after rematching the requests because
5003 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
5004 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09005005 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005006 } else {
5007 processListenRequests(newNetwork, false);
5008 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09005009
Paul Jensencf4c2c62015-07-01 14:16:32 -04005010 // do this after the default net is switched, but
5011 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09005012 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04005013
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005014 // Linger any networks that are no longer needed. This should be done after sending the
5015 // available callback for newNetwork.
5016 for (NetworkAgentInfo nai : affectedNetworks) {
5017 updateLingerState(nai, now);
5018 }
5019 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5020 // does not need to be done in any particular order.
5021 updateLingerState(newNetwork, now);
5022
Paul Jensencf4c2c62015-07-01 14:16:32 -04005023 if (isNewDefault) {
5024 // Maintain the illusion: since the legacy API only
5025 // understands one network at a time, we must pretend
5026 // that the current default network disconnected before
5027 // the new one connected.
5028 if (oldDefaultNetwork != null) {
5029 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5030 oldDefaultNetwork, true);
5031 }
5032 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5033 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5034 notifyLockdownVpn(newNetwork);
5035 }
5036
Robert Greenwalt7b816022014-04-18 15:25:25 -07005037 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005038 // Notify battery stats service about this network, both the normal
5039 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005040 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005041 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005042 final IBatteryStats bs = BatteryStatsService.getService();
5043 final int type = newNetwork.networkInfo.getType();
5044
5045 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5046 bs.noteNetworkInterfaceType(baseIface, type);
5047 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5048 final String stackedIface = stacked.getInterfaceName();
5049 bs.noteNetworkInterfaceType(stackedIface, type);
5050 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5051 }
5052 } catch (RemoteException ignored) {
5053 }
5054
Robert Greenwalt152ed372014-12-17 17:19:53 -08005055 // This has to happen after the notifyNetworkCallbacks as that tickles each
5056 // ConnectivityManager instance so that legacy requests correctly bind dns
5057 // requests to this network. The legacy users are listening for this bcast
5058 // and will generally do a dns request so they can ensureRouteToHost and if
5059 // they do that before the callbacks happen they'll use the default network.
5060 //
5061 // TODO: Is there still a race here? We send the broadcast
5062 // after sending the callback, but if the app can receive the
5063 // broadcast before the callback, it might still break.
5064 //
5065 // This *does* introduce a race where if the user uses the new api
5066 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5067 // they may get old info. Reverse this after the old startUsing api is removed.
5068 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005069 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5070 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005071 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005072 // legacy type tracker filters out repeat adds
5073 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5074 }
5075 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005076
5077 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5078 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5079 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5080 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5081 if (newNetwork.isVPN()) {
5082 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5083 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005084 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005085 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5086 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005087 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005088 if (nai.getLingerExpiry() > 0) {
5089 // This network has active linger timers and no requests, but is not
5090 // lingering. Linger it.
5091 //
5092 // One way (the only way?) this can happen if this network is unvalidated
5093 // and became unneeded due to another network improving its score to the
5094 // point where this network will no longer be able to satisfy any requests
5095 // even if it validates.
5096 updateLingerState(nai, now);
5097 } else {
5098 if (DBG) log("Reaping " + nai.name());
5099 teardownUnneededNetwork(nai);
5100 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005101 }
5102 }
5103 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005104 }
5105
Paul Jensen1c7ba022015-06-16 14:27:36 -04005106 /**
5107 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5108 * being disconnected.
5109 * @param changed If only one Network's score or capabilities have been modified since the last
5110 * time this function was called, pass this Network in this argument, otherwise pass
5111 * null.
5112 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5113 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5114 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5115 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5116 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005117 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005118 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005119 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5120 // to avoid the slowness. It is not simply enough to process just "changed", for
5121 // example in the case where "changed"'s score decreases and another network should begin
5122 // satifying a NetworkRequest that "changed" currently satisfies.
5123
5124 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5125 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5126 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005127 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005128 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005129 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005130 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005131 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5132 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5133 // Rematch higher scoring networks first to prevent requests first matching a lower
5134 // scoring network and then a higher scoring network, which could produce multiple
5135 // callbacks and inadvertently unlinger networks.
5136 Arrays.sort(nais);
5137 for (NetworkAgentInfo nai : nais) {
5138 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005139 // Only reap the last time through the loop. Reaping before all rematching
5140 // is complete could incorrectly teardown a network that hasn't yet been
5141 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005142 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005143 : ReapUnvalidatedNetworks.REAP,
5144 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005145 }
5146 }
5147 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005148
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005149 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005150 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005151 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005152 // For now only update icons for default connection.
5153 // TODO: Update WiFi and cellular icons separately. b/17237507
5154 if (!isDefaultNetwork(nai)) return;
5155
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005156 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005157 // Don't repeat publish.
5158 if (newInetCondition == mDefaultInetConditionPublished) return;
5159
5160 mDefaultInetConditionPublished = newInetCondition;
5161 sendInetConditionBroadcast(nai.networkInfo);
5162 }
5163
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005164 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5165 if (mLockdownTracker != null) {
5166 if (nai != null && nai.isVPN()) {
5167 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5168 } else {
5169 mLockdownTracker.onNetworkInfoChanged();
5170 }
5171 }
5172 }
5173
Robert Greenwalt7b816022014-04-18 15:25:25 -07005174 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005175 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005176 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005177 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005178 synchronized (networkAgent) {
5179 oldInfo = networkAgent.networkInfo;
5180 networkAgent.networkInfo = newInfo;
5181 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005182 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005183
5184 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005185 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5186 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5187 notifyIfacesChangedForNetworkStats();
5188 } else if (VDBG) log("ignoring duplicate network state non-change");
5189 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005190 return;
5191 }
5192 if (DBG) {
5193 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5194 (oldInfo == null ? "null" : oldInfo.getState()) +
5195 " to " + state);
5196 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005197
Robin Lee585e2482016-05-01 23:00:00 +01005198 if (!networkAgent.created
5199 && (state == NetworkInfo.State.CONNECTED
5200 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005201
5202 // A network that has just connected has zero requests and is thus a foreground network.
5203 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5204
Robert Greenwalt7b816022014-04-18 15:25:25 -07005205 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005206 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005207 if (networkAgent.isVPN()) {
5208 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005209 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5210 (networkAgent.networkMisc == null ||
5211 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005212 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005213 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005214 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005215 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005216 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005217 loge("Error creating network " + networkAgent.network.netId + ": "
5218 + e.getMessage());
5219 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005220 }
Paul Jenseneec75412014-08-04 12:21:19 -04005221 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005222 }
5223
5224 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5225 networkAgent.everConnected = true;
5226
Robert Greenwalt7b816022014-04-18 15:25:25 -07005227 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005228 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005229
Paul Jensenca8f16a2014-05-09 12:47:55 -04005230 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005231 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005232
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005233 if (networkAgent.isVPN()) {
5234 // Temporarily disable the default proxy (not global).
5235 synchronized (mProxyLock) {
5236 if (!mDefaultProxyDisabled) {
5237 mDefaultProxyDisabled = true;
5238 if (mGlobalProxy == null && mDefaultProxy != null) {
5239 sendProxyBroadcast(null);
5240 }
5241 }
5242 }
5243 // TODO: support proxy per network.
5244 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005245
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005246 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5247 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5248 // capabilities, so it only needs to be done once on initial connect, not every time the
5249 // network's capabilities change. Note that we do this before rematching the network,
5250 // so we could decide to tear it down immediately afterwards. That's fine though - on
5251 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5252 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005253 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005254
Paul Jensen2161a8e2014-09-11 11:00:39 -04005255 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005256 final long now = SystemClock.elapsedRealtime();
5257 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005258
5259 // This has to happen after matching the requests, because callbacks are just requests.
5260 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005261 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005262 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005263 if (networkAgent.isVPN()) {
5264 synchronized (mProxyLock) {
5265 if (mDefaultProxyDisabled) {
5266 mDefaultProxyDisabled = false;
5267 if (mGlobalProxy == null && mDefaultProxy != null) {
5268 sendProxyBroadcast(mDefaultProxy);
5269 }
5270 }
5271 }
5272 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005273 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5274 state == NetworkInfo.State.SUSPENDED) {
5275 // going into or coming out of SUSPEND: rescore and notify
5276 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005277 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005278 }
5279 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5280 ConnectivityManager.CALLBACK_SUSPENDED :
5281 ConnectivityManager.CALLBACK_RESUMED));
5282 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005283 }
5284 }
5285
Robert Greenwaltac96c522014-06-03 16:43:57 -07005286 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005287 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005288 if (score < 0) {
5289 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5290 "). Bumping score to min of 0");
5291 score = 0;
5292 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005293
Paul Jensen2161a8e2014-09-11 11:00:39 -04005294 final int oldScore = nai.getCurrentScore();
5295 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005296
Paul Jensen85cf78e2015-06-25 13:25:07 -04005297 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005298
Paul Jensenc8b9a742014-09-30 15:37:41 -04005299 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005300 }
5301
Erik Klinec75d4fa2017-02-15 19:59:17 +09005302 // Notify only this one new request of the current state. Transfer all the
5303 // current state by calling NetworkCapabilities and LinkProperties callbacks
5304 // so that callers can be guaranteed to have as close to atomicity in state
5305 // transfer as can be supported by this current API.
5306 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005307 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005308 if (nri.mPendingIntent != null) {
5309 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5310 // Attempt no subsequent state pushes where intents are involved.
5311 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005312 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005313
5314 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5315 // Whether a network is currently suspended is also an important
5316 // element of state to be transferred (it would not otherwise be
5317 // delivered by any currently available mechanism).
5318 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5319 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5320 }
5321 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5322 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005323 }
5324
Robert Greenwalt8d482522015-06-24 13:23:42 -07005325 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005326 // The NetworkInfo we actually send out has no bearing on the real
5327 // state of affairs. For example, if the default connection is mobile,
5328 // and a request for HIPRI has just gone away, we need to pretend that
5329 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5330 // the state to DISCONNECTED, even though the network is of type MOBILE
5331 // and is still connected.
5332 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5333 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005334 if (state != DetailedState.DISCONNECTED) {
5335 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005336 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005337 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005338 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005339 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5340 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5341 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5342 if (info.isFailover()) {
5343 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5344 nai.networkInfo.setFailover(false);
5345 }
5346 if (info.getReason() != null) {
5347 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5348 }
5349 if (info.getExtraInfo() != null) {
5350 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5351 }
5352 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005353 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005354 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005355 if (newDefaultAgent != null) {
5356 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5357 newDefaultAgent.networkInfo);
5358 } else {
5359 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5360 }
5361 }
5362 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5363 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005364 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005365 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005366 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005367 }
5368 }
5369 }
5370
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005371 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005372 if (VDBG) {
5373 String notification = ConnectivityManager.getCallbackName(notifyType);
5374 log("notifyType " + notification + " for " + networkAgent.name());
5375 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005376 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5377 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005378 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5379 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005380 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5381 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005382 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005383 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005384 } else {
5385 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5386 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005387 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005388 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005389
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005390 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5391 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5392 }
5393
Jeff Sharkey69736342014-12-08 14:50:12 -08005394 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005395 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5396 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005397 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005398 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005399 try {
5400 mStatsService.forceUpdateIfaces();
5401 } catch (Exception ignored) {
5402 }
5403 }
5404
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005405 @Override
5406 public boolean addVpnAddress(String address, int prefixLength) {
5407 throwIfLockdownEnabled();
5408 int user = UserHandle.getUserId(Binder.getCallingUid());
5409 synchronized (mVpns) {
5410 return mVpns.get(user).addAddress(address, prefixLength);
5411 }
5412 }
5413
5414 @Override
5415 public boolean removeVpnAddress(String address, int prefixLength) {
5416 throwIfLockdownEnabled();
5417 int user = UserHandle.getUserId(Binder.getCallingUid());
5418 synchronized (mVpns) {
5419 return mVpns.get(user).removeAddress(address, prefixLength);
5420 }
5421 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005422
5423 @Override
5424 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5425 throwIfLockdownEnabled();
5426 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005427 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005428 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005429 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005430 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005431 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005432 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005433 }
5434 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005435 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005436
5437 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005438 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005439 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005440 }
5441
5442 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005443 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5444 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5445 enforceKeepalivePermission();
5446 mKeepaliveTracker.startNattKeepalive(
5447 getNetworkAgentInfoForNetwork(network),
5448 intervalSeconds, messenger, binder,
5449 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5450 }
5451
5452 @Override
5453 public void stopKeepalive(Network network, int slot) {
5454 mHandler.sendMessage(mHandler.obtainMessage(
5455 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5456 }
5457
5458 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005459 public void factoryReset() {
5460 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005461
5462 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5463 return;
5464 }
5465
Robin Lee3b3dd942015-05-12 18:14:58 +01005466 final int userId = UserHandle.getCallingUserId();
5467
Stuart Scottf1fb3972015-04-02 18:00:02 -07005468 // Turn airplane mode off
5469 setAirplaneMode(false);
5470
Stuart Scotte3e314d2015-04-20 14:07:45 -07005471 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5472 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005473 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005474 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005475 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005476 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005477 }
5478
Stuart Scotte3e314d2015-04-20 14:07:45 -07005479 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005480 // Remove always-on package
5481 synchronized (mVpns) {
5482 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5483 if (alwaysOnPackage != null) {
5484 setAlwaysOnVpnPackage(userId, null, false);
5485 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5486 }
5487 }
5488
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005489 // Turn Always-on VPN off
5490 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5491 final long ident = Binder.clearCallingIdentity();
5492 try {
5493 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5494 mLockdownEnabled = false;
5495 setLockdownTracker(null);
5496 } finally {
5497 Binder.restoreCallingIdentity(ident);
5498 }
5499 }
5500
Stuart Scotte3e314d2015-04-20 14:07:45 -07005501 // Turn VPN off
5502 VpnConfig vpnConfig = getVpnConfig(userId);
5503 if (vpnConfig != null) {
5504 if (vpnConfig.legacy) {
5505 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5506 } else {
5507 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5508 // in the future without user intervention.
5509 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005510
Victor Changb04a5ea2016-05-30 20:36:30 +01005511 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005512 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005513 }
5514 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005515
5516 Settings.Global.putString(mContext.getContentResolver(),
5517 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005518 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005519
5520 @VisibleForTesting
5521 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5522 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5523 return new NetworkMonitor(context, handler, nai, defaultRequest);
5524 }
Erik Kline48f12f22016-04-14 17:30:59 +09005525
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005526 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005527 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5528 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005529 }
5530
5531 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005532 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5533 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5534 }
5535
Hugo Benichicfddd682016-05-31 16:28:06 +09005536 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005537 int newNetid = NETID_UNSET;
5538 int prevNetid = NETID_UNSET;
5539 int[] transports = new int[0];
5540 boolean hadIPv4 = false;
5541 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005542
Hugo Benichi5f16f762016-04-20 12:09:33 +09005543 if (newNai != null) {
5544 newNetid = newNai.network.netId;
5545 transports = newNai.networkCapabilities.getTransportTypes();
5546 }
5547 if (prevNai != null) {
5548 prevNetid = prevNai.network.netId;
5549 final LinkProperties lp = prevNai.linkProperties;
5550 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5551 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5552 }
5553
Hugo Benichicfddd682016-05-31 16:28:06 +09005554 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5555 }
5556
5557 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5558 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005559 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005560
5561 private static boolean toBool(int encodedBoolean) {
5562 return encodedBoolean != 0; // Only 0 means false.
5563 }
5564
5565 private static int encodeBool(boolean b) {
5566 return b ? 1 : 0;
5567 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005568}