blob: 135872b44610494e0b99d62d71e8a69a32a0ba5a [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;
Christopher Wiley497c1472016-10-11 13:26:03 -0700131import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900132import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900133import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700134import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600135import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400136import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900137import com.android.server.connectivity.NetworkNotificationManager;
138import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400139import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700140import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800141import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700142import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900143import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700144import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700145import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900146import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600147
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700148import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700149
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700150import org.xmlpull.v1.XmlPullParser;
151import org.xmlpull.v1.XmlPullParserException;
152
153import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700155import java.io.FileNotFoundException;
156import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700157import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700159import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700160import java.net.InetAddress;
161import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700162import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700163import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700165import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700166import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700167import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700168import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700169import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700170import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600171import java.util.SortedSet;
172import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
174/**
175 * @hide
176 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800177public class ConnectivityService extends IConnectivityManager.Stub
178 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900179 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Erik Kline7747fd42017-05-12 16:52:48 +0900181 public static final String DIAG_ARG = "--diag";
182 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900183 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900184
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900185 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700186 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Jake Hamby786e71a2014-02-06 14:43:50 -0800188 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900189 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700190
Jeff Sharkey899223b2012-08-04 15:24:58 -0700191 // TODO: create better separation between radio types and network types
192
Robert Greenwalt42acef32009-08-12 16:08:25 -0700193 // how long to wait before switching back to a radio's default network
194 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
195 // system property that can override the above value
196 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
197 "android.telephony.apn-restore";
198
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900199 // How long to wait before putting up a "This network doesn't have an Internet connection,
200 // connect anyway?" dialog after the user selects a network that doesn't validate.
201 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
202
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900203 // Default to 30s linger time-out. Modifiable only for testing.
204 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
205 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
206 @VisibleForTesting
207 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
208
Jeremy Joslin79294842014-12-03 17:15:28 -0800209 // How long to delay to removal of a pending intent based request.
210 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
211 private final int mReleasePendingIntentDelayMs;
212
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900213 private MockableSystemProperties mSystemProperties;
214
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800215 private Tethering mTethering;
216
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700217 private final PermissionMonitor mPermissionMonitor;
218
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700219 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700220
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700221 @GuardedBy("mVpns")
222 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700223
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700224 private boolean mLockdownEnabled;
225 private LockdownVpnTracker mLockdownTracker;
226
Erik Klineda4bfa82015-04-30 12:58:40 +0900227 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700229 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700230 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800232 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
234 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700235 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700237 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800238 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700239 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900240 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700241
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700242 private String mCurrentTcpBufferSizes;
243
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700244 private static final int ENABLED = 1;
245 private static final int DISABLED = 0;
246
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900247 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900248 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
249 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900250
Paul Jensenb10e37f2014-11-25 12:33:08 -0500251 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400252 // Tear down networks that have no chance (e.g. even if validated) of becoming
253 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500254 // all networks have been rematched against all NetworkRequests.
255 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400256 // Don't reap networks. This should be passed when some networks have not yet been
257 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 DONT_REAP
259 };
260
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900261 private enum UnneededFor {
262 LINGER, // Determine whether this network is unneeded and should be lingered.
263 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
264 }
265
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267 * used internally to change our mobile data enabled flag
268 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700269 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700270
271 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700272 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700273 * from one net to another. Clear happens when we get a new
274 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
275 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700276 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700277 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700278
Robert Greenwalt434203a2010-10-11 16:00:27 -0700279 /**
280 * used internally to reload global proxy settings
281 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700282 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700283
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700284 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400285 * PAC manager has received new port.
286 */
287 private static final int EVENT_PROXY_HAS_CHANGED = 16;
288
Robert Greenwalte049c232014-04-11 15:53:27 -0700289 /**
290 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700291 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700292 */
293 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
294
Robert Greenwalt7b816022014-04-18 15:25:25 -0700295 /**
296 * used internally when registering NetworkAgents
297 * obj = Messenger
298 */
299 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
300
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 /**
302 * used to add a network request
303 * includes a NetworkRequestInfo
304 */
305 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
306
307 /**
308 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900309 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700310 * cancel it.
311 * includes a NetworkRequestInfo
312 */
313 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
314
315 /**
316 * used to add a network listener - no request
317 * includes a NetworkRequestInfo
318 */
319 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
320
321 /**
322 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400323 * arg1 = UID of caller
324 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700325 */
326 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
327
Robert Greenwalta67be032014-05-16 15:49:14 -0700328 /**
329 * used internally when registering NetworkFactories
330 * obj = Messenger
331 */
332 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
333
Robert Greenwalt27711812014-06-25 16:45:57 -0700334 /**
335 * used internally to expire a wakelock when transitioning
336 * from one net to another. Expire happens when we fail to find
337 * a new network (typically after 1 minute) -
338 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
339 * a replacement network.
340 */
341 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
342
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700343 /**
344 * Used internally to indicate the system is ready.
345 */
346 private static final int EVENT_SYSTEM_READY = 25;
347
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800348 /**
349 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400350 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800351 */
352 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
353
354 /**
355 * used to remove a pending intent and its associated network request.
356 * arg1 = UID of caller
357 * obj = PendingIntent
358 */
359 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
360
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900361 /**
362 * used to specify whether a network should be used even if unvalidated.
363 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
364 * arg2 = whether to remember this choice in the future (1 or 0)
365 * obj = network
366 */
367 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
368
369 /**
370 * used to ask the user to confirm a connection to an unvalidated network.
371 * obj = network
372 */
373 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700374
Erik Klineda4bfa82015-04-30 12:58:40 +0900375 /**
376 * used internally to (re)configure mobile data always-on settings.
377 */
378 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
379
Paul Jensen694f2b82015-06-17 14:15:39 -0400380 /**
381 * used to add a network listener with a pending intent
382 * obj = NetworkRequestInfo
383 */
384 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
385
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900386 /**
387 * used to specify whether a network should not be penalized when it becomes unvalidated.
388 */
389 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
390
391 /**
392 * used to trigger revalidation of a network.
393 */
394 private static final int EVENT_REVALIDATE_NETWORK = 36;
395
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900396 private static String eventName(int what) {
397 return sMagicDecoderRing.get(what, Integer.toString(what));
398 }
399
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900400 /** Handler thread used for both of the handlers below. */
401 @VisibleForTesting
402 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700403 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700404 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700405 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700406 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700407
Mike Lockwood0f79b542009-08-14 14:18:49 -0400408 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800409 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400410
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700411 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700412 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800413 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700414
Robert Greenwalt434203a2010-10-11 16:00:27 -0700415 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400416 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700417 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700418 private boolean mDefaultProxyDisabled = false;
419
Robert Greenwalt434203a2010-10-11 16:00:27 -0700420 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400421 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700422
Jason Monk602b2322013-07-03 17:04:33 -0400423 private PacManager mPacManager = null;
424
Erik Klineda4bfa82015-04-30 12:58:40 +0900425 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700426
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400427 private UserManager mUserManager;
428
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700429 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700430 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700431
Robert Greenwalt50393202011-06-21 17:26:14 -0700432 // the set of network types that can only be enabled by system/sig apps
433 List mProtectedNetworks;
434
John Spurlockbf991a82013-06-24 14:20:23 -0400435 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700436
Wink Savilleab9321d2013-06-29 21:10:57 -0700437 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400438
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900439 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900440 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900441 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900442
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700443 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
444 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700445 private final static int MAX_NET_ID = 65535;
446 private int mNextNetId = MIN_NET_ID;
447
Robert Greenwalt34524f02014-05-18 16:22:10 -0700448 // sequence number of NetworkRequests
449 private int mNextNetworkRequestId = 1;
450
Erik Kline7523eb32015-07-09 18:24:03 +0900451 // NetworkRequest activity String log entries.
452 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
453 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
454
Hugo Benichic2ae2872016-07-11 11:05:12 +0900455 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900456 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900457 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
458
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900459 private static final int MAX_WAKELOCK_LOGS = 20;
460 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
461
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700462 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
463 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400464 private static class ValidationLog {
465 final Network mNetwork;
466 final String mNetworkExtraInfo;
467 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700468
Paul Jensen0808eb82016-06-03 13:51:21 -0400469 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
470 mNetwork = network;
471 mNetworkExtraInfo = networkExtraInfo;
472 mLog = log;
473 }
474 }
475 private final ArrayDeque<ValidationLog> mValidationLogs =
476 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
477
478 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900479 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700480 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
481 mValidationLogs.removeLast();
482 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400483 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700484 }
485 }
486
Hugo Benichif9fdf872016-07-28 17:53:06 +0900487 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900488
Erik Kline065ab6e2016-10-02 18:02:14 +0900489 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900490 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900491
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700492 /**
493 * Implements support for the legacy "one network per network type" model.
494 *
495 * We used to have a static array of NetworkStateTrackers, one for each
496 * network type, but that doesn't work any more now that we can have,
497 * for example, more that one wifi network. This class stores all the
498 * NetworkAgentInfo objects that support a given type, but the legacy
499 * API will only see the first one.
500 *
501 * It serves two main purposes:
502 *
503 * 1. Provide information about "the network for a given type" (since this
504 * API only supports one).
505 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
506 * the first network for a given type changes, or if the default network
507 * changes.
508 */
509 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900510
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900511 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900512 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700514 /**
515 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
516 * Each list holds references to all NetworkAgentInfos that are used to
517 * satisfy requests for that network type.
518 *
519 * This array is built out at startup such that an unsupported network
520 * doesn't get an ArrayList instance, making this a tristate:
521 * unsupported, supported but not active and active.
522 *
523 * The actual lists are populated when we scan the network types that
524 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900525 *
526 * Threading model:
527 * - addSupportedType() is only called in the constructor
528 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
529 * They are therefore not thread-safe with respect to each other.
530 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
531 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
532 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700533 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900534 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700535
536 public LegacyTypeTracker() {
537 mTypeLists = (ArrayList<NetworkAgentInfo>[])
538 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
539 }
540
541 public void addSupportedType(int type) {
542 if (mTypeLists[type] != null) {
543 throw new IllegalStateException(
544 "legacy list for type " + type + "already initialized");
545 }
546 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
547 }
548
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700549 public boolean isTypeSupported(int type) {
550 return isNetworkTypeValid(type) && mTypeLists[type] != null;
551 }
552
553 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900554 synchronized (mTypeLists) {
555 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
556 return mTypeLists[type].get(0);
557 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700558 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900559 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 }
561
Robert Greenwalt8d482522015-06-24 13:23:42 -0700562 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900563 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900564 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700565 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900566 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900567 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900568 }
569 }
570
571 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700572 public void add(int type, NetworkAgentInfo nai) {
573 if (!isTypeSupported(type)) {
574 return; // Invalid network type.
575 }
576 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
577
578 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
579 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700580 return;
581 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900582 synchronized (mTypeLists) {
583 list.add(nai);
584 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900585
586 // 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 +0900587 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900588 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700589 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
590 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700591 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700592 }
593
Lorenzo Colittia793a672014-07-31 23:20:17 +0900594 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900595 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900596 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
597 if (list == null || list.isEmpty()) {
598 return;
599 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900600 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900601
Hugo Benichi78caa2582016-06-21 09:48:07 +0900602 synchronized (mTypeLists) {
603 if (!list.remove(nai)) {
604 return;
605 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 }
607
Robert Greenwalt8d482522015-06-24 13:23:42 -0700608 final DetailedState state = DetailedState.DISCONNECTED;
609
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900610 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700611 maybeLogBroadcast(nai, state, type, wasDefault);
612 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900613 }
614
615 if (!list.isEmpty() && wasFirstNetwork) {
616 if (DBG) log("Other network available for type " + type +
617 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900618 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700619 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
620 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900621 }
622 }
623
624 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900625 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
626 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700627 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900628 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700629 }
630 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700631
Robert Greenwalt8d482522015-06-24 13:23:42 -0700632 // send out another legacy broadcast - currently only used for suspend/unsuspend
633 // toggle
634 public void update(NetworkAgentInfo nai) {
635 final boolean isDefault = isDefaultNetwork(nai);
636 final DetailedState state = nai.networkInfo.getDetailedState();
637 for (int type = 0; type < mTypeLists.length; type++) {
638 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700639 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900640 final boolean isFirst = contains && (nai == list.get(0));
641 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700642 maybeLogBroadcast(nai, state, type, isDefault);
643 sendLegacyNetworkBroadcast(nai, state, type);
644 }
645 }
646 }
647
Lorenzo Colittia793a672014-07-31 23:20:17 +0900648 private String naiToString(NetworkAgentInfo nai) {
649 String name = (nai != null) ? nai.name() : "null";
650 String state = (nai.networkInfo != null) ?
651 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
652 "???/???";
653 return name + " " + state;
654 }
655
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700656 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900657 pw.println("mLegacyTypeTracker:");
658 pw.increaseIndent();
659 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700660 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900661 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700662 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900663 pw.println();
664 pw.println("Current state:");
665 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900666 synchronized (mTypeLists) {
667 for (int type = 0; type < mTypeLists.length; type++) {
668 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
669 for (NetworkAgentInfo nai : mTypeLists[type]) {
670 pw.println(type + " " + naiToString(nai));
671 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900672 }
673 }
674 pw.decreaseIndent();
675 pw.decreaseIndent();
676 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700677 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700678 }
679 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
680
Jeff Sharkey899223b2012-08-04 15:24:58 -0700681 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700682 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900683 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
684 }
685
686 @VisibleForTesting
687 protected ConnectivityService(Context context, INetworkManagementService netManager,
688 INetworkStatsService statsService, INetworkPolicyManager policyManager,
689 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800690 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800691
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900692 mSystemProperties = getSystemProperties();
693
Hugo Benichif9fdf872016-07-28 17:53:06 +0900694 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900695 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900696 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900697 mNetworkRequests.put(mDefaultRequest, defaultNRI);
698 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900699
700 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900701 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700702
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900703 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900704 mHandlerThread.start();
705 mHandler = new InternalHandler(mHandlerThread.getLooper());
706 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700707
Jeremy Joslin79294842014-12-03 17:15:28 -0800708 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
709 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
710
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900711 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900712
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700713 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700714 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800715 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700716 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900717 mPolicyManagerInternal = checkNotNull(
718 LocalServices.getService(NetworkPolicyManagerInternal.class),
719 "missing NetworkPolicyManagerInternal");
720
Jeff Sharkey82f85212012-08-24 11:17:25 -0700721 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700722 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700723
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700724 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900725 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700726 } catch (RemoteException e) {
727 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700728 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 }
730
731 final PowerManager powerManager = (PowerManager) context.getSystemService(
732 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700733 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
734 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
735 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800736 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700737
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700738 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700739
Wink Saville51f456f2013-04-23 14:26:51 -0700740 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900741 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700742 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700743 String[] naStrings = context.getResources().getStringArray(
744 com.android.internal.R.array.networkAttributes);
745 for (String naString : naStrings) {
746 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700747 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700748 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700749 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800750 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700751 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700752 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700753 }
Wink Saville51f456f2013-04-23 14:26:51 -0700754 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
755 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
756 n.type);
757 continue;
758 }
Wink Saville975c8482011-04-07 14:23:45 -0700759 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800760 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700761 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700762 continue;
763 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700764 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700765
Wink Saville975c8482011-04-07 14:23:45 -0700766 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700767 mNetworksDefined++;
768 } catch(Exception e) {
769 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700770 }
771 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700772
773 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
774 if (mNetConfigs[TYPE_VPN] == null) {
775 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
776 // don't need to add TYPE_VPN to mNetConfigs.
777 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
778 mNetworksDefined++; // used only in the log() statement below.
779 }
780
Wink Saville5e56bc52013-07-29 15:00:57 -0700781 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700782
Robert Greenwalt50393202011-06-21 17:26:14 -0700783 mProtectedNetworks = new ArrayList<Integer>();
784 int[] protectedNetworks = context.getResources().getIntArray(
785 com.android.internal.R.array.config_protectedNetworks);
786 for (int p : protectedNetworks) {
787 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
788 mProtectedNetworks.add(p);
789 } else {
790 if (DBG) loge("Ignoring protectedNetwork " + p);
791 }
792 }
793
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900794 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
795 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700796
Erik Kline47222fc2017-04-30 19:36:15 +0900797 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800798
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700799 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
800
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700801 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700802 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100803 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700804 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700805 intentFilter.addAction(Intent.ACTION_USER_ADDED);
806 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000807 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700808 mContext.registerReceiverAsUser(
809 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000810 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
811 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900812
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700813 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700814 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700815 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700816 } catch (RemoteException e) {
817 loge("Error registering observer :" + e);
818 }
819
Erik Klineda4bfa82015-04-30 12:58:40 +0900820 mSettingsObserver = new SettingsObserver(mContext, mHandler);
821 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800822
John Spurlockbf991a82013-06-24 14:20:23 -0400823 mDataConnectionStats = new DataConnectionStats(mContext);
824 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400825
Jason Monkdecd2952013-10-10 14:02:51 -0400826 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700827
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400828 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900829
830 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900831 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
832 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900833
834 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
835 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
836 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
837 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
838 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
839 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
840 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900841
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900842 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900843 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900844 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800845 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700846
Erik Kline47222fc2017-04-30 19:36:15 +0900847 private Tethering makeTethering() {
848 // TODO: Move other elements into @Overridden getters.
849 final TetheringDependencies deps = new TetheringDependencies();
850 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
851 IoThread.get().getLooper(), new MockableSystemProperties(),
852 deps);
853 }
854
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900855 private NetworkRequest createInternetRequestForTransport(
856 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900857 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900858 netCap.addCapability(NET_CAPABILITY_INTERNET);
859 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900860 if (transportType > -1) {
861 netCap.addTransportType(transportType);
862 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900863 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900864 }
865
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900866 // Used only for testing.
867 // TODO: Delete this and either:
868 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
869 // changing ContentResolver to make registerContentObserver non-final).
870 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
871 // by subclassing SettingsObserver.
872 @VisibleForTesting
873 void updateMobileDataAlwaysOn() {
874 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
875 }
876
Erik Klineda4bfa82015-04-30 12:58:40 +0900877 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900878 final boolean enable = toBool(Settings.Global.getInt(
879 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900880 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
881 if (enable == isEnabled) {
882 return; // Nothing to do.
883 }
884
885 if (enable) {
886 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900887 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900888 } else {
889 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
890 }
891 }
892
893 private void registerSettingsCallbacks() {
894 // Watch for global HTTP proxy changes.
895 mSettingsObserver.observe(
896 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
897 EVENT_APPLY_GLOBAL_HTTP_PROXY);
898
899 // Watch for whether or not to keep mobile data always on.
900 mSettingsObserver.observe(
901 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
902 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
903 }
904
Robert Greenwalt34524f02014-05-18 16:22:10 -0700905 private synchronized int nextNetworkRequestId() {
906 return mNextNetworkRequestId++;
907 }
908
Paul Jensen67b0b072015-06-10 11:22:17 -0400909 @VisibleForTesting
910 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400911 synchronized (mNetworkForNetId) {
912 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
913 int netId = mNextNetId;
914 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
915 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500916 if (!mNetIdInUse.get(netId)) {
917 mNetIdInUse.put(netId, true);
918 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400919 }
920 }
921 }
922 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700923 }
924
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600925 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800926 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600927 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
928 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800929 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600930 state = nai.getNetworkState();
931 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800932 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600933 final NetworkInfo info = new NetworkInfo(networkType, 0,
934 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
936 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600937 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
938 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600940 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600941 return state;
942 } else {
943 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800944 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400945 }
946
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800947 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
948 if (network == null) {
949 return null;
950 }
951 synchronized (mNetworkForNetId) {
952 return mNetworkForNetId.get(network.netId);
953 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600954 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800955
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900956 private Network[] getVpnUnderlyingNetworks(int uid) {
957 if (!mLockdownEnabled) {
958 int user = UserHandle.getUserId(uid);
959 synchronized (mVpns) {
960 Vpn vpn = mVpns.get(user);
961 if (vpn != null && vpn.appliesToUid(uid)) {
962 return vpn.getUnderlyingNetworks();
963 }
964 }
965 }
966 return null;
967 }
968
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800969 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400970 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800971
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900972 final Network[] networks = getVpnUnderlyingNetworks(uid);
973 if (networks != null) {
974 // getUnderlyingNetworks() returns:
975 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
976 // empty array => the VPN explicitly said "no default network".
977 // non-empty array => the VPN specified one or more default networks; we use the
978 // first one.
979 if (networks.length > 0) {
980 nai = getNetworkAgentInfoForNetwork(networks[0]);
981 } else {
982 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800983 }
984 }
985
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800986 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600987 return nai.getNetworkState();
988 } else {
989 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800990 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400991 }
992
993 /**
994 * Check if UID should be blocked from using the network with the given LinkProperties.
995 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600996 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
997 boolean ignoreBlocked) {
998 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900999 if (ignoreBlocked) {
1000 return false;
1001 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001002 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001003 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1004 if (isSystem(uid)) {
1005 return false;
1006 }
Robin Lee17e61832016-05-09 13:46:28 +01001007 synchronized (mVpns) {
1008 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1009 if (vpn != null && vpn.isBlockingUid(uid)) {
1010 return true;
1011 }
1012 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001013 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001014 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001015 }
1016
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001017 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001018 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1019 return;
1020 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001021 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001022 synchronized (mBlockedAppUids) {
1023 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001024 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001025 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001026 blocked = false;
1027 } else {
1028 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001029 }
1030 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001031 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1032 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1033 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001034 }
1035
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001036 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001037 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1038 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1039 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1040 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001041 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001042 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001043 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1044
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001045 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001046 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001047 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001048 if (mLockdownTracker != null) {
1049 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001050 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001051
1052 // TODO: apply metered state closer to NetworkAgentInfo
1053 final long token = Binder.clearCallingIdentity();
1054 try {
1055 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1056 } catch (RemoteException e) {
1057 } finally {
1058 Binder.restoreCallingIdentity(token);
1059 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 }
1061
1062 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 * Return NetworkInfo for the active (i.e., connected) network interface.
1064 * It is assumed that at most one network is active at a time. If more
1065 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001066 * @return the info for the active network, or {@code null} if none is
1067 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001069 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001070 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001071 enforceAccessPermission();
1072 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001073 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001074 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001075 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1076 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
1078
Paul Jensen31a94f42015-02-13 14:18:39 -05001079 @Override
1080 public Network getActiveNetwork() {
1081 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001082 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001083 }
1084
1085 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001086 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001087 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001088 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001089 }
1090
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001091 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001092 final int user = UserHandle.getUserId(uid);
1093 int vpnNetId = NETID_UNSET;
1094 synchronized (mVpns) {
1095 final Vpn vpn = mVpns.get(user);
1096 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1097 }
1098 NetworkAgentInfo nai;
1099 if (vpnNetId != NETID_UNSET) {
1100 synchronized (mNetworkForNetId) {
1101 nai = mNetworkForNetId.get(vpnNetId);
1102 }
1103 if (nai != null) return nai.network;
1104 }
1105 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001106 if (nai != null
1107 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1108 nai = null;
1109 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001110 return nai != null ? nai.network : null;
1111 }
1112
Lorenzo Colitti18660282016-07-04 12:55:44 +09001113 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001114 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1115 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001116 final int uid = Binder.getCallingUid();
1117 NetworkState state = getUnfilteredActiveNetworkState(uid);
1118 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001119 }
1120
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001121 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001123 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001124 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001125 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001126 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001127 }
1128
1129 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001130 public NetworkInfo getNetworkInfo(int networkType) {
1131 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001133 if (getVpnUnderlyingNetworks(uid) != null) {
1134 // A VPN is active, so we may need to return one of its underlying networks. This
1135 // information is not available in LegacyTypeTracker, so we have to get it from
1136 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001137 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001138 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001139 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001140 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001141 }
1142 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001143 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001144 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 }
1146
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001147 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001148 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001149 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001150 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001151 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001152 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001153 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001154 return state.networkInfo;
1155 } else {
1156 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001157 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001158 }
1159
1160 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001161 public NetworkInfo[] getAllNetworkInfo() {
1162 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001163 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001164 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1165 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001166 NetworkInfo info = getNetworkInfo(networkType);
1167 if (info != null) {
1168 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001169 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001170 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001171 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001172 }
1173
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001174 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001175 public Network getNetworkForType(int networkType) {
1176 enforceAccessPermission();
1177 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001178 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1179 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001180 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001181 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001182 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001183 }
1184
1185 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001186 public Network[] getAllNetworks() {
1187 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001188 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001189 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001190 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001191 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001192 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001193 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001194 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001195 }
1196
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001197 @Override
1198 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1199 // The basic principle is: if an app's traffic could possibly go over a
1200 // network, without the app doing anything multinetwork-specific,
1201 // (hence, by "default"), then include that network's capabilities in
1202 // the array.
1203 //
1204 // In the normal case, app traffic only goes over the system's default
1205 // network connection, so that's the only network returned.
1206 //
1207 // With a VPN in force, some app traffic may go into the VPN, and thus
1208 // over whatever underlying networks the VPN specifies, while other app
1209 // traffic may go over the system default network (e.g.: a split-tunnel
1210 // VPN, or an app disallowed by the VPN), so the set of networks
1211 // returned includes the VPN's underlying networks and the system
1212 // default.
1213 enforceAccessPermission();
1214
1215 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1216
1217 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001218 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001219 if (nc != null) {
1220 result.put(nai.network, nc);
1221 }
1222
1223 if (!mLockdownEnabled) {
1224 synchronized (mVpns) {
1225 Vpn vpn = mVpns.get(userId);
1226 if (vpn != null) {
1227 Network[] networks = vpn.getUnderlyingNetworks();
1228 if (networks != null) {
1229 for (Network network : networks) {
1230 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001231 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001232 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001233 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001234 }
1235 }
1236 }
1237 }
1238 }
1239 }
1240
1241 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1242 out = result.values().toArray(out);
1243 return out;
1244 }
1245
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001246 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001247 public boolean isNetworkSupported(int networkType) {
1248 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001249 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001250 }
1251
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001252 /**
1253 * Return LinkProperties for the active (i.e., connected) default
1254 * network interface. It is assumed that at most one default network
1255 * is active at a time. If more than one is active, it is indeterminate
1256 * which will be returned.
1257 * @return the ip properties for the active network, or {@code null} if
1258 * none is active
1259 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001260 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001261 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001262 enforceAccessPermission();
1263 final int uid = Binder.getCallingUid();
1264 NetworkState state = getUnfilteredActiveNetworkState(uid);
1265 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001266 }
1267
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001268 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001269 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001270 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001271 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1272 if (nai != null) {
1273 synchronized (nai) {
1274 return new LinkProperties(nai.linkProperties);
1275 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001276 }
1277 return null;
1278 }
1279
Robert Greenwalt12e67352014-05-13 21:41:06 -07001280 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001281 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001282 public LinkProperties getLinkProperties(Network network) {
1283 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001284 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1285 }
1286
1287 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1288 if (nai == null) {
1289 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001290 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001291 synchronized (nai) {
1292 return new LinkProperties(nai.linkProperties);
1293 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001294 }
1295
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001296 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001297 if (nai != null) {
1298 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001299 if (nai.networkCapabilities != null) {
1300 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001301 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001302 }
1303 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001304 return null;
1305 }
1306
1307 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001308 public NetworkCapabilities getNetworkCapabilities(Network network) {
1309 enforceAccessPermission();
1310 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1311 }
1312
1313 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001314 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001315 // Require internal since we're handing out IMSI details
1316 enforceConnectivityInternalPermission();
1317
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001318 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001319 for (Network network : getAllNetworks()) {
1320 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1321 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001322 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001323 }
1324 }
1325 return result.toArray(new NetworkState[result.size()]);
1326 }
1327
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001328 @Override
1329 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1330 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001331 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001332 final long token = Binder.clearCallingIdentity();
1333 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001334 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1335 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001336 try {
1337 return mPolicyManager.getNetworkQuotaInfo(state);
1338 } catch (RemoteException e) {
1339 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001340 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001341 return null;
1342 } finally {
1343 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001344 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001345 }
1346
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001347 @Override
1348 public boolean isActiveNetworkMetered() {
1349 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001350
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001351 final NetworkInfo info = getActiveNetworkInfo();
1352 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001353 }
1354
Jeff Sharkey216c1812012-08-05 14:29:23 -07001355 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1356 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001357 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001358 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001359 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001360 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001361 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001362
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001363 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 * Ensure that a network route exists to deliver traffic to the specified
1365 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001366 * @param networkType the type of the network over which traffic to the
1367 * specified host is to be routed
1368 * @param hostAddress the IP address of the host to which the route is
1369 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 * @return {@code true} on success, {@code false} on failure
1371 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001372 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001373 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001375 if (mProtectedNetworks.contains(networkType)) {
1376 enforceConnectivityInternalPermission();
1377 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001378
Chad Brubakerc0234532014-02-14 13:24:29 -08001379 InetAddress addr;
1380 try {
1381 addr = InetAddress.getByAddress(hostAddress);
1382 } catch (UnknownHostException e) {
1383 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1384 return false;
1385 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001386
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001387 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001388 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001389 return false;
1390 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001391
1392 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1393 if (nai == null) {
1394 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1395 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1396 } else {
1397 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1398 }
1399 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001400 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001401
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001402 DetailedState netState;
1403 synchronized (nai) {
1404 netState = nai.networkInfo.getDetailedState();
1405 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001406
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001407 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001408 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001409 log("requestRouteToHostAddress on down network "
1410 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001411 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001412 }
1413 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001414 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001415
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001416 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001417 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001418 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001419 LinkProperties lp;
1420 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001421 synchronized (nai) {
1422 lp = nai.linkProperties;
1423 netId = nai.network.netId;
1424 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001425 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001426 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1427 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001428 } finally {
1429 Binder.restoreCallingIdentity(token);
1430 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001431 }
1432
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001433 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001434 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001435 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001436 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001437 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001438 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001439 if (bestRoute.getGateway().equals(addr)) {
1440 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001441 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001442 } else {
1443 // if we will connect to this through another route, add a direct route
1444 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001445 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001446 }
1447 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001448 if (DBG) log("Adding legacy route " + bestRoute +
1449 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001450 try {
1451 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1452 } catch (Exception e) {
1453 // never crash - catch them all
1454 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001455 return false;
1456 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001457 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 }
1459
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001460 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001461 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001462 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001463 // TODO: notify UID when it has requested targeted updates
1464 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001465 @Override
1466 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001467 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001468 @Override
1469 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001470 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001471 if (restrictBackground) {
1472 log("onRestrictBackgroundChanged(true): disabling tethering");
1473 mTethering.untetherAll();
1474 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001475 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001476 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001477 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001478 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001479 };
1480
Robin Lee3b3dd942015-05-12 18:14:58 +01001481 /**
1482 * Require that the caller is either in the same user or has appropriate permission to interact
1483 * across users.
1484 *
1485 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1486 */
1487 private void enforceCrossUserPermission(int userId) {
1488 if (userId == UserHandle.getCallingUserId()) {
1489 // Not a cross-user call.
1490 return;
1491 }
1492 mContext.enforceCallingOrSelfPermission(
1493 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1494 "ConnectivityService");
1495 }
1496
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001497 private void enforceInternetPermission() {
1498 mContext.enforceCallingOrSelfPermission(
1499 android.Manifest.permission.INTERNET,
1500 "ConnectivityService");
1501 }
1502
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001503 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001504 mContext.enforceCallingOrSelfPermission(
1505 android.Manifest.permission.ACCESS_NETWORK_STATE,
1506 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001507 }
1508
1509 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001510 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001511 }
1512
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001513 private void enforceTetherAccessPermission() {
1514 mContext.enforceCallingOrSelfPermission(
1515 android.Manifest.permission.ACCESS_NETWORK_STATE,
1516 "ConnectivityService");
1517 }
1518
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001519 private void enforceConnectivityInternalPermission() {
1520 mContext.enforceCallingOrSelfPermission(
1521 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1522 "ConnectivityService");
1523 }
1524
Hugo Benichi514da602016-07-19 15:59:27 +09001525 private void enforceConnectivityRestrictedNetworksPermission() {
1526 try {
1527 mContext.enforceCallingOrSelfPermission(
1528 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1529 "ConnectivityService");
1530 return;
1531 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1532 enforceConnectivityInternalPermission();
1533 }
1534
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001535 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001536 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001537 }
1538
Lorenzo Colitti18660282016-07-04 12:55:44 +09001539 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001540 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001541 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001542 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001543 }
1544
1545 private void sendInetConditionBroadcast(NetworkInfo info) {
1546 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1547 }
1548
Wink Saville628b0852011-08-04 15:01:58 -07001549 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001550 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001551 info = new NetworkInfo(info);
1552 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001553 }
1554
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001555 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001556 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001557 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 if (info.isFailover()) {
1559 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1560 info.setFailover(false);
1561 }
1562 if (info.getReason() != null) {
1563 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1564 }
1565 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001566 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1567 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001569 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001570 return intent;
1571 }
1572
1573 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1574 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1575 }
1576
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001577 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001578 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1579 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1580 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001581 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001582 final long ident = Binder.clearCallingIdentity();
1583 try {
1584 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1585 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1586 } finally {
1587 Binder.restoreCallingIdentity(ident);
1588 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001589 }
1590
Mike Lockwood0f79b542009-08-14 14:18:49 -04001591 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001592 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001593 if (!mSystemReady) {
1594 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001595 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001596 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001597 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001598 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001599 }
1600
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001601 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001602 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001603 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001604 final NetworkInfo ni = intent.getParcelableExtra(
1605 ConnectivityManager.EXTRA_NETWORK_INFO);
1606 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1607 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1608 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001609 } else {
1610 BroadcastOptions opts = BroadcastOptions.makeBasic();
1611 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1612 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001613 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001614 final IBatteryStats bs = BatteryStatsService.getService();
1615 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001616 bs.noteConnectivityChanged(intent.getIntExtra(
1617 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1618 ni != null ? ni.getState().toString() : "?");
1619 } catch (RemoteException e) {
1620 }
1621 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001622 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001623 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001624 } finally {
1625 Binder.restoreCallingIdentity(ident);
1626 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001627 }
1628 }
1629
1630 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001631 loadGlobalProxy();
1632
Hugo Benichi20035e02017-04-26 14:53:28 +09001633 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001634 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001635 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001636 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001637 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001638 }
1639 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001640 // load the global proxy at startup
1641 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001642
Robin Lee244ce8e2016-01-05 18:03:46 +00001643 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1644 // for user to unlock device too.
1645 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001646
Erik Klineda4bfa82015-04-30 12:58:40 +09001647 // Configure whether mobile data is always on.
1648 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1649
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001650 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001651
1652 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001653 }
1654
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001655 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001656 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001657 *
1658 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001659 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001660 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001661 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1662 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001663
1664 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001665 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001666
Robert Greenwalt7b816022014-04-18 15:25:25 -07001667 if (networkAgent.networkCapabilities.hasTransport(
1668 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001669 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1670 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001671 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001672 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001673 } else if (networkAgent.networkCapabilities.hasTransport(
1674 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001675 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1676 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001677 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001678 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001679 } else {
1680 // do not track any other networks
1681 timeout = 0;
1682 }
1683
Robert Greenwalt7b816022014-04-18 15:25:25 -07001684 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001685 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001686 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001687 } catch (Exception e) {
1688 // You shall not crash!
1689 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001690 }
1691 }
1692 }
1693
1694 /**
1695 * Remove data activity tracking when network disconnects.
1696 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001697 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1698 final String iface = networkAgent.linkProperties.getInterfaceName();
1699 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001700
Robert Greenwalt7b816022014-04-18 15:25:25 -07001701 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1702 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001703 try {
1704 // the call fails silently if no idletimer setup for this interface
1705 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001706 } catch (Exception e) {
1707 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001708 }
1709 }
1710 }
1711
1712 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001713 * Reads the network specific MTU size from reources.
1714 * and set it on it's iface.
1715 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001716 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1717 final String iface = newLp.getInterfaceName();
1718 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001719 if (oldLp == null && mtu == 0) {
1720 // Silently ignore unset MTU value.
1721 return;
1722 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001723 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1724 if (VDBG) log("identical MTU - not setting");
1725 return;
1726 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001727 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001728 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001729 return;
1730 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001731
w1997615afd812014-08-05 15:18:11 -07001732 // Cannot set MTU without interface name
1733 if (TextUtils.isEmpty(iface)) {
1734 loge("Setting MTU size with null iface.");
1735 return;
1736 }
1737
Robert Greenwalt7b816022014-04-18 15:25:25 -07001738 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001739 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001740 mNetd.setMtu(iface, mtu);
1741 } catch (Exception e) {
1742 Slog.e(TAG, "exception in setMtu()" + e);
1743 }
1744 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001745
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001746 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001747 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1748
1749 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001750 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001751 protected MockableSystemProperties getSystemProperties() {
1752 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001753 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001754
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001755 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1756 if (isDefaultNetwork(nai) == false) {
1757 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001758 }
1759
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001760 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1761 String[] values = null;
1762 if (tcpBufferSizes != null) {
1763 values = tcpBufferSizes.split(",");
1764 }
1765
1766 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001767 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001768 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1769 values = tcpBufferSizes.split(",");
1770 }
1771
1772 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1773
1774 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001775 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001776
1777 final String prefix = "/sys/kernel/ipv4/tcp_";
1778 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1779 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1780 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1781 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1782 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1783 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1784 mCurrentTcpBufferSizes = tcpBufferSizes;
1785 } catch (IOException e) {
1786 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001787 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001788
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001789 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001790 Settings.Global.TCP_DEFAULT_INIT_RWND,
1791 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001792 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1793 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001794 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001795 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001796 }
1797
Mattias Falk8b47b362011-08-23 14:15:13 +02001798 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001799 /*
1800 * Tell the VMs to toss their DNS caches
1801 */
1802 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1803 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001804 /*
1805 * Connectivity events can happen before boot has completed ...
1806 */
1807 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001808 final long ident = Binder.clearCallingIdentity();
1809 try {
1810 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1811 } finally {
1812 Binder.restoreCallingIdentity(ident);
1813 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001814 }
1815
Robert Greenwalt562cc542014-05-15 18:07:26 -07001816 @Override
1817 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001818 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001819 NETWORK_RESTORE_DELAY_PROP_NAME);
1820 if(restoreDefaultNetworkDelayStr != null &&
1821 restoreDefaultNetworkDelayStr.length() != 0) {
1822 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001823 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001824 } catch (NumberFormatException e) {
1825 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001826 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001827 // if the system property isn't set, use the value for the apn type
1828 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1829
1830 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1831 (mNetConfigs[networkType] != null)) {
1832 ret = mNetConfigs[networkType].restoreTime;
1833 }
1834 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001835 }
1836
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001837 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001838 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001839 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001840 }
1841 return false;
1842 }
1843
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001844 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1845 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1846 final long DIAG_TIME_MS = 5000;
1847 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1848 // Start gathering diagnostic information.
1849 netDiags.add(new NetworkDiagnostics(
1850 nai.network,
1851 new LinkProperties(nai.linkProperties), // Must be a copy.
1852 DIAG_TIME_MS));
1853 }
1854
1855 for (NetworkDiagnostics netDiag : netDiags) {
1856 pw.println();
1857 netDiag.waitForMeasurements();
1858 netDiag.dump(pw);
1859 }
1860 }
1861
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001863 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1864 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001865 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001866
Erik Kline7747fd42017-05-12 16:52:48 +09001867 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001868 dumpNetworkDiagnostics(pw);
1869 return;
Erik Klineee363c42017-05-29 09:11:03 +09001870 } else if (argsContain(args, TETHERING_ARG)) {
1871 mTethering.dump(fd, pw, args);
1872 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001873 }
Erik Kline379747a2015-06-05 17:47:34 +09001874
Lorenzo Colittie3805462015-06-03 11:18:24 +09001875 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001876 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001877 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001878 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001879 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001880 pw.println();
1881
Paul Jensen85cf78e2015-06-25 13:25:07 -04001882 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001883 pw.print("Active default network: ");
1884 if (defaultNai == null) {
1885 pw.println("none");
1886 } else {
1887 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001888 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001889 pw.println();
1890
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001891 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001892 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001893 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1894 pw.println(nai.toString());
1895 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001896 pw.println(String.format(
1897 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1898 nai.numForegroundNetworkRequests(),
1899 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1900 nai.numBackgroundNetworkRequests(),
1901 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001902 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001903 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1904 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001905 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001906 pw.decreaseIndent();
1907 pw.println("Lingered:");
1908 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001909 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001910 pw.decreaseIndent();
1911 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001912 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001913 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001914 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001915
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001916 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001917 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001918 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1919 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001920 }
1921 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001922 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001923
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001924 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001925
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001926 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001927 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001928
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001929 pw.println();
1930 mKeepaliveTracker.dump(pw);
1931
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001932 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001933 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001934
Erik Kline7747fd42017-05-12 16:52:48 +09001935 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001936 pw.println();
1937 synchronized (mValidationLogs) {
1938 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001939 for (ValidationLog p : mValidationLogs) {
1940 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001941 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001942 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001943 pw.decreaseIndent();
1944 }
1945 }
Erik Kline7523eb32015-07-09 18:24:03 +09001946
1947 pw.println();
1948 pw.println("mNetworkRequestInfoLogs (most recent first):");
1949 pw.increaseIndent();
1950 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1951 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001952
1953 pw.println();
1954 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1955 pw.increaseIndent();
1956 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1957 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001958
1959 pw.println();
1960 pw.println("NetTransition WakeLock activity (most recent first):");
1961 pw.increaseIndent();
1962 mWakelockLogs.reverseDump(fd, pw, args);
1963 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001964 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001965 }
1966
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001967 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001968 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001969 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001970 if (officialNai != null && officialNai.equals(nai)) return true;
1971 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001972 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001973 " - " + nai);
1974 }
1975 return false;
1976 }
1977
Robert Greenwalt42acef32009-08-12 16:08:25 -07001978 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001979 private class NetworkStateTrackerHandler extends Handler {
1980 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001981 super(looper);
1982 }
1983
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001984 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001985 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001986 default:
1987 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001988 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001989 handleAsyncChannelHalfConnect(msg);
1990 break;
1991 }
1992 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1993 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1994 if (nai != null) nai.asyncChannel.disconnect();
1995 break;
1996 }
1997 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1998 handleAsyncChannelDisconnected(msg);
1999 break;
2000 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002001 }
2002 return true;
2003 }
2004
2005 private void maybeHandleNetworkAgentMessage(Message msg) {
2006 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2007 if (nai == null) {
2008 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002009 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002010 }
2011 return;
2012 }
2013
2014 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002015 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002016 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2017 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002018 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2019 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002020 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002021 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002022 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002023 break;
2024 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002025 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002026 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002027 break;
2028 }
2029 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002030 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002031 updateNetworkInfo(nai, info);
2032 break;
2033 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002034 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002035 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002036 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002037 break;
2038 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002039 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002040 try {
2041 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002042 } catch (Exception e) {
2043 // Never crash!
2044 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002045 }
2046 break;
2047 }
2048 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002049 try {
2050 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002051 } catch (Exception e) {
2052 // Never crash!
2053 loge("Exception in removeVpnUidRanges: " + e);
2054 }
2055 break;
2056 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002057 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002058 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2059 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002060 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002061 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002062 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002063 break;
2064 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002065 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002066 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2067 break;
2068 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002069 }
2070 }
2071
2072 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2073 switch (msg.what) {
2074 default:
2075 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002076 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002077 final NetworkAgentInfo nai;
2078 synchronized (mNetworkForNetId) {
2079 nai = mNetworkForNetId.get(msg.arg2);
2080 }
2081 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002082 final boolean valid =
2083 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002084 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002085 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2086 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002087 if (valid != nai.lastValidated) {
2088 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002089 nai.lastValidated = valid;
2090 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002091 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002092 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2093 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002094 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002095 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002096 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002097 Bundle redirectUrlBundle = new Bundle();
2098 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002099 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002100 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002101 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002102 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002103 if (wasValidated && !nai.lastValidated) {
2104 handleNetworkUnvalidated(nai);
2105 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002106 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002107 break;
2108 }
Paul Jensen869868be2014-05-15 10:33:05 -04002109 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002110 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002111 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002112 final NetworkAgentInfo nai;
2113 synchronized (mNetworkForNetId) {
2114 nai = mNetworkForNetId.get(netId);
2115 }
Calvin Onbe96da12016-10-11 15:10:46 -07002116 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002117 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002118 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002119 nai.lastCaptivePortalDetected = visible;
2120 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002121 if (nai.lastCaptivePortalDetected &&
2122 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2123 if (DBG) log("Avoiding captive portal network: " + nai.name());
2124 nai.asyncChannel.sendMessage(
2125 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2126 teardownUnneededNetwork(nai);
2127 break;
2128 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002129 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002130 }
2131 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002132 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002133 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002134 if (nai == null) {
2135 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2136 break;
2137 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002138 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002139 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002140 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002141 }
Paul Jensen869868be2014-05-15 10:33:05 -04002142 }
Paul Jensen869868be2014-05-15 10:33:05 -04002143 break;
2144 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002145 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002146 return true;
2147 }
2148
Calvin Onbe96da12016-10-11 15:10:46 -07002149 private int getCaptivePortalMode() {
2150 return Settings.Global.getInt(mContext.getContentResolver(),
2151 Settings.Global.CAPTIVE_PORTAL_MODE,
2152 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2153 }
2154
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002155 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2156 switch (msg.what) {
2157 default:
2158 return false;
2159 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2160 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2161 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2162 handleLingerComplete(nai);
2163 }
2164 break;
2165 }
2166 }
2167 return true;
2168 }
2169
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002170 @Override
2171 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002172 if (!maybeHandleAsyncChannelMessage(msg) &&
2173 !maybeHandleNetworkMonitorMessage(msg) &&
2174 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002175 maybeHandleNetworkAgentMessage(msg);
2176 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002177 }
2178 }
2179
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002180 private void updateLingerState(NetworkAgentInfo nai, long now) {
2181 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2182 // 2. If the network was lingering and there are now requests, unlinger it.
2183 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2184 // one lingered request, start lingering.
2185 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002186 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002187 if (DBG) log("Unlingering " + nai.name());
2188 nai.unlinger();
2189 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002190 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002191 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002192 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002193 nai.linger();
2194 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2195 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2196 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002197 }
2198
Robert Greenwalt7b816022014-04-18 15:25:25 -07002199 private void handleAsyncChannelHalfConnect(Message msg) {
2200 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002201 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002202 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2203 if (VDBG) log("NetworkFactory connected");
2204 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002205 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002206 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002207 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002208 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002209 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002210 }
2211 } else {
2212 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002213 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002214 }
2215 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2216 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2217 if (VDBG) log("NetworkAgent connected");
2218 // A network agent has requested a connection. Establish the connection.
2219 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2220 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2221 } else {
2222 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002223 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002224 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002225 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002226 synchronized (mNetworkForNetId) {
2227 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002228 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002229 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002230 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002231 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002232 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002233 }
2234 }
2235 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002236
Robert Greenwalt7b816022014-04-18 15:25:25 -07002237 private void handleAsyncChannelDisconnected(Message msg) {
2238 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2239 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002240 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002241 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002242 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002243 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002244 // TODO - if we move the logic to the network agent (have them disconnect
2245 // because they lost all their requests or because their score isn't good)
2246 // then they would disconnect organically, report their new state and then
2247 // disconnect the channel.
2248 if (nai.networkInfo.isConnected()) {
2249 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2250 null, null);
2251 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002252 final boolean wasDefault = isDefaultNetwork(nai);
2253 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002254 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002255 // Log default network disconnection before required book-keeping.
2256 // Let rematchAllNetworksAndRequests() below record a new default network event
2257 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2258 // whose timestamps tell how long it takes to recover a default network.
2259 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002260 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002261 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002262 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2263 // by other networks that are already connected. Perhaps that can be done by
2264 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2265 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002266 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002267 mKeepaliveTracker.handleStopAllKeepalives(nai,
2268 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002269 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2270 // Disable wakeup packet monitoring for each interface.
2271 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2272 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002273 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002274 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002275 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002276 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002277 // Remove the NetworkAgent, but don't mark the netId as
2278 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002279 mNetworkForNetId.remove(nai.network.netId);
2280 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002281 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002282 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2283 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002284 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2285 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2286 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002287 sendUpdatedScoreToFactories(request, 0);
2288 }
2289 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002290 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002291 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002292 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002293 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002294 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002295 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002296 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002297 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002298 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002299 if (nai.created) {
2300 // Tell netd to clean up the configuration for this network
2301 // (routing rules, DNS, etc).
2302 // This may be slow as it requires a lot of netd shelling out to ip and
2303 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2304 // after we've rematched networks with requests which should make a potential
2305 // fallback network the default or requested a new network from the
2306 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2307 // long time.
2308 try {
2309 mNetd.removeNetwork(nai.network.netId);
2310 } catch (Exception e) {
2311 loge("Exception removing network: " + e);
2312 }
2313 }
2314 synchronized (mNetworkForNetId) {
2315 mNetIdInUse.delete(nai.network.netId);
2316 }
2317 } else {
2318 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2319 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002320 }
2321 }
2322
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002323 // If this method proves to be too slow then we can maintain a separate
2324 // pendingIntent => NetworkRequestInfo map.
2325 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2326 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2327 Intent intent = pendingIntent.getIntent();
2328 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2329 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2330 if (existingPendingIntent != null &&
2331 existingPendingIntent.getIntent().filterEquals(intent)) {
2332 return entry.getValue();
2333 }
2334 }
2335 return null;
2336 }
2337
2338 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2339 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2340
2341 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2342 if (existingRequest != null) { // remove the existing request.
2343 if (DBG) log("Replacing " + existingRequest.request + " with "
2344 + nri.request + " because their intents matched.");
2345 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2346 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002347 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002348 }
2349
Erik Klineda4bfa82015-04-30 12:58:40 +09002350 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002351 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002352 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002353 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002354 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002355 if (nri.request.networkCapabilities.hasSignalStrength() &&
2356 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2357 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002358 }
2359 }
2360 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002361 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002362 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002363 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002364 }
2365 }
2366
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002367 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2368 int callingUid) {
2369 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2370 if (nri != null) {
2371 handleReleaseNetworkRequest(nri.request, callingUid);
2372 }
2373 }
2374
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002375 // Determines whether the network is the best (or could become the best, if it validated), for
2376 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2377 // on the value of reason:
2378 //
2379 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2380 // then it should be torn down.
2381 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2382 // then it should be lingered.
2383 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2384 final int numRequests;
2385 switch (reason) {
2386 case TEARDOWN:
2387 numRequests = nai.numRequestNetworkRequests();
2388 break;
2389 case LINGER:
2390 numRequests = nai.numForegroundNetworkRequests();
2391 break;
2392 default:
2393 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2394 return true;
2395 }
2396
2397 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002398 return false;
2399 }
Paul Jensene0988542015-06-25 15:30:08 -04002400 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002401 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2402 // Background requests don't affect lingering.
2403 continue;
2404 }
2405
Paul Jensene0988542015-06-25 15:30:08 -04002406 // If this Network is already the highest scoring Network for a request, or if
2407 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002408 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002409 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002410 // Note that this catches two important cases:
2411 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2412 // is currently satisfying the request. This is desirable when
2413 // cellular ends up validating but WiFi does not.
2414 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002415 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002416 // WiFi ends up validating and out scoring cellular.
2417 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2418 nai.getCurrentScoreAsValidated())) {
2419 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002420 }
2421 }
Paul Jensene0988542015-06-25 15:30:08 -04002422 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002423 }
2424
Erik Klineacdd6392016-07-07 16:50:58 +09002425 private NetworkRequestInfo getNriForAppRequest(
2426 NetworkRequest request, int callingUid, String requestedOperation) {
2427 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2428
Robert Greenwalt9258c642014-03-26 16:47:06 -07002429 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002430 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002431 log(String.format("UID %d attempted to %s for unowned request %s",
2432 callingUid, requestedOperation, nri));
2433 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002434 }
Erik Klineacdd6392016-07-07 16:50:58 +09002435 }
2436
2437 return nri;
2438 }
2439
Erik Kline57faba92015-11-25 12:49:38 +09002440 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002441 if (mNetworkRequests.get(nri.request) == null) {
2442 return;
Erik Kline57faba92015-11-25 12:49:38 +09002443 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002444 if (mNetworkForRequestId.get(nri.request.requestId) != null) {
2445 return;
2446 }
2447 if (VDBG || (DBG && nri.request.isRequest())) {
2448 log("releasing " + nri.request + " (timeout)");
2449 }
2450 handleRemoveNetworkRequest(nri);
2451 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002452 }
2453
Erik Klineacdd6392016-07-07 16:50:58 +09002454 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002455 final NetworkRequestInfo nri =
2456 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2457 if (nri == null) {
2458 return;
Erik Kline57faba92015-11-25 12:49:38 +09002459 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002460 if (VDBG || (DBG && nri.request.isRequest())) {
2461 log("releasing " + nri.request + " (release request)");
2462 }
2463 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002464 }
Erik Klineacdd6392016-07-07 16:50:58 +09002465
Hugo Benichidba33db2017-03-23 22:40:44 +09002466 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002467 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002468 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002469 synchronized (mUidToNetworkRequestCount) {
2470 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2471 if (requests < 1) {
2472 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2473 nri.mUid);
2474 } else if (requests == 1) {
2475 mUidToNetworkRequestCount.removeAt(
2476 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2477 } else {
2478 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2479 }
2480 }
2481 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2482 if (nri.request.isRequest()) {
2483 boolean wasKept = false;
2484 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2485 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002486 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002487 nai.removeRequest(nri.request.requestId);
2488 if (VDBG) {
2489 log(" Removing from current network " + nai.name() +
2490 ", leaving " + nai.numNetworkRequests() + " requests.");
2491 }
2492 // If there are still lingered requests on this network, don't tear it down,
2493 // but resume lingering instead.
2494 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002495 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002496 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2497 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002498 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002499 wasKept = true;
2500 }
2501 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002502 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2503 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002504 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002505 }
Erik Klineacdd6392016-07-07 16:50:58 +09002506 }
2507
2508 // TODO: remove this code once we know that the Slog.wtf is never hit.
2509 //
2510 // Find all networks that are satisfying this request and remove the request
2511 // from their request lists.
2512 // TODO - it's my understanding that for a request there is only a single
2513 // network satisfying it, so this loop is wasteful
2514 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2515 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2516 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2517 otherNai.name() + ", but mNetworkAgentInfos says " +
2518 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002519 }
2520 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002521
Erik Klineacdd6392016-07-07 16:50:58 +09002522 // Maintain the illusion. When this request arrived, we might have pretended
2523 // that a network connected to serve it, even though the network was already
2524 // connected. Now that this request has gone away, we might have to pretend
2525 // that the network disconnected. LegacyTypeTracker will generate that
2526 // phantom disconnect for this type.
2527 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2528 boolean doRemove = true;
2529 if (wasKept) {
2530 // check if any of the remaining requests for this network are for the
2531 // same legacy type - if so, don't remove the nai
2532 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2533 NetworkRequest otherRequest = nai.requestAt(i);
2534 if (otherRequest.legacyType == nri.request.legacyType &&
2535 otherRequest.isRequest()) {
2536 if (DBG) log(" still have other legacy request - leaving");
2537 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002538 }
2539 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002540 }
2541
Erik Klineacdd6392016-07-07 16:50:58 +09002542 if (doRemove) {
2543 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002544 }
2545 }
Erik Klineacdd6392016-07-07 16:50:58 +09002546
2547 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2548 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2549 nri.request);
2550 }
2551 } else {
2552 // listens don't have a singular affectedNetwork. Check all networks to see
2553 // if this listen request applies and remove it.
2554 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2555 nai.removeRequest(nri.request.requestId);
2556 if (nri.request.networkCapabilities.hasSignalStrength() &&
2557 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2558 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2559 }
2560 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002561 }
2562 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002563
Lorenzo Colitti18660282016-07-04 12:55:44 +09002564 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002565 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2566 enforceConnectivityInternalPermission();
2567 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002568 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002569 }
2570
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002571 @Override
2572 public void setAvoidUnvalidated(Network network) {
2573 enforceConnectivityInternalPermission();
2574 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2575 }
2576
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002577 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2578 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2579 " accept=" + accept + " always=" + always);
2580
2581 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2582 if (nai == null) {
2583 // Nothing to do.
2584 return;
2585 }
2586
2587 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002588 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002589 return;
2590 }
2591
2592 if (!nai.networkMisc.explicitlySelected) {
2593 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2594 }
2595
2596 if (accept != nai.networkMisc.acceptUnvalidated) {
2597 int oldScore = nai.getCurrentScore();
2598 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002599 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002600 sendUpdatedScoreToFactories(nai);
2601 }
2602
2603 if (always) {
2604 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002605 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002606 }
2607
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002608 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002609 // Tell the NetworkAgent to not automatically reconnect to the network.
2610 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2611 // Teardown the nework.
2612 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002613 }
2614
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002615 }
2616
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002617 private void handleSetAvoidUnvalidated(Network network) {
2618 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2619 if (nai == null || nai.lastValidated) {
2620 // Nothing to do. The network either disconnected or revalidated.
2621 return;
2622 }
2623 if (!nai.avoidUnvalidated) {
2624 int oldScore = nai.getCurrentScore();
2625 nai.avoidUnvalidated = true;
2626 rematchAllNetworksAndRequests(nai, oldScore);
2627 sendUpdatedScoreToFactories(nai);
2628 }
2629 }
2630
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002631 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002632 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002633 mHandler.sendMessageDelayed(
2634 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2635 PROMPT_UNVALIDATED_DELAY_MS);
2636 }
2637
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002638 @Override
2639 public void startCaptivePortalApp(Network network) {
2640 enforceConnectivityInternalPermission();
2641 mHandler.post(() -> {
2642 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2643 if (nai == null) return;
2644 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2645 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2646 });
2647 }
2648
Hugo Benichic8e9e122016-09-14 23:23:08 +00002649 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002650 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002651 }
2652
Erik Kline065ab6e2016-10-02 18:02:14 +09002653 private void rematchForAvoidBadWifiUpdate() {
2654 rematchAllNetworksAndRequests(null, 0);
2655 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2656 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2657 sendUpdatedScoreToFactories(nai);
2658 }
2659 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002660 }
2661
Erik Kline065ab6e2016-10-02 18:02:14 +09002662 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002663 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002664 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002665 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002666 if (!configRestrict) {
2667 pw.println("Bad Wi-Fi avoidance: unrestricted");
2668 return;
2669 }
2670
2671 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2672 pw.increaseIndent();
2673 pw.println("Config restrict: " + configRestrict);
2674
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002675 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002676 String description;
2677 // Can't use a switch statement because strings are legal case labels, but null is not.
2678 if ("0".equals(value)) {
2679 description = "get stuck";
2680 } else if (value == null) {
2681 description = "prompt";
2682 } else if ("1".equals(value)) {
2683 description = "avoid";
2684 } else {
2685 description = value + " (?)";
2686 }
2687 pw.println("User setting: " + description);
2688 pw.println("Network overrides:");
2689 pw.increaseIndent();
2690 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2691 if (nai.avoidUnvalidated) {
2692 pw.println(nai.name());
2693 }
2694 }
2695 pw.decreaseIndent();
2696 pw.decreaseIndent();
2697 }
2698
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002699 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2700 final String action;
2701 switch (type) {
2702 case NO_INTERNET:
2703 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2704 break;
2705 case LOST_INTERNET:
2706 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2707 break;
2708 default:
2709 Slog.wtf(TAG, "Unknown notification type " + type);
2710 return;
2711 }
2712
2713 Intent intent = new Intent(action);
2714 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2715 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2716 intent.setClassName("com.android.settings",
2717 "com.android.settings.wifi.WifiNoInternetDialog");
2718
2719 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2720 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2721 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2722 }
2723
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002724 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002725 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002726 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2727
2728 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2729 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002730 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002731 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002732 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2733 return;
2734 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002735 showValidationNotification(nai, NotificationType.NO_INTERNET);
2736 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002737
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002738 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2739 NetworkCapabilities nc = nai.networkCapabilities;
2740 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002741
Erik Kline065ab6e2016-10-02 18:02:14 +09002742 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002743 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002744 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2745 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002746 }
2747
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002748 @Override
2749 public int getMultipathPreference(Network network) {
2750 enforceAccessPermission();
2751
2752 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2753 if (nai != null && !nai.networkInfo.isMetered()) {
2754 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2755 }
2756
2757 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2758 }
2759
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002760 private class InternalHandler extends Handler {
2761 public InternalHandler(Looper looper) {
2762 super(looper);
2763 }
2764
2765 @Override
2766 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002767 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002768 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002769 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002770 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002771 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002772 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002773 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002774 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002775 break;
2776 }
Jason Monkdecd2952013-10-10 14:02:51 -04002777 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002778 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002779 break;
2780 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002781 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002782 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2783 break;
2784 }
2785 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2786 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002787 break;
2788 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002789 case EVENT_REGISTER_NETWORK_AGENT: {
2790 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2791 break;
2792 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002793 case EVENT_REGISTER_NETWORK_REQUEST:
2794 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002795 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002796 break;
2797 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002798 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2799 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002800 handleRegisterNetworkRequestWithIntent(msg);
2801 break;
2802 }
Erik Kline57faba92015-11-25 12:49:38 +09002803 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2804 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2805 handleTimedOutNetworkRequest(nri);
2806 break;
2807 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002808 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2809 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2810 break;
2811 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002812 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002813 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002814 break;
2815 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002816 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002817 Network network = (Network) msg.obj;
2818 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002819 break;
2820 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002821 case EVENT_SET_AVOID_UNVALIDATED: {
2822 handleSetAvoidUnvalidated((Network) msg.obj);
2823 break;
2824 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002825 case EVENT_PROMPT_UNVALIDATED: {
2826 handlePromptUnvalidated((Network) msg.obj);
2827 break;
2828 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002829 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2830 handleMobileDataAlwaysOn();
2831 break;
2832 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002833 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2834 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2835 mKeepaliveTracker.handleStartKeepalive(msg);
2836 break;
2837 }
2838 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2839 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2840 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2841 int slot = msg.arg1;
2842 int reason = msg.arg2;
2843 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2844 break;
2845 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002846 case EVENT_SYSTEM_READY: {
2847 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2848 nai.networkMonitor.systemReady = true;
2849 }
2850 break;
2851 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002852 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002853 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002854 break;
2855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002856 }
2857 }
2858 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002859
2860 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002861 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002862 public int tether(String iface, String callerPkg) {
2863 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002864 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002865 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002866 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002867 } else {
2868 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2869 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002870 }
2871
2872 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002873 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002874 public int untether(String iface, String callerPkg) {
2875 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002876
2877 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002878 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002879 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002880 } else {
2881 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2882 }
2883 }
2884
2885 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002886 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002887 public int getLastTetherError(String iface) {
2888 enforceTetherAccessPermission();
2889
2890 if (isTetheringSupported()) {
2891 return mTethering.getLastTetherError(iface);
2892 } else {
2893 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2894 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002895 }
2896
2897 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002898 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002899 public String[] getTetherableUsbRegexs() {
2900 enforceTetherAccessPermission();
2901 if (isTetheringSupported()) {
2902 return mTethering.getTetherableUsbRegexs();
2903 } else {
2904 return new String[0];
2905 }
2906 }
2907
Lorenzo Colitti18660282016-07-04 12:55:44 +09002908 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002909 public String[] getTetherableWifiRegexs() {
2910 enforceTetherAccessPermission();
2911 if (isTetheringSupported()) {
2912 return mTethering.getTetherableWifiRegexs();
2913 } else {
2914 return new String[0];
2915 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002916 }
2917
Lorenzo Colitti18660282016-07-04 12:55:44 +09002918 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002919 public String[] getTetherableBluetoothRegexs() {
2920 enforceTetherAccessPermission();
2921 if (isTetheringSupported()) {
2922 return mTethering.getTetherableBluetoothRegexs();
2923 } else {
2924 return new String[0];
2925 }
2926 }
2927
Lorenzo Colitti18660282016-07-04 12:55:44 +09002928 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002929 public int setUsbTethering(boolean enable, String callerPkg) {
2930 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002931 if (isTetheringSupported()) {
2932 return mTethering.setUsbTethering(enable);
2933 } else {
2934 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2935 }
2936 }
2937
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002938 // TODO - move iface listing, queries, etc to new module
2939 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002940 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002941 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002942 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002943 return mTethering.getTetherableIfaces();
2944 }
2945
Lorenzo Colitti18660282016-07-04 12:55:44 +09002946 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002947 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002948 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002949 return mTethering.getTetheredIfaces();
2950 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002951
Lorenzo Colitti18660282016-07-04 12:55:44 +09002952 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002953 public String[] getTetheringErroredIfaces() {
2954 enforceTetherAccessPermission();
2955 return mTethering.getErroredIfaces();
2956 }
2957
Lorenzo Colitti18660282016-07-04 12:55:44 +09002958 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002959 public String[] getTetheredDhcpRanges() {
2960 enforceConnectivityInternalPermission();
2961 return mTethering.getTetheredDhcpRanges();
2962 }
2963
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002964 // if ro.tether.denied = true we default to no tethering
2965 // gservices could set the secure setting to 1 though to enable it on a build where it
2966 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002967 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002968 public boolean isTetheringSupported() {
2969 enforceTetherAccessPermission();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002970 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
2971 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
2972 Settings.Global.TETHER_SUPPORTED, defaultVal));
2973 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002974 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07002975
2976 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
2977 boolean adminUser = false;
2978 final long token = Binder.clearCallingIdentity();
2979 try {
2980 adminUser = mUserManager.isAdminUser();
2981 } finally {
2982 Binder.restoreCallingIdentity(token);
2983 }
2984
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002985 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002986 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002987
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002988 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002989 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
2990 String callerPkg) {
2991 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002992 if (!isTetheringSupported()) {
2993 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2994 return;
2995 }
2996 mTethering.startTethering(type, receiver, showProvisioningUi);
2997 }
2998
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002999 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003000 public void stopTethering(int type, String callerPkg) {
3001 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003002 mTethering.stopTethering(type);
3003 }
3004
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003005 // Called when we lose the default network and have no replacement yet.
3006 // This will automatically be cleared after X seconds or a new default network
3007 // becomes CONNECTED, whichever happens first. The timer is started by the
3008 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003009 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003010 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003011 if (mNetTransitionWakeLock.isHeld()) {
3012 return;
3013 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003014 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003015 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003016 mWakelockLogs.log("ACQUIRE for " + forWhom);
3017 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3018 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003019 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003020
Hugo Benichi4c31b342017-03-30 23:18:10 +09003021 // Called when we gain a new default network to release the network transition wakelock in a
3022 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3023 // message is cancelled.
3024 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003025 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003026 if (!mNetTransitionWakeLock.isHeld()) {
3027 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003028 }
3029 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003030 // Cancel self timeout on wakelock hold.
3031 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3032 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3033 mHandler.sendMessageDelayed(msg, 1000);
3034 }
3035
3036 // Called when either message of ensureNetworkTransitionWakelock or
3037 // scheduleReleaseNetworkTransitionWakelock is processed.
3038 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3039 String event = eventName(eventId);
3040 synchronized (this) {
3041 if (!mNetTransitionWakeLock.isHeld()) {
3042 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3043 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3044 return;
3045 }
3046 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003047 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003048 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003049 }
3050
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003051 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003052 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003053 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003054 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003055 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003056 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003057 }
3058
Lorenzo Colitti18660282016-07-04 12:55:44 +09003059 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003060 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003061 enforceAccessPermission();
3062 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003063 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003064 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003065 mHandler.sendMessage(
3066 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3067 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003068
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003069 private void handleReportNetworkConnectivity(
3070 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003071 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003072 if (network == null) {
3073 nai = getDefaultNetwork();
3074 } else {
3075 nai = getNetworkAgentInfoForNetwork(network);
3076 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003077 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3078 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3079 return;
3080 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003081 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003082 if (hasConnectivity == nai.lastValidated) {
3083 return;
3084 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003085 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003086 int netid = nai.network.netId;
3087 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003088 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003089 // Validating a network that has not yet connected could result in a call to
3090 // rematchNetworkAndRequests() which is not meant to work on such networks.
3091 if (!nai.everConnected) {
3092 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003093 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003094 LinkProperties lp = getLinkProperties(nai);
3095 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3096 return;
3097 }
3098 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003099 }
3100
Paul Jensencee9b512015-05-06 07:32:40 -04003101 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003102 // this information is already available as a world read/writable jvm property
3103 // so this API change wouldn't have a benifit. It also breaks the passing
3104 // of proxy info to all the JVMs.
3105 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003106 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003107 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003108 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3109 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003110 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003111 }
3112
Lorenzo Colitti18660282016-07-04 12:55:44 +09003113 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003114 public ProxyInfo getProxyForNetwork(Network network) {
3115 if (network == null) return getDefaultProxy();
3116 final ProxyInfo globalProxy = getGlobalProxy();
3117 if (globalProxy != null) return globalProxy;
3118 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3119 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3120 // caller may not have.
3121 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3122 if (nai == null) return null;
3123 synchronized (nai) {
3124 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3125 if (proxyInfo == null) return null;
3126 return new ProxyInfo(proxyInfo);
3127 }
3128 }
3129
Paul Jensene0bef712014-12-10 15:12:18 -05003130 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3131 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3132 // proxy is null then there is no proxy in place).
3133 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3134 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3135 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3136 proxy = null;
3137 }
3138 return proxy;
3139 }
3140
3141 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3142 // better for determining if a new proxy broadcast is necessary:
3143 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3144 // avoid unnecessary broadcasts.
3145 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3146 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3147 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3148 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3149 // all set.
3150 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3151 a = canonicalizeProxyInfo(a);
3152 b = canonicalizeProxyInfo(b);
3153 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3154 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3155 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3156 }
3157
Jason Monk207900c2014-04-25 15:00:09 -04003158 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003159 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003160
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003161 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003162 if (proxyProperties == mGlobalProxy) return;
3163 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3164 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3165
3166 String host = "";
3167 int port = 0;
3168 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003169 String pacFileUrl = "";
3170 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003171 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003172 if (!proxyProperties.isValid()) {
3173 if (DBG)
3174 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3175 return;
3176 }
Jason Monk207900c2014-04-25 15:00:09 -04003177 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003178 host = mGlobalProxy.getHost();
3179 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003180 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003181 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003182 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003183 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003184 } else {
3185 mGlobalProxy = null;
3186 }
3187 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003188 final long token = Binder.clearCallingIdentity();
3189 try {
3190 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3191 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3192 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3193 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003194 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003195 } finally {
3196 Binder.restoreCallingIdentity(token);
3197 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003198
Jason Monkcf0f97a2014-10-02 15:39:38 -04003199 if (mGlobalProxy == null) {
3200 proxyProperties = mDefaultProxy;
3201 }
3202 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003203 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003204 }
3205
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003206 private void loadGlobalProxy() {
3207 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003208 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3209 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3210 String exclList = Settings.Global.getString(res,
3211 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003212 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3213 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003214 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003215 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003216 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003217 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003218 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003219 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003220 if (!proxyProperties.isValid()) {
3221 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3222 return;
3223 }
3224
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003225 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003226 mGlobalProxy = proxyProperties;
3227 }
3228 }
3229 }
3230
Jason Monk207900c2014-04-25 15:00:09 -04003231 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003232 // this information is already available as a world read/writable jvm property
3233 // so this API change wouldn't have a benifit. It also breaks the passing
3234 // of proxy info to all the JVMs.
3235 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003236 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003237 return mGlobalProxy;
3238 }
3239 }
3240
Jason Monk207900c2014-04-25 15:00:09 -04003241 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003242 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003243 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003244 proxy = null;
3245 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003246 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003247 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003248 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003249 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003250 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3251 return;
3252 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003253
3254 // This call could be coming from the PacManager, containing the port of the local
3255 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3256 // global (to get the correct local port), and send a broadcast.
3257 // TODO: Switch PacManager to have its own message to send back rather than
3258 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003259 if ((mGlobalProxy != null) && (proxy != null)
3260 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003261 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3262 mGlobalProxy = proxy;
3263 sendProxyBroadcast(mGlobalProxy);
3264 return;
3265 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003266 mDefaultProxy = proxy;
3267
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003268 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003269 if (!mDefaultProxyDisabled) {
3270 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003271 }
3272 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003273 }
3274
Paul Jensene0bef712014-12-10 15:12:18 -05003275 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3276 // This method gets called when any network changes proxy, but the broadcast only ever contains
3277 // the default proxy (even if it hasn't changed).
3278 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3279 // world where an app might be bound to a non-default network.
3280 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3281 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3282 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3283
3284 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3285 sendProxyBroadcast(getDefaultProxy());
3286 }
3287 }
3288
Robert Greenwalt434203a2010-10-11 16:00:27 -07003289 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003290 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3291 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003292 if (!TextUtils.isEmpty(proxy)) {
3293 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003294 if (data.length == 0) {
3295 return;
3296 }
3297
Robert Greenwalt434203a2010-10-11 16:00:27 -07003298 String proxyHost = data[0];
3299 int proxyPort = 8080;
3300 if (data.length > 1) {
3301 try {
3302 proxyPort = Integer.parseInt(data[1]);
3303 } catch (NumberFormatException e) {
3304 return;
3305 }
3306 }
Jason Monk207900c2014-04-25 15:00:09 -04003307 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003308 setGlobalProxy(p);
3309 }
3310 }
3311
Jason Monk207900c2014-04-25 15:00:09 -04003312 private void sendProxyBroadcast(ProxyInfo proxy) {
3313 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003314 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003315 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003316 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003317 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3318 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003319 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003320 final long ident = Binder.clearCallingIdentity();
3321 try {
3322 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3323 } finally {
3324 Binder.restoreCallingIdentity(ident);
3325 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003326 }
3327
3328 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003329 final private HashMap<Uri, Integer> mUriEventMap;
3330 final private Context mContext;
3331 final private Handler mHandler;
3332
3333 SettingsObserver(Context context, Handler handler) {
3334 super(null);
3335 mUriEventMap = new HashMap<Uri, Integer>();
3336 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003337 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003338 }
3339
Erik Klineda4bfa82015-04-30 12:58:40 +09003340 void observe(Uri uri, int what) {
3341 mUriEventMap.put(uri, what);
3342 final ContentResolver resolver = mContext.getContentResolver();
3343 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003344 }
3345
3346 @Override
3347 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003348 Slog.wtf(TAG, "Should never be reached.");
3349 }
3350
3351 @Override
3352 public void onChange(boolean selfChange, Uri uri) {
3353 final Integer what = mUriEventMap.get(uri);
3354 if (what != null) {
3355 mHandler.obtainMessage(what.intValue()).sendToTarget();
3356 } else {
3357 loge("No matching event to send for URI=" + uri);
3358 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003359 }
3360 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003361
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003362 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003363 Slog.d(TAG, s);
3364 }
3365
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003366 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003367 Slog.e(TAG, s);
3368 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003369
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003370 private static void loge(String s, Throwable t) {
3371 Slog.e(TAG, s, t);
3372 }
3373
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003374 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003375 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003376 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3377 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3378 *
3379 * @param oldPackage Package name of the application which currently controls VPN, which will
3380 * be replaced. If there is no such application, this should should either be
3381 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3382 * @param newPackage Package name of the application which should gain control of VPN, or
3383 * {@code null} to disable.
3384 * @param userId User for whom to prepare the new VPN.
3385 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003386 * @hide
3387 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003388 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003389 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3390 int userId) {
3391 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003392 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003393
Hugo Benichi20035e02017-04-26 14:53:28 +09003394 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003395 Vpn vpn = mVpns.get(userId);
3396 if (vpn != null) {
3397 return vpn.prepare(oldPackage, newPackage);
3398 } else {
3399 return false;
3400 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003401 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003402 }
3403
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003404 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003405 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3406 * This method is used by system-privileged apps.
3407 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3408 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3409 *
3410 * @param packageName The package for which authorization state should change.
3411 * @param userId User for whom {@code packageName} is installed.
3412 * @param authorized {@code true} if this app should be able to start a VPN connection without
3413 * explicit user approval, {@code false} if not.
3414 *
Jeff Davidson05542602014-08-11 14:07:27 -07003415 * @hide
3416 */
3417 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003418 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3419 enforceCrossUserPermission(userId);
3420
Hugo Benichi20035e02017-04-26 14:53:28 +09003421 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003422 Vpn vpn = mVpns.get(userId);
3423 if (vpn != null) {
3424 vpn.setPackageAuthorization(packageName, authorized);
3425 }
Jeff Davidson05542602014-08-11 14:07:27 -07003426 }
3427 }
3428
3429 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003430 * Configure a TUN interface and return its file descriptor. Parameters
3431 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003432 * and not available in ConnectivityManager. Permissions are checked in
3433 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003434 * @hide
3435 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003436 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003437 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003438 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003439 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003440 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003441 return mVpns.get(user).establish(config);
3442 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003443 }
3444
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003445 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003446 * Start legacy VPN, controlling native daemons as needed. Creates a
3447 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003448 */
3449 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003450 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003451 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003452 final LinkProperties egress = getActiveLinkProperties();
3453 if (egress == null) {
3454 throw new IllegalStateException("Missing active network connection");
3455 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003456 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003457 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003458 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3459 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003460 }
3461
3462 /**
3463 * Return the information of the ongoing legacy VPN. This method is used
3464 * by VpnSettings and not available in ConnectivityManager. Permissions
3465 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003466 */
3467 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003468 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3469 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003470
Hugo Benichi20035e02017-04-26 14:53:28 +09003471 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003472 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003473 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003474 }
3475
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003476 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003477 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3478 * and not available in ConnectivityManager.
3479 */
3480 @Override
3481 public VpnInfo[] getAllVpnInfo() {
3482 enforceConnectivityInternalPermission();
3483 if (mLockdownEnabled) {
3484 return new VpnInfo[0];
3485 }
3486
Hugo Benichi20035e02017-04-26 14:53:28 +09003487 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003488 List<VpnInfo> infoList = new ArrayList<>();
3489 for (int i = 0; i < mVpns.size(); i++) {
3490 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3491 if (info != null) {
3492 infoList.add(info);
3493 }
3494 }
3495 return infoList.toArray(new VpnInfo[infoList.size()]);
3496 }
3497 }
3498
3499 /**
3500 * @return VPN information for accounting, or null if we can't retrieve all required
3501 * information, e.g primary underlying iface.
3502 */
3503 @Nullable
3504 private VpnInfo createVpnInfo(Vpn vpn) {
3505 VpnInfo info = vpn.getVpnInfo();
3506 if (info == null) {
3507 return null;
3508 }
3509 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3510 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3511 // the underlyingNetworks list.
3512 if (underlyingNetworks == null) {
3513 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3514 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3515 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3516 }
3517 } else if (underlyingNetworks.length > 0) {
3518 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3519 if (linkProperties != null) {
3520 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3521 }
3522 }
3523 return info.primaryUnderlyingIface == null ? null : info;
3524 }
3525
3526 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003527 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3528 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003529 * Permissions are checked in Vpn class.
3530 * @hide
3531 */
3532 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003533 public VpnConfig getVpnConfig(int userId) {
3534 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003535 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003536 Vpn vpn = mVpns.get(userId);
3537 if (vpn != null) {
3538 return vpn.getVpnConfig();
3539 } else {
3540 return null;
3541 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003542 }
3543 }
3544
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003545 @Override
3546 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003547 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3548 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3549 return false;
3550 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003551
3552 // Tear down existing lockdown if profile was removed
3553 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3554 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003555 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3556 if (profileTag == null) {
3557 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3558 return false;
3559 }
3560 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003561 final VpnProfile profile = VpnProfile.decode(
3562 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003563 if (profile == null) {
3564 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3565 setLockdownTracker(null);
3566 return true;
3567 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003568 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003569 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003570 Vpn vpn = mVpns.get(user);
3571 if (vpn == null) {
3572 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3573 return false;
3574 }
3575 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003576 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003577 } else {
3578 setLockdownTracker(null);
3579 }
3580
3581 return true;
3582 }
3583
3584 /**
3585 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3586 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3587 */
3588 private void setLockdownTracker(LockdownVpnTracker tracker) {
3589 // Shutdown any existing tracker
3590 final LockdownVpnTracker existing = mLockdownTracker;
3591 mLockdownTracker = null;
3592 if (existing != null) {
3593 existing.shutdown();
3594 }
3595
Robin Leec3736bc2017-03-10 16:19:54 +00003596 if (tracker != null) {
3597 mLockdownTracker = tracker;
3598 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003599 }
3600 }
3601
3602 private void throwIfLockdownEnabled() {
3603 if (mLockdownEnabled) {
3604 throw new IllegalStateException("Unavailable in lockdown mode");
3605 }
3606 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003607
Robin Lee244ce8e2016-01-05 18:03:46 +00003608 /**
Robin Lee17e61832016-05-09 13:46:28 +01003609 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3610 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003611 *
Robin Lee17e61832016-05-09 13:46:28 +01003612 * @return {@code true} if the service was started, the service was already connected, or there
3613 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003614 */
Robin Lee17e61832016-05-09 13:46:28 +01003615 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003616 synchronized (mVpns) {
3617 Vpn vpn = mVpns.get(userId);
3618 if (vpn == null) {
3619 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3620 // exists already.
3621 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3622 return false;
3623 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003624
Robin Lee812800c2016-05-13 15:38:08 +01003625 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003626 }
3627 }
3628
3629 @Override
Robin Leedc679712016-05-03 13:23:03 +01003630 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003631 enforceConnectivityInternalPermission();
3632 enforceCrossUserPermission(userId);
3633
3634 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3635 if (LockdownVpnTracker.isEnabled()) {
3636 return false;
3637 }
3638
Robin Lee244ce8e2016-01-05 18:03:46 +00003639 synchronized (mVpns) {
3640 Vpn vpn = mVpns.get(userId);
3641 if (vpn == null) {
3642 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3643 return false;
3644 }
Robin Lee17e61832016-05-09 13:46:28 +01003645 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003646 return false;
3647 }
Robin Lee17e61832016-05-09 13:46:28 +01003648 if (!startAlwaysOnVpn(userId)) {
3649 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003650 return false;
3651 }
3652 }
3653 return true;
3654 }
3655
3656 @Override
3657 public String getAlwaysOnVpnPackage(int userId) {
3658 enforceConnectivityInternalPermission();
3659 enforceCrossUserPermission(userId);
3660
3661 synchronized (mVpns) {
3662 Vpn vpn = mVpns.get(userId);
3663 if (vpn == null) {
3664 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3665 return null;
3666 }
3667 return vpn.getAlwaysOnPackage();
3668 }
3669 }
3670
Wink Savilleab9321d2013-06-29 21:10:57 -07003671 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003672 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003673 // TODO: Remove? Any reason to trigger a provisioning check?
3674 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003675 }
3676
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003677 /** Location to an updatable file listing carrier provisioning urls.
3678 * An example:
3679 *
3680 * <?xml version="1.0" encoding="utf-8"?>
3681 * <provisioningUrls>
3682 * <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 -07003683 * </provisioningUrls>
3684 */
3685 private static final String PROVISIONING_URL_PATH =
3686 "/data/misc/radio/provisioning_urls.xml";
3687 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003688
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003689 /** XML tag for root element. */
3690 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3691 /** XML tag for individual url */
3692 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003693 /** XML attribute for mcc */
3694 private static final String ATTR_MCC = "mcc";
3695 /** XML attribute for mnc */
3696 private static final String ATTR_MNC = "mnc";
3697
Paul Jensen434dde82015-06-11 09:43:30 -04003698 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003699 FileReader fileReader = null;
3700 XmlPullParser parser = null;
3701 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003702
3703 try {
3704 fileReader = new FileReader(mProvisioningUrlFile);
3705 parser = Xml.newPullParser();
3706 parser.setInput(fileReader);
3707 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3708
3709 while (true) {
3710 XmlUtils.nextElement(parser);
3711
3712 String element = parser.getName();
3713 if (element == null) break;
3714
Paul Jensen434dde82015-06-11 09:43:30 -04003715 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003716 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3717 try {
3718 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3719 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3720 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3721 parser.next();
3722 if (parser.getEventType() == XmlPullParser.TEXT) {
3723 return parser.getText();
3724 }
3725 }
3726 }
3727 } catch (NumberFormatException e) {
3728 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3729 }
3730 }
3731 }
3732 return null;
3733 } catch (FileNotFoundException e) {
3734 loge("Carrier Provisioning Urls file not found");
3735 } catch (XmlPullParserException e) {
3736 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3737 } catch (IOException e) {
3738 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3739 } finally {
3740 if (fileReader != null) {
3741 try {
3742 fileReader.close();
3743 } catch (IOException e) {}
3744 }
3745 }
3746 return null;
3747 }
3748
Wink Saville42d4f082013-07-20 20:31:59 -07003749 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003750 public String getMobileProvisioningUrl() {
3751 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003752 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003753 if (TextUtils.isEmpty(url)) {
3754 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003755 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003756 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003757 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003758 }
Wink Saville8cf35602013-07-10 23:00:07 -07003759 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003760 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003761 String phoneNumber = mTelephonyManager.getLine1Number();
3762 if (TextUtils.isEmpty(phoneNumber)) {
3763 phoneNumber = "0000000000";
3764 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003765 url = String.format(url,
3766 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3767 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003768 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003769 }
3770
Wink Savilleab9321d2013-06-29 21:10:57 -07003771 return url;
3772 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003773
Wink Saville948282b2013-08-29 08:55:16 -07003774 @Override
3775 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003776 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003777 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003778 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3779 return;
3780 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003781 final long ident = Binder.clearCallingIdentity();
3782 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003783 // Concatenate the range of types onto the range of NetIDs.
3784 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3785 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003786 } finally {
3787 Binder.restoreCallingIdentity(ident);
3788 }
Wink Saville948282b2013-08-29 08:55:16 -07003789 }
Wink Saville7788c612013-08-29 14:57:08 -07003790
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003791 @Override
3792 public void setAirplaneMode(boolean enable) {
3793 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003794 final long ident = Binder.clearCallingIdentity();
3795 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003796 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003797 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003798 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3799 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003800 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003801 } finally {
3802 Binder.restoreCallingIdentity(ident);
3803 }
3804 }
3805
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003806 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003807 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003808 Vpn userVpn = mVpns.get(userId);
3809 if (userVpn != null) {
3810 loge("Starting user already has a VPN");
3811 return;
3812 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003813 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003814 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003815 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003816 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3817 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003818 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003819 }
3820
3821 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003822 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003823 Vpn userVpn = mVpns.get(userId);
3824 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003825 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003826 return;
3827 }
Robin Lee17e61832016-05-09 13:46:28 +01003828 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003829 mVpns.delete(userId);
3830 }
3831 }
3832
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003833 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003834 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003835 final int vpnsSize = mVpns.size();
3836 for (int i = 0; i < vpnsSize; i++) {
3837 Vpn vpn = mVpns.valueAt(i);
3838 vpn.onUserAdded(userId);
3839 }
3840 }
3841 }
3842
3843 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003844 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003845 final int vpnsSize = mVpns.size();
3846 for (int i = 0; i < vpnsSize; i++) {
3847 Vpn vpn = mVpns.valueAt(i);
3848 vpn.onUserRemoved(userId);
3849 }
3850 }
3851 }
3852
Robin Lee89e7a692016-02-29 14:38:17 +00003853 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003854 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3855 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3856 updateLockdownVpn();
3857 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003858 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003859 }
3860 }
3861
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003862 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3863 @Override
3864 public void onReceive(Context context, Intent intent) {
3865 final String action = intent.getAction();
3866 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3867 if (userId == UserHandle.USER_NULL) return;
3868
Robin Lee323f29d2016-05-04 16:38:06 +01003869 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003870 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003871 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003872 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003873 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3874 onUserAdded(userId);
3875 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3876 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003877 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3878 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003879 }
3880 }
3881 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003882
Robin Lee95204e02017-01-27 11:59:22 +00003883 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3884 @Override
3885 public void onReceive(Context context, Intent intent) {
3886 // Try creating lockdown tracker, since user present usually means
3887 // unlocked keystore.
3888 updateLockdownVpn();
3889 mContext.unregisterReceiver(this);
3890 }
3891 };
3892
Robert Greenwalta67be032014-05-16 15:49:14 -07003893 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3894 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003895 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3896 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003897
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003898 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3899 // Map from UID to number of NetworkRequests that UID has filed.
3900 @GuardedBy("mUidToNetworkRequestCount")
3901 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3902
Robert Greenwalta67be032014-05-16 15:49:14 -07003903 private static class NetworkFactoryInfo {
3904 public final String name;
3905 public final Messenger messenger;
3906 public final AsyncChannel asyncChannel;
3907
3908 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3909 this.name = name;
3910 this.messenger = messenger;
3911 this.asyncChannel = asyncChannel;
3912 }
3913 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003914
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003915 private void ensureNetworkRequestHasType(NetworkRequest request) {
3916 if (request.type == NetworkRequest.Type.NONE) {
3917 throw new IllegalArgumentException(
3918 "All NetworkRequests in ConnectivityService must have a type");
3919 }
3920 }
3921
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003922 /**
3923 * Tracks info about the requester.
3924 * Also used to notice when the calling process dies so we can self-expire
3925 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003926 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003927 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003928 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003929 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003930 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003931 final int mPid;
3932 final int mUid;
3933 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003934
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003935 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003936 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003937 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003938 mPendingIntent = pi;
3939 messenger = null;
3940 mBinder = null;
3941 mPid = getCallingPid();
3942 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003943 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003944 }
3945
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003946 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003947 super();
3948 messenger = m;
3949 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003950 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003951 mBinder = binder;
3952 mPid = getCallingPid();
3953 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003954 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003955 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003956
3957 try {
3958 mBinder.linkToDeath(this, 0);
3959 } catch (RemoteException e) {
3960 binderDied();
3961 }
3962 }
3963
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003964 private void enforceRequestCountLimit() {
3965 synchronized (mUidToNetworkRequestCount) {
3966 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3967 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09003968 throw new ServiceSpecificException(
3969 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003970 }
3971 mUidToNetworkRequestCount.put(mUid, networkRequests);
3972 }
3973 }
3974
Robert Greenwalt9258c642014-03-26 16:47:06 -07003975 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003976 if (mBinder != null) {
3977 mBinder.unlinkToDeath(this, 0);
3978 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003979 }
3980
3981 public void binderDied() {
3982 log("ConnectivityService NetworkRequestInfo binderDied(" +
3983 request + ", " + mBinder + ")");
3984 releaseNetworkRequest(request);
3985 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003986
3987 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003988 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003989 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003990 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003991 }
3992
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003993 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3994 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3995 if (badCapability != null) {
3996 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003997 }
3998 }
3999
Erik Kline9d598e12015-07-13 16:37:51 +09004000 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004001 final SortedSet<Integer> thresholds = new TreeSet();
4002 synchronized (nai) {
4003 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4004 if (nri.request.networkCapabilities.hasSignalStrength() &&
4005 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4006 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4007 }
4008 }
4009 }
Erik Kline9d598e12015-07-13 16:37:51 +09004010 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004011 }
4012
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004013 private void updateSignalStrengthThresholds(
4014 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4015 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004016 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004017 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4018
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004019 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004020 String detail;
4021 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4022 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4023 } else {
4024 detail = reason;
4025 }
4026 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4027 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4028 }
4029
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004030 nai.asyncChannel.sendMessage(
4031 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004032 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004033 }
4034
Etan Cohen859748f2017-04-03 17:42:34 -07004035 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4036 if (nc == null) {
4037 return;
4038 }
4039 NetworkSpecifier ns = nc.getNetworkSpecifier();
4040 if (ns == null) {
4041 return;
4042 }
4043 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4044 ns.assertValidFromUid(Binder.getCallingUid());
4045 }
4046
Robert Greenwalt9258c642014-03-26 16:47:06 -07004047 @Override
4048 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004049 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004050 final NetworkRequest.Type type = (networkCapabilities == null)
4051 ? NetworkRequest.Type.TRACK_DEFAULT
4052 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004053 // If the requested networkCapabilities is null, take them instead from
4054 // the default network request. This allows callers to keep track of
4055 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004056 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004057 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4058 enforceAccessPermission();
4059 } else {
4060 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4061 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004062 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4063 // of the app when the request is filed, but we never change the request if the app
4064 // changes network state. http://b/29964605
4065 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004066 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004067 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004068
Etan Cohenba07c8c2017-02-05 10:42:27 -08004069 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004070 throw new IllegalArgumentException("Bad timeout specified");
4071 }
Etan Cohen859748f2017-04-03 17:42:34 -07004072 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004073
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004074 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004075 nextNetworkRequestId(), type);
4076 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004077 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004078
4079 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004080 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004081 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004082 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004083 }
4084 return networkRequest;
4085 }
4086
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004087 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004088 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004089 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004090 } else {
4091 enforceChangePermission();
4092 }
4093 }
4094
fenglub15e72b2015-03-20 11:29:56 -07004095 @Override
fengludb571472015-04-21 17:12:05 -07004096 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004097 enforceAccessPermission();
4098 NetworkAgentInfo nai = null;
4099 if (network == null) {
4100 return false;
4101 }
4102 synchronized (mNetworkForNetId) {
4103 nai = mNetworkForNetId.get(network.netId);
4104 }
4105 if (nai != null) {
4106 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4107 return true;
4108 }
4109 return false;
4110 }
4111
Felipe Lemeee27cab2016-06-20 16:36:29 -07004112 private boolean isSystem(int uid) {
4113 return uid < Process.FIRST_APPLICATION_UID;
4114 }
fenglub15e72b2015-03-20 11:29:56 -07004115
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004116 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004117 final int uid = Binder.getCallingUid();
4118 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004119 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004120 return;
4121 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004122 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4123 // Policy already enforced.
4124 return;
4125 }
4126 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4127 // If UID is restricted, don't allow them to bring up metered APNs.
4128 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004129 }
4130 }
4131
Robert Greenwalt9258c642014-03-26 16:47:06 -07004132 @Override
4133 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4134 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004135 checkNotNull(operation, "PendingIntent cannot be null.");
4136 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4137 enforceNetworkRequestPermissions(networkCapabilities);
4138 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004139 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004140 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004141
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004142 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004143 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4144 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004145 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004146 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4147 nri));
4148 return networkRequest;
4149 }
4150
Jeremy Joslin79294842014-12-03 17:15:28 -08004151 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4152 mHandler.sendMessageDelayed(
4153 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4154 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4155 }
4156
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004157 @Override
4158 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004159 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004160 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4161 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004162 }
4163
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004164 // In order to implement the compatibility measure for pre-M apps that call
4165 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4166 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4167 // This ensures it has permission to do so.
4168 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4169 if (nc == null) {
4170 return false;
4171 }
4172 int[] transportTypes = nc.getTransportTypes();
4173 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4174 return false;
4175 }
4176 try {
4177 mContext.enforceCallingOrSelfPermission(
4178 android.Manifest.permission.ACCESS_WIFI_STATE,
4179 "ConnectivityService");
4180 } catch (SecurityException e) {
4181 return false;
4182 }
4183 return true;
4184 }
4185
Robert Greenwalt9258c642014-03-26 16:47:06 -07004186 @Override
4187 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4188 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004189 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4190 enforceAccessPermission();
4191 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004192
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004193 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4194 if (!ConnectivityManager.checkChangePermission(mContext)) {
4195 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4196 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4197 // onLost and onAvailable callbacks when networks move in and out of the background.
4198 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4199 // can't request networks.
4200 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4201 }
Etan Cohen859748f2017-04-03 17:42:34 -07004202 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004203
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004204 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004205 NetworkRequest.Type.LISTEN);
4206 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004207 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004208
4209 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4210 return networkRequest;
4211 }
4212
4213 @Override
4214 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4215 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004216 checkNotNull(operation, "PendingIntent cannot be null.");
4217 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4218 enforceAccessPermission();
4219 }
Etan Cohen859748f2017-04-03 17:42:34 -07004220 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004221
Erik Kline7523eb32015-07-09 18:24:03 +09004222 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004223 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4224 NetworkRequest.Type.LISTEN);
4225 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004226 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004227
4228 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004229 }
4230
Erik Klineacdd6392016-07-07 16:50:58 +09004231 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004232 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004233 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004234 mHandler.sendMessage(mHandler.obtainMessage(
4235 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004236 }
4237
4238 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004239 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004240 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004241 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4242 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004243 }
4244
Robert Greenwalta67be032014-05-16 15:49:14 -07004245 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004246 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004247 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4248 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4249 }
4250
4251 @Override
4252 public void unregisterNetworkFactory(Messenger messenger) {
4253 enforceConnectivityInternalPermission();
4254 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4255 }
4256
4257 private void handleUnregisterNetworkFactory(Messenger messenger) {
4258 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4259 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004260 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004261 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004262 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004263 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004264 }
4265
Robert Greenwalt7b816022014-04-18 15:25:25 -07004266 /**
4267 * NetworkAgentInfo supporting a request by requestId.
4268 * These have already been vetted (their Capabilities satisfy the request)
4269 * and the are the highest scored network available.
4270 * the are keyed off the Requests requestId.
4271 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004272 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004273 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4274 new SparseArray<NetworkAgentInfo>();
4275
Paul Jensen31a94f42015-02-13 14:18:39 -05004276 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4277 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004278 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4279 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004280 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4281 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4282 // there may not be a strict 1:1 correlation between the two.
4283 @GuardedBy("mNetworkForNetId")
4284 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004285
Robert Greenwalt7b816022014-04-18 15:25:25 -07004286 // NetworkAgentInfo keyed off its connecting messenger
4287 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004288 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004289 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4290 new HashMap<Messenger, NetworkAgentInfo>();
4291
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004292 @GuardedBy("mBlockedAppUids")
4293 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4294
Paul Jensen2c311d62014-11-17 12:34:51 -05004295 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004296 private final NetworkRequest mDefaultRequest;
4297
Erik Klineda4bfa82015-04-30 12:58:40 +09004298 // Request used to optionally keep mobile data active even when higher
4299 // priority networks like Wi-Fi are active.
4300 private final NetworkRequest mDefaultMobileDataRequest;
4301
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004302 private NetworkAgentInfo getDefaultNetwork() {
4303 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4304 }
4305
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004306 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004307 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004308 }
4309
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004310 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4311 return nri.request.requestId == mDefaultRequest.requestId;
4312 }
4313
Paul Jensen31a94f42015-02-13 14:18:39 -05004314 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004315 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004316 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004317 enforceConnectivityInternalPermission();
4318
Rubin Xu1bb5c082017-09-05 18:40:49 +01004319 LinkProperties lp = new LinkProperties(linkProperties);
4320 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004321 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4322 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004323 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004324 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4325 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004326 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004327 synchronized (this) {
4328 nai.networkMonitor.systemReady = mSystemReady;
4329 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004330 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4331 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004332 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004333 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004334 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004335 }
4336
4337 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4338 if (VDBG) log("Got NetworkAgent Messenger");
4339 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004340 synchronized (mNetworkForNetId) {
4341 mNetworkForNetId.put(na.network.netId, na);
4342 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004343 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4344 NetworkInfo networkInfo = na.networkInfo;
4345 na.networkInfo = null;
4346 updateNetworkInfo(na, networkInfo);
4347 }
4348
4349 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4350 LinkProperties newLp = networkAgent.linkProperties;
4351 int netId = networkAgent.network.netId;
4352
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004353 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4354 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004355 if (networkAgent.clatd != null) {
4356 networkAgent.clatd.fixupLinkProperties(oldLp);
4357 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004358
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004359 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004360 updateMtu(newLp, oldLp);
4361 // TODO - figure out what to do for clat
4362// for (LinkProperties lp : newLp.getStackedLinks()) {
4363// updateMtu(lp, null);
4364// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004365 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004366
Erik Kline94887872016-04-05 13:30:49 +09004367 updateRoutes(newLp, oldLp, netId);
4368 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004369
Hugo Benichib577d652017-06-27 15:13:20 +09004370 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004371 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004372 if (isDefaultNetwork(networkAgent)) {
4373 handleApplyDefaultProxy(newLp.getHttpProxy());
4374 } else {
4375 updateProxy(newLp, oldLp, networkAgent);
4376 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004377 // TODO - move this check to cover the whole function
4378 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004379 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004380 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4381 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004382
4383 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004384 }
4385
Joel Scherpelz668370b2017-06-08 15:35:21 +09004386 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004387 // Marks are only available on WiFi interaces. Checking for
4388 // marks on unsupported interfaces is harmless.
4389 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4390 return;
4391 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004392
Joel Scherpelz668370b2017-06-08 15:35:21 +09004393 int mark = mContext.getResources().getInteger(
4394 com.android.internal.R.integer.config_networkWakeupPacketMark);
4395 int mask = mContext.getResources().getInteger(
4396 com.android.internal.R.integer.config_networkWakeupPacketMask);
4397
4398 // Mask/mark of zero will not detect anything interesting.
4399 // Don't install rules unless both values are nonzero.
4400 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004401 return;
4402 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004403
4404 final String prefix = "iface:" + iface;
4405 try {
4406 if (add) {
4407 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4408 } else {
4409 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4410 }
4411 } catch (Exception e) {
4412 loge("Exception modifying wakeup packet monitoring: " + e);
4413 }
4414
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004415 }
4416
4417 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4418 NetworkCapabilities caps) {
Paul Jensen992f2522014-04-28 10:33:11 -04004419 CompareResult<String> interfaceDiff = new CompareResult<String>();
4420 if (oldLp != null) {
4421 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4422 } else if (newLp != null) {
4423 interfaceDiff.added = newLp.getAllInterfaceNames();
4424 }
4425 for (String iface : interfaceDiff.added) {
4426 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004427 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004428 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004429 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004430 } catch (Exception e) {
4431 loge("Exception adding interface: " + e);
4432 }
4433 }
4434 for (String iface : interfaceDiff.removed) {
4435 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004436 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004437 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004438 mNetd.removeInterfaceFromNetwork(iface, netId);
4439 } catch (Exception e) {
4440 loge("Exception removing interface: " + e);
4441 }
4442 }
4443 }
4444
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004445 /**
4446 * Have netd update routes from oldLp to newLp.
4447 * @return true if routes changed between oldLp and newLp
4448 */
4449 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004450 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4451 if (oldLp != null) {
4452 routeDiff = oldLp.compareAllRoutes(newLp);
4453 } else if (newLp != null) {
4454 routeDiff.added = newLp.getAllRoutes();
4455 }
4456
4457 // add routes before removing old in case it helps with continuous connectivity
4458
4459 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4460 for (RouteInfo route : routeDiff.added) {
4461 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004462 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004463 try {
4464 mNetd.addRoute(netId, route);
4465 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004466 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4467 loge("Exception in addRoute for non-gateway: " + e);
4468 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004469 }
4470 }
4471 for (RouteInfo route : routeDiff.added) {
4472 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004473 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004474 try {
4475 mNetd.addRoute(netId, route);
4476 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004477 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4478 loge("Exception in addRoute for gateway: " + e);
4479 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004480 }
4481 }
4482
4483 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004484 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004485 try {
4486 mNetd.removeRoute(netId, route);
4487 } catch (Exception e) {
4488 loge("Exception in removeRoute: " + e);
4489 }
4490 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004491 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 }
Erik Kline41368502015-06-17 13:19:54 +09004493
Erik Kline94887872016-04-05 13:30:49 +09004494 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4495 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4496 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004497 }
Erik Kline94887872016-04-05 13:30:49 +09004498
4499 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004500 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004501 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004502 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004503 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4504 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004505 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004506 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004507 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4508 if (defaultNai != null && defaultNai.network.netId == netId) {
4509 setDefaultDnsSystemProperties(dnses);
4510 }
Erik Kline94887872016-04-05 13:30:49 +09004511 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004512 }
4513
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004514 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4515 int last = 0;
4516 for (InetAddress dns : dnses) {
4517 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004518 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004519 }
4520 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004521 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004522 }
4523 mNumDnsEntries = last;
4524 }
4525
Erik Kline4edba012017-04-07 15:29:29 +09004526 private void setNetDnsProperty(int which, String value) {
4527 final String key = "net.dns" + which;
4528 // Log and forget errors setting unsupported properties.
4529 try {
4530 mSystemProperties.set(key, value);
4531 } catch (Exception e) {
4532 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4533 }
4534 }
4535
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004536 private String getNetworkPermission(NetworkCapabilities nc) {
4537 // TODO: make these permission strings AIDL constants instead.
4538 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4539 return NetworkManagementService.PERMISSION_SYSTEM;
4540 }
4541 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4542 return NetworkManagementService.PERMISSION_NETWORK;
4543 }
4544 return null;
4545 }
4546
Paul Jensen3d194ea2015-06-16 14:27:36 -04004547 /**
4548 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4549 * augmented with any stateful capabilities implied from {@code networkAgent}
4550 * (e.g., validated status and captive portal status).
4551 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004552 * @param oldScore score of the network before any of the changes that prompted us
4553 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004554 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004555 * @param networkCapabilities the new network capabilities.
4556 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004557 private void updateCapabilities(
4558 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004559 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Hugo Benichia60c6ea2017-08-18 14:41:22 +09004560 if (nai.everConnected && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
4561 networkCapabilities)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004562 // TODO: consider not complaining when a network agent degrade its capabilities if this
4563 // does not cause any request (that is not a listen) currently matching that agent to
4564 // stop being matched by the updated agent.
Hugo Benichieae7a222017-07-25 11:40:56 +09004565 String diff = nai.networkCapabilities.describeImmutableDifferences(networkCapabilities);
4566 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004567 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004568 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004569 }
4570
Paul Jensen3d194ea2015-06-16 14:27:36 -04004571 // Don't modify caller's NetworkCapabilities.
4572 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004573 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004574 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4575 } else {
4576 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4577 }
Paul Jensene0988542015-06-25 15:30:08 -04004578 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004579 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4580 } else {
4581 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4582 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004583 if (nai.isBackgroundNetwork()) {
4584 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4585 } else {
4586 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4587 }
4588
4589 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4590
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004591 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4592 final String newPermission = getNetworkPermission(networkCapabilities);
4593 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004594 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004595 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004596 } catch (RemoteException e) {
4597 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004598 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004599 }
4600
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004601 final NetworkCapabilities prevNc = nai.networkCapabilities;
4602 synchronized (nai) {
4603 nai.networkCapabilities = networkCapabilities;
4604 }
4605 if (nai.getCurrentScore() == oldScore &&
4606 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4607 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4608 // the change we're processing can't affect any requests, it can only affect the listens
4609 // on this network. We might have been called by rematchNetworkAndRequests when a
4610 // network changed foreground state.
4611 processListenRequests(nai, true);
4612 } else {
4613 // If the requestable capabilities have changed or the score changed, we can't have been
4614 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004615 rematchAllNetworksAndRequests(nai, oldScore);
4616 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004617 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004618 }
4619
Hugo Benichief502882017-09-01 01:23:32 +00004620 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4621 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4622 // Ignore updates for disconnected networks
4623 return;
4624 }
4625
4626 if (VDBG) {
4627 log("Update of LinkProperties for " + nai.name() +
4628 "; created=" + nai.created +
4629 "; everConnected=" + nai.everConnected);
4630 }
4631 LinkProperties oldLp = nai.linkProperties;
4632 synchronized (nai) {
4633 nai.linkProperties = newLp;
4634 }
Rubin Xu1bb5c082017-09-05 18:40:49 +01004635 // msg.obj is already a defensive copy.
4636 nai.linkProperties.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004637 if (nai.everConnected) {
4638 updateLinkProperties(nai, oldLp);
4639 }
4640 }
4641
Paul Jensenc8b9a742014-09-30 15:37:41 -04004642 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004643 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4644 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004645 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004646 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004647 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4648 }
4649 }
4650
Robert Greenwalt7b816022014-04-18 15:25:25 -07004651 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4652 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004653 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004654 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4655 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004656 }
4657 }
4658
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004659 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4660 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004661 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004662 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004663 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4664 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004665 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004666 sendIntent(nri.mPendingIntent, intent);
4667 }
4668 // else not handled
4669 }
4670
4671 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4672 mPendingIntentWakeLock.acquire();
4673 try {
4674 if (DBG) log("Sending " + pendingIntent);
4675 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4676 } catch (PendingIntent.CanceledException e) {
4677 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4678 mPendingIntentWakeLock.release();
4679 releasePendingNetworkRequest(pendingIntent);
4680 }
4681 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4682 }
4683
4684 @Override
4685 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4686 String resultData, Bundle resultExtras) {
4687 if (DBG) log("Finished sending " + pendingIntent);
4688 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004689 // Release with a delay so the receiving client has an opportunity to put in its
4690 // own request.
4691 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004692 }
4693
Hugo Benichidba33db2017-03-23 22:40:44 +09004694 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004695 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004696 if (nri.messenger == null) {
4697 return; // Default request has no msgr
4698 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004699 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004700 // TODO: check if defensive copies of data is needed.
4701 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004702 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004703 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4704 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004705 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004706 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004707 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004708 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004709 break;
4710 }
4711 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004712 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004713 break;
4714 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004715 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004716 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004717 break;
4718 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004719 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004720 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004721 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004722 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004723 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004724 String notification = ConnectivityManager.getCallbackName(notificationType);
4725 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004726 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004727 nri.messenger.send(msg);
4728 } catch (RemoteException e) {
4729 // may occur naturally in the race of binder death.
4730 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4731 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004732 }
4733
Hugo Benichidba33db2017-03-23 22:40:44 +09004734 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4735 bundle.putParcelable(t.getClass().getSimpleName(), t);
4736 }
4737
Paul Jensenc8b9a742014-09-30 15:37:41 -04004738 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004739 if (nai.numRequestNetworkRequests() != 0) {
4740 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4741 NetworkRequest nr = nai.requestAt(i);
4742 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004743 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004744 loge("Dead network still had at least " + nr);
4745 break;
4746 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004747 }
4748 nai.asyncChannel.disconnect();
4749 }
4750
Robert Greenwalt7b816022014-04-18 15:25:25 -07004751 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4752 if (oldNetwork == null) {
4753 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4754 return;
4755 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004756 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004757
4758 // If we get here it means that the last linger timeout for this network expired. So there
4759 // must be no other active linger timers, and we must stop lingering.
4760 oldNetwork.clearLingerState();
4761
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004762 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004763 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004764 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004765 } else {
4766 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004767 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4768 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004769 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004770 }
4771
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004772 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004773 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004774 setupDataActivityTracking(newNetwork);
4775 try {
4776 mNetd.setDefaultNetId(newNetwork.network.netId);
4777 } catch (Exception e) {
4778 loge("Exception setting default network :" + e);
4779 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004780 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004781 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004782 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004783 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004784 }
4785
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004786 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004787 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4788 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4789 NetworkRequest nr = nri.request;
4790 if (!nr.isListen()) continue;
4791 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4792 nai.removeRequest(nri.request.requestId);
4793 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4794 }
4795 }
4796
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004797 if (capabilitiesChanged) {
4798 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4799 }
4800
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004801 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4802 NetworkRequest nr = nri.request;
4803 if (!nr.isListen()) continue;
4804 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4805 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004806 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004807 }
4808 }
4809 }
4810
Paul Jensen2161a8e2014-09-11 11:00:39 -04004811 // Handles a network appearing or improving its score.
4812 //
4813 // - Evaluates all current NetworkRequests that can be
4814 // satisfied by newNetwork, and reassigns to newNetwork
4815 // any such requests for which newNetwork is the best.
4816 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004817 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004818 // needed. A network is needed if it is the best network for
4819 // one or more NetworkRequests, or if it is a VPN.
4820 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004821 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004822 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004823 //
4824 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4825 // networks that have no chance (i.e. even if validated)
4826 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004827 //
4828 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4829 // it does not remove NetworkRequests that other Networks could better satisfy.
4830 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4831 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4832 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004833 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004834 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004835 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4836 // performed to tear down unvalidated networks that have no chance (i.e. even if
4837 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004838 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004839 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004840 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004841 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004842 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004843 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004844
4845 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4846 final int score = newNetwork.getCurrentScore();
4847
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004848 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004849
Paul Jensen2161a8e2014-09-11 11:00:39 -04004850 // Find and migrate to this Network any NetworkRequests for
4851 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004852 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004853 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004854 NetworkCapabilities nc = newNetwork.networkCapabilities;
4855 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004856 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004857 // Process requests in the first pass and listens in the second pass. This allows us to
4858 // change a network's capabilities depending on which requests it has. This is only
4859 // correct if the change in capabilities doesn't affect whether the network satisfies
4860 // requests or not, and doesn't affect the network's score.
4861 if (nri.request.isListen()) continue;
4862
Paul Jensencf4c2c62015-07-01 14:16:32 -04004863 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4864 final boolean satisfies = newNetwork.satisfies(nri.request);
4865 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004866 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004867 log("Network " + newNetwork.name() + " was already satisfying" +
4868 " request " + nri.request.requestId + ". No change.");
4869 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004870 keep = true;
4871 continue;
4872 }
4873
4874 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004875 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004876 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004877 // next check if it's better than any current network we're using for
4878 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004879 if (VDBG) {
4880 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004881 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004882 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004883 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004884 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004885 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004886 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004887 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004888 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004889 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004890 affectedNetworks.add(currentNetwork);
4891 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004892 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004893 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004894 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004895 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004896 if (!newNetwork.addRequest(nri.request)) {
4897 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4898 }
4899 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004900 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004901 // Tell NetworkFactories about the new score, so they can stop
4902 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004903 // TODO - this could get expensive if we have alot of requests for this
4904 // network. Think about if there is a way to reduce this. Push
4905 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004906 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004907 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004908 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004909 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004910 if (currentNetwork != null) {
4911 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4912 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004913 }
4914 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004915 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004916 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4917 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004918 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004919 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4920 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4921 // This means this code doesn't have to handle the case where "currentNetwork" no
4922 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4923 if (DBG) {
4924 log("Network " + newNetwork.name() + " stopped satisfying" +
4925 " request " + nri.request.requestId);
4926 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004927 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004928 if (currentNetwork == newNetwork) {
4929 mNetworkForRequestId.remove(nri.request.requestId);
4930 sendUpdatedScoreToFactories(nri.request, 0);
4931 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004932 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4933 newNetwork.name() +
4934 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004935 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004936 // TODO: Technically, sending CALLBACK_LOST here is
4937 // incorrect if there is a replacement network currently
4938 // connected that can satisfy nri, which is a request
4939 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004940 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4941 // so this code is only incorrect for a network that loses
4942 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004943 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004944 }
4945 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004946 if (isNewDefault) {
4947 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004948 makeDefault(newNetwork);
4949 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4950 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004951 // Have a new default network, release the transition wakelock in
4952 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004953 }
4954
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004955 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4956 Slog.wtf(TAG, String.format(
4957 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07004958 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004959 }
4960 if (newNetwork.getCurrentScore() != score) {
4961 Slog.wtf(TAG, String.format(
4962 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08004963 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004964 }
4965
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004966 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004967 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4968 // If the network went from background to foreground or vice versa, we need to update
4969 // its foreground state. It is safe to do this after rematching the requests because
4970 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4971 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004972 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004973 } else {
4974 processListenRequests(newNetwork, false);
4975 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004976
Paul Jensencf4c2c62015-07-01 14:16:32 -04004977 // do this after the default net is switched, but
4978 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09004979 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004980
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004981 // Linger any networks that are no longer needed. This should be done after sending the
4982 // available callback for newNetwork.
4983 for (NetworkAgentInfo nai : affectedNetworks) {
4984 updateLingerState(nai, now);
4985 }
4986 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4987 // does not need to be done in any particular order.
4988 updateLingerState(newNetwork, now);
4989
Paul Jensencf4c2c62015-07-01 14:16:32 -04004990 if (isNewDefault) {
4991 // Maintain the illusion: since the legacy API only
4992 // understands one network at a time, we must pretend
4993 // that the current default network disconnected before
4994 // the new one connected.
4995 if (oldDefaultNetwork != null) {
4996 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4997 oldDefaultNetwork, true);
4998 }
4999 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5000 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5001 notifyLockdownVpn(newNetwork);
5002 }
5003
Robert Greenwalt7b816022014-04-18 15:25:25 -07005004 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005005 // Notify battery stats service about this network, both the normal
5006 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005007 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005008 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005009 final IBatteryStats bs = BatteryStatsService.getService();
5010 final int type = newNetwork.networkInfo.getType();
5011
5012 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5013 bs.noteNetworkInterfaceType(baseIface, type);
5014 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5015 final String stackedIface = stacked.getInterfaceName();
5016 bs.noteNetworkInterfaceType(stackedIface, type);
5017 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5018 }
5019 } catch (RemoteException ignored) {
5020 }
5021
Robert Greenwalt152ed372014-12-17 17:19:53 -08005022 // This has to happen after the notifyNetworkCallbacks as that tickles each
5023 // ConnectivityManager instance so that legacy requests correctly bind dns
5024 // requests to this network. The legacy users are listening for this bcast
5025 // and will generally do a dns request so they can ensureRouteToHost and if
5026 // they do that before the callbacks happen they'll use the default network.
5027 //
5028 // TODO: Is there still a race here? We send the broadcast
5029 // after sending the callback, but if the app can receive the
5030 // broadcast before the callback, it might still break.
5031 //
5032 // This *does* introduce a race where if the user uses the new api
5033 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5034 // they may get old info. Reverse this after the old startUsing api is removed.
5035 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005036 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5037 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005038 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005039 // legacy type tracker filters out repeat adds
5040 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5041 }
5042 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005043
5044 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5045 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5046 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5047 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5048 if (newNetwork.isVPN()) {
5049 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5050 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005051 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005052 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5053 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005054 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005055 if (nai.getLingerExpiry() > 0) {
5056 // This network has active linger timers and no requests, but is not
5057 // lingering. Linger it.
5058 //
5059 // One way (the only way?) this can happen if this network is unvalidated
5060 // and became unneeded due to another network improving its score to the
5061 // point where this network will no longer be able to satisfy any requests
5062 // even if it validates.
5063 updateLingerState(nai, now);
5064 } else {
5065 if (DBG) log("Reaping " + nai.name());
5066 teardownUnneededNetwork(nai);
5067 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005068 }
5069 }
5070 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005071 }
5072
Paul Jensen1c7ba022015-06-16 14:27:36 -04005073 /**
5074 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5075 * being disconnected.
5076 * @param changed If only one Network's score or capabilities have been modified since the last
5077 * time this function was called, pass this Network in this argument, otherwise pass
5078 * null.
5079 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5080 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5081 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5082 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5083 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005084 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005085 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005086 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5087 // to avoid the slowness. It is not simply enough to process just "changed", for
5088 // example in the case where "changed"'s score decreases and another network should begin
5089 // satifying a NetworkRequest that "changed" currently satisfies.
5090
5091 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5092 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5093 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005094 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005095 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005096 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005097 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005098 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5099 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5100 // Rematch higher scoring networks first to prevent requests first matching a lower
5101 // scoring network and then a higher scoring network, which could produce multiple
5102 // callbacks and inadvertently unlinger networks.
5103 Arrays.sort(nais);
5104 for (NetworkAgentInfo nai : nais) {
5105 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005106 // Only reap the last time through the loop. Reaping before all rematching
5107 // is complete could incorrectly teardown a network that hasn't yet been
5108 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005109 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005110 : ReapUnvalidatedNetworks.REAP,
5111 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005112 }
5113 }
5114 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005116 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005117 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005118 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005119 // For now only update icons for default connection.
5120 // TODO: Update WiFi and cellular icons separately. b/17237507
5121 if (!isDefaultNetwork(nai)) return;
5122
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005123 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005124 // Don't repeat publish.
5125 if (newInetCondition == mDefaultInetConditionPublished) return;
5126
5127 mDefaultInetConditionPublished = newInetCondition;
5128 sendInetConditionBroadcast(nai.networkInfo);
5129 }
5130
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005131 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5132 if (mLockdownTracker != null) {
5133 if (nai != null && nai.isVPN()) {
5134 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5135 } else {
5136 mLockdownTracker.onNetworkInfoChanged();
5137 }
5138 }
5139 }
5140
Robert Greenwalt7b816022014-04-18 15:25:25 -07005141 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005142 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005143 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005144 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005145 synchronized (networkAgent) {
5146 oldInfo = networkAgent.networkInfo;
5147 networkAgent.networkInfo = newInfo;
5148 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005149 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005150
5151 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005152 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5153 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5154 notifyIfacesChangedForNetworkStats();
5155 } else if (VDBG) log("ignoring duplicate network state non-change");
5156 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005157 return;
5158 }
5159 if (DBG) {
5160 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5161 (oldInfo == null ? "null" : oldInfo.getState()) +
5162 " to " + state);
5163 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005164
Robin Lee585e2482016-05-01 23:00:00 +01005165 if (!networkAgent.created
5166 && (state == NetworkInfo.State.CONNECTED
5167 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005168
5169 // A network that has just connected has zero requests and is thus a foreground network.
5170 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5171
Robert Greenwalt7b816022014-04-18 15:25:25 -07005172 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005173 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005174 if (networkAgent.isVPN()) {
5175 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005176 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5177 (networkAgent.networkMisc == null ||
5178 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005179 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005180 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005181 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005182 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005183 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005184 loge("Error creating network " + networkAgent.network.netId + ": "
5185 + e.getMessage());
5186 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005187 }
Paul Jenseneec75412014-08-04 12:21:19 -04005188 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005189 }
5190
5191 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5192 networkAgent.everConnected = true;
5193
Robert Greenwalt7b816022014-04-18 15:25:25 -07005194 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005195 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005196
Paul Jensenca8f16a2014-05-09 12:47:55 -04005197 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005198 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005199
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005200 if (networkAgent.isVPN()) {
5201 // Temporarily disable the default proxy (not global).
5202 synchronized (mProxyLock) {
5203 if (!mDefaultProxyDisabled) {
5204 mDefaultProxyDisabled = true;
5205 if (mGlobalProxy == null && mDefaultProxy != null) {
5206 sendProxyBroadcast(null);
5207 }
5208 }
5209 }
5210 // TODO: support proxy per network.
5211 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005212
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005213 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5214 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5215 // capabilities, so it only needs to be done once on initial connect, not every time the
5216 // network's capabilities change. Note that we do this before rematching the network,
5217 // so we could decide to tear it down immediately afterwards. That's fine though - on
5218 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5219 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005220 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005221
Paul Jensen2161a8e2014-09-11 11:00:39 -04005222 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005223 final long now = SystemClock.elapsedRealtime();
5224 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005225
5226 // This has to happen after matching the requests, because callbacks are just requests.
5227 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005228 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005229 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005230 if (networkAgent.isVPN()) {
5231 synchronized (mProxyLock) {
5232 if (mDefaultProxyDisabled) {
5233 mDefaultProxyDisabled = false;
5234 if (mGlobalProxy == null && mDefaultProxy != null) {
5235 sendProxyBroadcast(mDefaultProxy);
5236 }
5237 }
5238 }
5239 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005240 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5241 state == NetworkInfo.State.SUSPENDED) {
5242 // going into or coming out of SUSPEND: rescore and notify
5243 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005244 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005245 }
5246 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5247 ConnectivityManager.CALLBACK_SUSPENDED :
5248 ConnectivityManager.CALLBACK_RESUMED));
5249 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005250 }
5251 }
5252
Robert Greenwaltac96c522014-06-03 16:43:57 -07005253 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005254 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005255 if (score < 0) {
5256 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5257 "). Bumping score to min of 0");
5258 score = 0;
5259 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005260
Paul Jensen2161a8e2014-09-11 11:00:39 -04005261 final int oldScore = nai.getCurrentScore();
5262 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005263
Paul Jensen85cf78e2015-06-25 13:25:07 -04005264 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005265
Paul Jensenc8b9a742014-09-30 15:37:41 -04005266 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005267 }
5268
Erik Klinec75d4fa2017-02-15 19:59:17 +09005269 // Notify only this one new request of the current state. Transfer all the
5270 // current state by calling NetworkCapabilities and LinkProperties callbacks
5271 // so that callers can be guaranteed to have as close to atomicity in state
5272 // transfer as can be supported by this current API.
5273 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005274 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005275 if (nri.mPendingIntent != null) {
5276 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5277 // Attempt no subsequent state pushes where intents are involved.
5278 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005279 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005280
5281 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5282 // Whether a network is currently suspended is also an important
5283 // element of state to be transferred (it would not otherwise be
5284 // delivered by any currently available mechanism).
5285 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5286 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5287 }
5288 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5289 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005290 }
5291
Robert Greenwalt8d482522015-06-24 13:23:42 -07005292 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005293 // The NetworkInfo we actually send out has no bearing on the real
5294 // state of affairs. For example, if the default connection is mobile,
5295 // and a request for HIPRI has just gone away, we need to pretend that
5296 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5297 // the state to DISCONNECTED, even though the network is of type MOBILE
5298 // and is still connected.
5299 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5300 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005301 if (state != DetailedState.DISCONNECTED) {
5302 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005303 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005304 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005305 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005306 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5307 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5308 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5309 if (info.isFailover()) {
5310 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5311 nai.networkInfo.setFailover(false);
5312 }
5313 if (info.getReason() != null) {
5314 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5315 }
5316 if (info.getExtraInfo() != null) {
5317 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5318 }
5319 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005320 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005321 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005322 if (newDefaultAgent != null) {
5323 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5324 newDefaultAgent.networkInfo);
5325 } else {
5326 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5327 }
5328 }
5329 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5330 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005331 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005332 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005333 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005334 }
5335 }
5336 }
5337
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005338 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005339 if (VDBG) {
5340 String notification = ConnectivityManager.getCallbackName(notifyType);
5341 log("notifyType " + notification + " for " + networkAgent.name());
5342 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005343 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5344 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005345 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5346 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005347 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5348 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005349 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005350 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005351 } else {
5352 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5353 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005354 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005355 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005356
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005357 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5358 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5359 }
5360
Jeff Sharkey69736342014-12-08 14:50:12 -08005361 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005362 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5363 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005364 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005365 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005366 try {
5367 mStatsService.forceUpdateIfaces();
5368 } catch (Exception ignored) {
5369 }
5370 }
5371
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005372 @Override
5373 public boolean addVpnAddress(String address, int prefixLength) {
5374 throwIfLockdownEnabled();
5375 int user = UserHandle.getUserId(Binder.getCallingUid());
5376 synchronized (mVpns) {
5377 return mVpns.get(user).addAddress(address, prefixLength);
5378 }
5379 }
5380
5381 @Override
5382 public boolean removeVpnAddress(String address, int prefixLength) {
5383 throwIfLockdownEnabled();
5384 int user = UserHandle.getUserId(Binder.getCallingUid());
5385 synchronized (mVpns) {
5386 return mVpns.get(user).removeAddress(address, prefixLength);
5387 }
5388 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005389
5390 @Override
5391 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5392 throwIfLockdownEnabled();
5393 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005394 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005395 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005396 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005397 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005398 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005399 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005400 }
5401 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005402 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005403
5404 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005405 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005406 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005407 }
5408
5409 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005410 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5411 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5412 enforceKeepalivePermission();
5413 mKeepaliveTracker.startNattKeepalive(
5414 getNetworkAgentInfoForNetwork(network),
5415 intervalSeconds, messenger, binder,
5416 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5417 }
5418
5419 @Override
5420 public void stopKeepalive(Network network, int slot) {
5421 mHandler.sendMessage(mHandler.obtainMessage(
5422 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5423 }
5424
5425 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005426 public void factoryReset() {
5427 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005428
5429 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5430 return;
5431 }
5432
Robin Lee3b3dd942015-05-12 18:14:58 +01005433 final int userId = UserHandle.getCallingUserId();
5434
Stuart Scottf1fb3972015-04-02 18:00:02 -07005435 // Turn airplane mode off
5436 setAirplaneMode(false);
5437
Stuart Scotte3e314d2015-04-20 14:07:45 -07005438 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5439 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005440 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005441 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005442 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005443 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005444 }
5445
Stuart Scotte3e314d2015-04-20 14:07:45 -07005446 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005447 // Remove always-on package
5448 synchronized (mVpns) {
5449 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5450 if (alwaysOnPackage != null) {
5451 setAlwaysOnVpnPackage(userId, null, false);
5452 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5453 }
5454 }
5455
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005456 // Turn Always-on VPN off
5457 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5458 final long ident = Binder.clearCallingIdentity();
5459 try {
5460 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5461 mLockdownEnabled = false;
5462 setLockdownTracker(null);
5463 } finally {
5464 Binder.restoreCallingIdentity(ident);
5465 }
5466 }
5467
Stuart Scotte3e314d2015-04-20 14:07:45 -07005468 // Turn VPN off
5469 VpnConfig vpnConfig = getVpnConfig(userId);
5470 if (vpnConfig != null) {
5471 if (vpnConfig.legacy) {
5472 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5473 } else {
5474 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5475 // in the future without user intervention.
5476 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005477
Victor Changb04a5ea2016-05-30 20:36:30 +01005478 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005479 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005480 }
5481 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005482
5483 Settings.Global.putString(mContext.getContentResolver(),
5484 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005485 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005486
5487 @VisibleForTesting
5488 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5489 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5490 return new NetworkMonitor(context, handler, nai, defaultRequest);
5491 }
Erik Kline48f12f22016-04-14 17:30:59 +09005492
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005493 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005494 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5495 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005496 }
5497
5498 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005499 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5500 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5501 }
5502
Hugo Benichicfddd682016-05-31 16:28:06 +09005503 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005504 int newNetid = NETID_UNSET;
5505 int prevNetid = NETID_UNSET;
5506 int[] transports = new int[0];
5507 boolean hadIPv4 = false;
5508 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005509
Hugo Benichi5f16f762016-04-20 12:09:33 +09005510 if (newNai != null) {
5511 newNetid = newNai.network.netId;
5512 transports = newNai.networkCapabilities.getTransportTypes();
5513 }
5514 if (prevNai != null) {
5515 prevNetid = prevNai.network.netId;
5516 final LinkProperties lp = prevNai.linkProperties;
5517 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5518 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5519 }
5520
Hugo Benichicfddd682016-05-31 16:28:06 +09005521 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5522 }
5523
5524 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5525 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005526 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005527
5528 private static boolean toBool(int encodedBoolean) {
5529 return encodedBoolean != 0; // Only 0 means false.
5530 }
5531
5532 private static int encodeBool(boolean b) {
5533 return b ? 1 : 0;
5534 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005535}