blob: 8200289a76b21642cbf6298a476dd33585db231a [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;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070055import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070056import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070057import android.net.NetworkCapabilities;
Etan Cohena7434272017-04-03 12:17:51 -070058import android.net.MatchAllNetworkSpecifier;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070062import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070063import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkRequest;
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;
Erik Kline47222fc2017-04-30 19:36:15 +0900142import com.android.server.connectivity.tethering.TetheringDependencies;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700143import com.android.server.connectivity.Vpn;
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
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001039 * on {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001040 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001041 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001042 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1043
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001044 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001045 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001046 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001047 if (mLockdownTracker != null) {
1048 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001049 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001050 }
1051
1052 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 * Return NetworkInfo for the active (i.e., connected) network interface.
1054 * It is assumed that at most one network is active at a time. If more
1055 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001056 * @return the info for the active network, or {@code null} if none is
1057 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001058 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001059 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001061 enforceAccessPermission();
1062 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001063 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001064 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001065 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1066 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001067 }
1068
Paul Jensen31a94f42015-02-13 14:18:39 -05001069 @Override
1070 public Network getActiveNetwork() {
1071 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001072 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001073 }
1074
1075 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001076 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001077 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001078 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001079 }
1080
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001081 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001082 final int user = UserHandle.getUserId(uid);
1083 int vpnNetId = NETID_UNSET;
1084 synchronized (mVpns) {
1085 final Vpn vpn = mVpns.get(user);
1086 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1087 }
1088 NetworkAgentInfo nai;
1089 if (vpnNetId != NETID_UNSET) {
1090 synchronized (mNetworkForNetId) {
1091 nai = mNetworkForNetId.get(vpnNetId);
1092 }
1093 if (nai != null) return nai.network;
1094 }
1095 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001096 if (nai != null
1097 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1098 nai = null;
1099 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001100 return nai != null ? nai.network : null;
1101 }
1102
Lorenzo Colitti18660282016-07-04 12:55:44 +09001103 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001104 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1105 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001106 final int uid = Binder.getCallingUid();
1107 NetworkState state = getUnfilteredActiveNetworkState(uid);
1108 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001109 }
1110
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001112 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001113 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001114 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001115 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001116 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001117 }
1118
1119 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001120 public NetworkInfo getNetworkInfo(int networkType) {
1121 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001122 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001123 if (getVpnUnderlyingNetworks(uid) != null) {
1124 // A VPN is active, so we may need to return one of its underlying networks. This
1125 // information is not available in LegacyTypeTracker, so we have to get it from
1126 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001127 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001128 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001129 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001130 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001131 }
1132 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001133 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001134 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 }
1136
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001137 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001138 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001139 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001140 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001141 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001142 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001143 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001144 return state.networkInfo;
1145 } else {
1146 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001147 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001148 }
1149
1150 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001151 public NetworkInfo[] getAllNetworkInfo() {
1152 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001153 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001154 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1155 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001156 NetworkInfo info = getNetworkInfo(networkType);
1157 if (info != null) {
1158 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001159 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001160 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001161 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001162 }
1163
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001164 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001165 public Network getNetworkForType(int networkType) {
1166 enforceAccessPermission();
1167 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001168 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1169 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001170 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001171 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001173 }
1174
1175 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001176 public Network[] getAllNetworks() {
1177 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001178 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001179 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001180 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001181 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001182 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001183 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001184 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001185 }
1186
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001187 @Override
1188 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1189 // The basic principle is: if an app's traffic could possibly go over a
1190 // network, without the app doing anything multinetwork-specific,
1191 // (hence, by "default"), then include that network's capabilities in
1192 // the array.
1193 //
1194 // In the normal case, app traffic only goes over the system's default
1195 // network connection, so that's the only network returned.
1196 //
1197 // With a VPN in force, some app traffic may go into the VPN, and thus
1198 // over whatever underlying networks the VPN specifies, while other app
1199 // traffic may go over the system default network (e.g.: a split-tunnel
1200 // VPN, or an app disallowed by the VPN), so the set of networks
1201 // returned includes the VPN's underlying networks and the system
1202 // default.
1203 enforceAccessPermission();
1204
1205 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1206
1207 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001208 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001209 if (nc != null) {
1210 result.put(nai.network, nc);
1211 }
1212
1213 if (!mLockdownEnabled) {
1214 synchronized (mVpns) {
1215 Vpn vpn = mVpns.get(userId);
1216 if (vpn != null) {
1217 Network[] networks = vpn.getUnderlyingNetworks();
1218 if (networks != null) {
1219 for (Network network : networks) {
1220 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001221 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001222 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001223 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001224 }
1225 }
1226 }
1227 }
1228 }
1229 }
1230
1231 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1232 out = result.values().toArray(out);
1233 return out;
1234 }
1235
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001236 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001237 public boolean isNetworkSupported(int networkType) {
1238 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001240 }
1241
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001242 /**
1243 * Return LinkProperties for the active (i.e., connected) default
1244 * network interface. It is assumed that at most one default network
1245 * is active at a time. If more than one is active, it is indeterminate
1246 * which will be returned.
1247 * @return the ip properties for the active network, or {@code null} if
1248 * none is active
1249 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001250 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001251 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 enforceAccessPermission();
1253 final int uid = Binder.getCallingUid();
1254 NetworkState state = getUnfilteredActiveNetworkState(uid);
1255 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001256 }
1257
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001258 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001259 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001260 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001261 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1262 if (nai != null) {
1263 synchronized (nai) {
1264 return new LinkProperties(nai.linkProperties);
1265 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001266 }
1267 return null;
1268 }
1269
Robert Greenwalt12e67352014-05-13 21:41:06 -07001270 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001271 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001272 public LinkProperties getLinkProperties(Network network) {
1273 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001274 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1275 }
1276
1277 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1278 if (nai == null) {
1279 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001280 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001281 synchronized (nai) {
1282 return new LinkProperties(nai.linkProperties);
1283 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001284 }
1285
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001286 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001287 if (nai != null) {
1288 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001289 if (nai.networkCapabilities != null) {
1290 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001291 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001292 }
1293 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001294 return null;
1295 }
1296
1297 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001298 public NetworkCapabilities getNetworkCapabilities(Network network) {
1299 enforceAccessPermission();
1300 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1301 }
1302
1303 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001304 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001305 // Require internal since we're handing out IMSI details
1306 enforceConnectivityInternalPermission();
1307
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001308 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001309 for (Network network : getAllNetworks()) {
1310 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1311 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001312 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001313 }
1314 }
1315 return result.toArray(new NetworkState[result.size()]);
1316 }
1317
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001318 @Override
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001319 @Deprecated
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001320 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001321 Log.w(TAG, "Shame on UID " + Binder.getCallingUid()
1322 + " for calling the hidden API getNetworkQuotaInfo(). Shame!");
1323 return new NetworkQuotaInfo();
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001324 }
1325
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001326 @Override
1327 public boolean isActiveNetworkMetered() {
1328 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001329
Jeff Sharkey43d2a172017-07-12 10:50:42 -06001330 final NetworkCapabilities caps = getNetworkCapabilities(getActiveNetwork());
1331 if (caps != null) {
1332 return !caps.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
1333 } else {
1334 // Always return the most conservative value
1335 return true;
1336 }
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001337 }
1338
Jeff Sharkey216c1812012-08-05 14:29:23 -07001339 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1340 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001341 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001342 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001343 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001344 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001345 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001346
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001347 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 * Ensure that a network route exists to deliver traffic to the specified
1349 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001350 * @param networkType the type of the network over which traffic to the
1351 * specified host is to be routed
1352 * @param hostAddress the IP address of the host to which the route is
1353 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 * @return {@code true} on success, {@code false} on failure
1355 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001356 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001357 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001359 if (mProtectedNetworks.contains(networkType)) {
1360 enforceConnectivityInternalPermission();
1361 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001362
Chad Brubakerc0234532014-02-14 13:24:29 -08001363 InetAddress addr;
1364 try {
1365 addr = InetAddress.getByAddress(hostAddress);
1366 } catch (UnknownHostException e) {
1367 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1368 return false;
1369 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001372 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 return false;
1374 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001375
1376 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1377 if (nai == null) {
1378 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1379 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1380 } else {
1381 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1382 }
1383 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001384 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001385
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001386 DetailedState netState;
1387 synchronized (nai) {
1388 netState = nai.networkInfo.getDetailedState();
1389 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001390
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001391 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001392 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001393 log("requestRouteToHostAddress on down network "
1394 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001395 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001396 }
1397 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001399
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001400 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001401 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001402 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001403 LinkProperties lp;
1404 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001405 synchronized (nai) {
1406 lp = nai.linkProperties;
1407 netId = nai.network.netId;
1408 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001409 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001410 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1411 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001412 } finally {
1413 Binder.restoreCallingIdentity(token);
1414 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001415 }
1416
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001417 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001418 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001419 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001420 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001421 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001422 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001423 if (bestRoute.getGateway().equals(addr)) {
1424 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001425 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001426 } else {
1427 // if we will connect to this through another route, add a direct route
1428 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001429 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001430 }
1431 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001432 if (DBG) log("Adding legacy route " + bestRoute +
1433 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001434 try {
1435 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1436 } catch (Exception e) {
1437 // never crash - catch them all
1438 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001439 return false;
1440 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001441 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
1443
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001444 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001445 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001446 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001447 // TODO: notify UID when it has requested targeted updates
1448 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001449 @Override
1450 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001451 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001452 @Override
1453 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001454 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001455 if (restrictBackground) {
1456 log("onRestrictBackgroundChanged(true): disabling tethering");
1457 mTethering.untetherAll();
1458 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001459 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001460 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001461 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001462 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001463 };
1464
Robin Lee3b3dd942015-05-12 18:14:58 +01001465 /**
1466 * Require that the caller is either in the same user or has appropriate permission to interact
1467 * across users.
1468 *
1469 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1470 */
1471 private void enforceCrossUserPermission(int userId) {
1472 if (userId == UserHandle.getCallingUserId()) {
1473 // Not a cross-user call.
1474 return;
1475 }
1476 mContext.enforceCallingOrSelfPermission(
1477 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1478 "ConnectivityService");
1479 }
1480
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001481 private void enforceInternetPermission() {
1482 mContext.enforceCallingOrSelfPermission(
1483 android.Manifest.permission.INTERNET,
1484 "ConnectivityService");
1485 }
1486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001488 mContext.enforceCallingOrSelfPermission(
1489 android.Manifest.permission.ACCESS_NETWORK_STATE,
1490 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492
1493 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001494 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001497 private void enforceTetherAccessPermission() {
1498 mContext.enforceCallingOrSelfPermission(
1499 android.Manifest.permission.ACCESS_NETWORK_STATE,
1500 "ConnectivityService");
1501 }
1502
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001503 private void enforceConnectivityInternalPermission() {
1504 mContext.enforceCallingOrSelfPermission(
1505 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1506 "ConnectivityService");
1507 }
1508
Hugo Benichi514da602016-07-19 15:59:27 +09001509 private void enforceConnectivityRestrictedNetworksPermission() {
1510 try {
1511 mContext.enforceCallingOrSelfPermission(
1512 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1513 "ConnectivityService");
1514 return;
1515 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1516 enforceConnectivityInternalPermission();
1517 }
1518
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001519 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001520 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001521 }
1522
Lorenzo Colitti18660282016-07-04 12:55:44 +09001523 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001524 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001525 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001526 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001527 }
1528
1529 private void sendInetConditionBroadcast(NetworkInfo info) {
1530 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1531 }
1532
Wink Saville628b0852011-08-04 15:01:58 -07001533 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001534 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001535 info = new NetworkInfo(info);
1536 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001537 }
1538
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001539 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001540 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001541 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 if (info.isFailover()) {
1543 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1544 info.setFailover(false);
1545 }
1546 if (info.getReason() != null) {
1547 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1548 }
1549 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001550 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1551 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001553 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001554 return intent;
1555 }
1556
1557 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1558 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1559 }
1560
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001561 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001562 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1563 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1564 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001565 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001566 final long ident = Binder.clearCallingIdentity();
1567 try {
1568 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1569 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1570 } finally {
1571 Binder.restoreCallingIdentity(ident);
1572 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001573 }
1574
Mike Lockwood0f79b542009-08-14 14:18:49 -04001575 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001576 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001577 if (!mSystemReady) {
1578 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001579 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001580 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001581 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001582 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001583 }
1584
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001585 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001586 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001587 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001588 final NetworkInfo ni = intent.getParcelableExtra(
1589 ConnectivityManager.EXTRA_NETWORK_INFO);
1590 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1591 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1592 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001593 } else {
1594 BroadcastOptions opts = BroadcastOptions.makeBasic();
1595 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1596 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001597 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001598 final IBatteryStats bs = BatteryStatsService.getService();
1599 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001600 bs.noteConnectivityChanged(intent.getIntExtra(
1601 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1602 ni != null ? ni.getState().toString() : "?");
1603 } catch (RemoteException e) {
1604 }
1605 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001606 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001607 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001608 } finally {
1609 Binder.restoreCallingIdentity(ident);
1610 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001611 }
1612 }
1613
1614 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001615 loadGlobalProxy();
1616
Hugo Benichi20035e02017-04-26 14:53:28 +09001617 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001618 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001619 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001620 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001621 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001622 }
1623 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001624 // load the global proxy at startup
1625 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001626
Robin Lee244ce8e2016-01-05 18:03:46 +00001627 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1628 // for user to unlock device too.
1629 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001630
Erik Klineda4bfa82015-04-30 12:58:40 +09001631 // Configure whether mobile data is always on.
1632 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1633
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001634 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001635
1636 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001640 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001641 *
1642 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001643 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001644 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1646 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001647
1648 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001649 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001650
Robert Greenwalt7b816022014-04-18 15:25:25 -07001651 if (networkAgent.networkCapabilities.hasTransport(
1652 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001653 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1654 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001655 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001656 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001657 } else if (networkAgent.networkCapabilities.hasTransport(
1658 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001659 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1660 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001661 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001662 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001663 } else {
1664 // do not track any other networks
1665 timeout = 0;
1666 }
1667
Robert Greenwalt7b816022014-04-18 15:25:25 -07001668 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001669 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001670 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001671 } catch (Exception e) {
1672 // You shall not crash!
1673 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001674 }
1675 }
1676 }
1677
1678 /**
1679 * Remove data activity tracking when network disconnects.
1680 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001681 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1682 final String iface = networkAgent.linkProperties.getInterfaceName();
1683 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001684
Robert Greenwalt7b816022014-04-18 15:25:25 -07001685 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1686 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001687 try {
1688 // the call fails silently if no idletimer setup for this interface
1689 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001690 } catch (Exception e) {
1691 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001692 }
1693 }
1694 }
1695
1696 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001697 * Reads the network specific MTU size from reources.
1698 * and set it on it's iface.
1699 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001700 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1701 final String iface = newLp.getInterfaceName();
1702 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001703 if (oldLp == null && mtu == 0) {
1704 // Silently ignore unset MTU value.
1705 return;
1706 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001707 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1708 if (VDBG) log("identical MTU - not setting");
1709 return;
1710 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001711 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001712 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001713 return;
1714 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001715
w1997615afd812014-08-05 15:18:11 -07001716 // Cannot set MTU without interface name
1717 if (TextUtils.isEmpty(iface)) {
1718 loge("Setting MTU size with null iface.");
1719 return;
1720 }
1721
Robert Greenwalt7b816022014-04-18 15:25:25 -07001722 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001723 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001724 mNetd.setMtu(iface, mtu);
1725 } catch (Exception e) {
1726 Slog.e(TAG, "exception in setMtu()" + e);
1727 }
1728 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001729
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001730 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001731 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1732
1733 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001734 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001735 protected MockableSystemProperties getSystemProperties() {
1736 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001737 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001738
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001739 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1740 if (isDefaultNetwork(nai) == false) {
1741 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001742 }
1743
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001744 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1745 String[] values = null;
1746 if (tcpBufferSizes != null) {
1747 values = tcpBufferSizes.split(",");
1748 }
1749
1750 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001751 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001752 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1753 values = tcpBufferSizes.split(",");
1754 }
1755
1756 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1757
1758 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001759 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001760
1761 final String prefix = "/sys/kernel/ipv4/tcp_";
1762 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1763 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1764 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1765 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1766 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1767 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1768 mCurrentTcpBufferSizes = tcpBufferSizes;
1769 } catch (IOException e) {
1770 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001771 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001772
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001773 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001774 Settings.Global.TCP_DEFAULT_INIT_RWND,
1775 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001776 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1777 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001778 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001779 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001780 }
1781
Mattias Falk8b47b362011-08-23 14:15:13 +02001782 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001783 /*
1784 * Tell the VMs to toss their DNS caches
1785 */
1786 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1787 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001788 /*
1789 * Connectivity events can happen before boot has completed ...
1790 */
1791 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001792 final long ident = Binder.clearCallingIdentity();
1793 try {
1794 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1795 } finally {
1796 Binder.restoreCallingIdentity(ident);
1797 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001798 }
1799
Robert Greenwalt562cc542014-05-15 18:07:26 -07001800 @Override
1801 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001802 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001803 NETWORK_RESTORE_DELAY_PROP_NAME);
1804 if(restoreDefaultNetworkDelayStr != null &&
1805 restoreDefaultNetworkDelayStr.length() != 0) {
1806 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001807 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001808 } catch (NumberFormatException e) {
1809 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001810 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001811 // if the system property isn't set, use the value for the apn type
1812 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1813
1814 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1815 (mNetConfigs[networkType] != null)) {
1816 ret = mNetConfigs[networkType].restoreTime;
1817 }
1818 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001819 }
1820
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001821 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001822 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001823 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001824 }
1825 return false;
1826 }
1827
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001828 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1829 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1830 final long DIAG_TIME_MS = 5000;
1831 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1832 // Start gathering diagnostic information.
1833 netDiags.add(new NetworkDiagnostics(
1834 nai.network,
1835 new LinkProperties(nai.linkProperties), // Must be a copy.
1836 DIAG_TIME_MS));
1837 }
1838
1839 for (NetworkDiagnostics netDiag : netDiags) {
1840 pw.println();
1841 netDiag.waitForMeasurements();
1842 netDiag.dump(pw);
1843 }
1844 }
1845
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001847 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1848 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001849 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001850
Erik Kline7747fd42017-05-12 16:52:48 +09001851 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001852 dumpNetworkDiagnostics(pw);
1853 return;
Erik Klineee363c42017-05-29 09:11:03 +09001854 } else if (argsContain(args, TETHERING_ARG)) {
1855 mTethering.dump(fd, pw, args);
1856 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001857 }
Erik Kline379747a2015-06-05 17:47:34 +09001858
Lorenzo Colittie3805462015-06-03 11:18:24 +09001859 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001860 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001861 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001862 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001863 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001864 pw.println();
1865
Paul Jensen85cf78e2015-06-25 13:25:07 -04001866 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001867 pw.print("Active default network: ");
1868 if (defaultNai == null) {
1869 pw.println("none");
1870 } else {
1871 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001872 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001873 pw.println();
1874
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001875 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001876 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001877 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1878 pw.println(nai.toString());
1879 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001880 pw.println(String.format(
1881 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1882 nai.numForegroundNetworkRequests(),
1883 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1884 nai.numBackgroundNetworkRequests(),
1885 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001886 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001887 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1888 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001889 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001890 pw.decreaseIndent();
1891 pw.println("Lingered:");
1892 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001893 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001894 pw.decreaseIndent();
1895 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001896 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001897 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001898 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001899
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001900 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001901 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001902 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1903 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001904 }
1905 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001906 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001907
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001908 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001909
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001910 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001911 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001912
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001913 pw.println();
1914 mKeepaliveTracker.dump(pw);
1915
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001916 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001917 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001918
Erik Kline7747fd42017-05-12 16:52:48 +09001919 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001920 pw.println();
1921 synchronized (mValidationLogs) {
1922 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001923 for (ValidationLog p : mValidationLogs) {
1924 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001925 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001926 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001927 pw.decreaseIndent();
1928 }
1929 }
Erik Kline7523eb32015-07-09 18:24:03 +09001930
1931 pw.println();
1932 pw.println("mNetworkRequestInfoLogs (most recent first):");
1933 pw.increaseIndent();
1934 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1935 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001936
1937 pw.println();
1938 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1939 pw.increaseIndent();
1940 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1941 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001942
1943 pw.println();
1944 pw.println("NetTransition WakeLock activity (most recent first):");
1945 pw.increaseIndent();
1946 mWakelockLogs.reverseDump(fd, pw, args);
1947 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001948 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001949 }
1950
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001951 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001952 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001953 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001954 if (officialNai != null && officialNai.equals(nai)) return true;
1955 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001956 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001957 " - " + nai);
1958 }
1959 return false;
1960 }
1961
Robert Greenwalt42acef32009-08-12 16:08:25 -07001962 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001963 private class NetworkStateTrackerHandler extends Handler {
1964 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001965 super(looper);
1966 }
1967
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001968 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001969 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001970 default:
1971 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001972 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001973 handleAsyncChannelHalfConnect(msg);
1974 break;
1975 }
1976 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1977 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1978 if (nai != null) nai.asyncChannel.disconnect();
1979 break;
1980 }
1981 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1982 handleAsyncChannelDisconnected(msg);
1983 break;
1984 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001985 }
1986 return true;
1987 }
1988
1989 private void maybeHandleNetworkAgentMessage(Message msg) {
1990 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1991 if (nai == null) {
1992 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001993 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001994 }
1995 return;
1996 }
1997
1998 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001999 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002000 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2001 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002002 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2003 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002004 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002005 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002006 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002007 break;
2008 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002009 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002010 if (VDBG) {
2011 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002012 "; created=" + nai.created +
2013 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002014 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002015 LinkProperties oldLp = nai.linkProperties;
2016 synchronized (nai) {
2017 nai.linkProperties = (LinkProperties)msg.obj;
2018 }
Robin Lee585e2482016-05-01 23:00:00 +01002019 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002020 break;
2021 }
2022 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002023 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002024 updateNetworkInfo(nai, info);
2025 break;
2026 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002027 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002028 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002029 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002030 break;
2031 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002032 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002033 try {
2034 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002035 } catch (Exception e) {
2036 // Never crash!
2037 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002038 }
2039 break;
2040 }
2041 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002042 try {
2043 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002044 } catch (Exception e) {
2045 // Never crash!
2046 loge("Exception in removeVpnUidRanges: " + e);
2047 }
2048 break;
2049 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002050 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002051 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2052 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002053 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002054 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002055 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002056 break;
2057 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002058 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002059 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2060 break;
2061 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002062 }
2063 }
2064
2065 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2066 switch (msg.what) {
2067 default:
2068 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002069 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002070 final NetworkAgentInfo nai;
2071 synchronized (mNetworkForNetId) {
2072 nai = mNetworkForNetId.get(msg.arg2);
2073 }
2074 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002075 final boolean valid =
2076 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002077 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002078 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2079 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002080 if (valid != nai.lastValidated) {
2081 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002082 nai.lastValidated = valid;
2083 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002084 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002085 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2086 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002087 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002088 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002089 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002090 Bundle redirectUrlBundle = new Bundle();
2091 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002092 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002093 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002094 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002095 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002096 if (wasValidated && !nai.lastValidated) {
2097 handleNetworkUnvalidated(nai);
2098 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002099 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002100 break;
2101 }
Paul Jensen869868be2014-05-15 10:33:05 -04002102 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002103 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002104 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002105 final NetworkAgentInfo nai;
2106 synchronized (mNetworkForNetId) {
2107 nai = mNetworkForNetId.get(netId);
2108 }
Calvin Onbe96da12016-10-11 15:10:46 -07002109 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002110 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002111 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002112 nai.lastCaptivePortalDetected = visible;
2113 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002114 if (nai.lastCaptivePortalDetected &&
2115 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2116 if (DBG) log("Avoiding captive portal network: " + nai.name());
2117 nai.asyncChannel.sendMessage(
2118 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2119 teardownUnneededNetwork(nai);
2120 break;
2121 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002122 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002123 }
2124 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002125 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002126 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002127 if (nai == null) {
2128 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2129 break;
2130 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002131 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002132 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002133 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002134 }
Paul Jensen869868be2014-05-15 10:33:05 -04002135 }
Paul Jensen869868be2014-05-15 10:33:05 -04002136 break;
2137 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002138 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002139 return true;
2140 }
2141
Calvin Onbe96da12016-10-11 15:10:46 -07002142 private int getCaptivePortalMode() {
2143 return Settings.Global.getInt(mContext.getContentResolver(),
2144 Settings.Global.CAPTIVE_PORTAL_MODE,
2145 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2146 }
2147
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002148 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2149 switch (msg.what) {
2150 default:
2151 return false;
2152 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2153 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2154 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2155 handleLingerComplete(nai);
2156 }
2157 break;
2158 }
2159 }
2160 return true;
2161 }
2162
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002163 @Override
2164 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002165 if (!maybeHandleAsyncChannelMessage(msg) &&
2166 !maybeHandleNetworkMonitorMessage(msg) &&
2167 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002168 maybeHandleNetworkAgentMessage(msg);
2169 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002170 }
2171 }
2172
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002173 private void updateLingerState(NetworkAgentInfo nai, long now) {
2174 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2175 // 2. If the network was lingering and there are now requests, unlinger it.
2176 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2177 // one lingered request, start lingering.
2178 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002179 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002180 if (DBG) log("Unlingering " + nai.name());
2181 nai.unlinger();
2182 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002183 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002184 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002185 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002186 nai.linger();
2187 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2188 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2189 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002190 }
2191
Robert Greenwalt7b816022014-04-18 15:25:25 -07002192 private void handleAsyncChannelHalfConnect(Message msg) {
2193 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002194 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002195 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2196 if (VDBG) log("NetworkFactory connected");
2197 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002198 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002199 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002200 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002201 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002202 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002203 }
2204 } else {
2205 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002206 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002207 }
2208 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2209 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2210 if (VDBG) log("NetworkAgent connected");
2211 // A network agent has requested a connection. Establish the connection.
2212 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2213 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2214 } else {
2215 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002216 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002217 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002218 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002219 synchronized (mNetworkForNetId) {
2220 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002221 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002222 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002223 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002224 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002225 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002226 }
2227 }
2228 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002229
Robert Greenwalt7b816022014-04-18 15:25:25 -07002230 private void handleAsyncChannelDisconnected(Message msg) {
2231 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2232 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002233 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002234 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002235 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002236 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002237 // TODO - if we move the logic to the network agent (have them disconnect
2238 // because they lost all their requests or because their score isn't good)
2239 // then they would disconnect organically, report their new state and then
2240 // disconnect the channel.
2241 if (nai.networkInfo.isConnected()) {
2242 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2243 null, null);
2244 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002245 final boolean wasDefault = isDefaultNetwork(nai);
2246 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002247 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002248 // Log default network disconnection before required book-keeping.
2249 // Let rematchAllNetworksAndRequests() below record a new default network event
2250 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2251 // whose timestamps tell how long it takes to recover a default network.
2252 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002253 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002254 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002255 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2256 // by other networks that are already connected. Perhaps that can be done by
2257 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2258 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002259 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002260 mKeepaliveTracker.handleStopAllKeepalives(nai,
2261 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002262 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2263 // Disable wakeup packet monitoring for each interface.
2264 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2265 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002266 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002267 mNetworkAgentInfos.remove(msg.replyTo);
2268 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002269 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002270 // Remove the NetworkAgent, but don't mark the netId as
2271 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002272 mNetworkForNetId.remove(nai.network.netId);
2273 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002274 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002275 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2276 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002277 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2278 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2279 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002280 sendUpdatedScoreToFactories(request, 0);
2281 }
2282 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002283 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002284 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002285 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002286 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002287 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002288 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002289 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002290 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002291 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002292 if (nai.created) {
2293 // Tell netd to clean up the configuration for this network
2294 // (routing rules, DNS, etc).
2295 // This may be slow as it requires a lot of netd shelling out to ip and
2296 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2297 // after we've rematched networks with requests which should make a potential
2298 // fallback network the default or requested a new network from the
2299 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2300 // long time.
2301 try {
2302 mNetd.removeNetwork(nai.network.netId);
2303 } catch (Exception e) {
2304 loge("Exception removing network: " + e);
2305 }
2306 }
2307 synchronized (mNetworkForNetId) {
2308 mNetIdInUse.delete(nai.network.netId);
2309 }
2310 } else {
2311 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2312 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002313 }
2314 }
2315
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002316 // If this method proves to be too slow then we can maintain a separate
2317 // pendingIntent => NetworkRequestInfo map.
2318 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2319 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2320 Intent intent = pendingIntent.getIntent();
2321 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2322 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2323 if (existingPendingIntent != null &&
2324 existingPendingIntent.getIntent().filterEquals(intent)) {
2325 return entry.getValue();
2326 }
2327 }
2328 return null;
2329 }
2330
2331 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2332 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2333
2334 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2335 if (existingRequest != null) { // remove the existing request.
2336 if (DBG) log("Replacing " + existingRequest.request + " with "
2337 + nri.request + " because their intents matched.");
2338 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2339 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002340 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002341 }
2342
Erik Klineda4bfa82015-04-30 12:58:40 +09002343 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002344 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002345 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002346 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002347 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002348 if (nri.request.networkCapabilities.hasSignalStrength() &&
2349 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2350 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002351 }
2352 }
2353 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002354 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002355 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002356 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002357 }
2358 }
2359
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002360 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2361 int callingUid) {
2362 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2363 if (nri != null) {
2364 handleReleaseNetworkRequest(nri.request, callingUid);
2365 }
2366 }
2367
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002368 // Determines whether the network is the best (or could become the best, if it validated), for
2369 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2370 // on the value of reason:
2371 //
2372 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2373 // then it should be torn down.
2374 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2375 // then it should be lingered.
2376 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2377 final int numRequests;
2378 switch (reason) {
2379 case TEARDOWN:
2380 numRequests = nai.numRequestNetworkRequests();
2381 break;
2382 case LINGER:
2383 numRequests = nai.numForegroundNetworkRequests();
2384 break;
2385 default:
2386 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2387 return true;
2388 }
2389
2390 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002391 return false;
2392 }
Paul Jensene0988542015-06-25 15:30:08 -04002393 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002394 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2395 // Background requests don't affect lingering.
2396 continue;
2397 }
2398
Paul Jensene0988542015-06-25 15:30:08 -04002399 // If this Network is already the highest scoring Network for a request, or if
2400 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002401 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002402 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002403 // Note that this catches two important cases:
2404 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2405 // is currently satisfying the request. This is desirable when
2406 // cellular ends up validating but WiFi does not.
2407 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002408 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002409 // WiFi ends up validating and out scoring cellular.
2410 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2411 nai.getCurrentScoreAsValidated())) {
2412 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002413 }
2414 }
Paul Jensene0988542015-06-25 15:30:08 -04002415 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002416 }
2417
Erik Klineacdd6392016-07-07 16:50:58 +09002418 private NetworkRequestInfo getNriForAppRequest(
2419 NetworkRequest request, int callingUid, String requestedOperation) {
2420 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2421
Robert Greenwalt9258c642014-03-26 16:47:06 -07002422 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002423 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002424 log(String.format("UID %d attempted to %s for unowned request %s",
2425 callingUid, requestedOperation, nri));
2426 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002427 }
Erik Klineacdd6392016-07-07 16:50:58 +09002428 }
2429
2430 return nri;
2431 }
2432
Erik Kline57faba92015-11-25 12:49:38 +09002433 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002434 if (mNetworkRequests.get(nri.request) == null) {
2435 return;
Erik Kline57faba92015-11-25 12:49:38 +09002436 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002437 if (mNetworkForRequestId.get(nri.request.requestId) != null) {
2438 return;
2439 }
2440 if (VDBG || (DBG && nri.request.isRequest())) {
2441 log("releasing " + nri.request + " (timeout)");
2442 }
2443 handleRemoveNetworkRequest(nri);
2444 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002445 }
2446
Erik Klineacdd6392016-07-07 16:50:58 +09002447 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002448 final NetworkRequestInfo nri =
2449 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2450 if (nri == null) {
2451 return;
Erik Kline57faba92015-11-25 12:49:38 +09002452 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002453 if (VDBG || (DBG && nri.request.isRequest())) {
2454 log("releasing " + nri.request + " (release request)");
2455 }
2456 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002457 }
Erik Klineacdd6392016-07-07 16:50:58 +09002458
Hugo Benichidba33db2017-03-23 22:40:44 +09002459 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002460 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002461 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002462 synchronized (mUidToNetworkRequestCount) {
2463 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2464 if (requests < 1) {
2465 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2466 nri.mUid);
2467 } else if (requests == 1) {
2468 mUidToNetworkRequestCount.removeAt(
2469 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2470 } else {
2471 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2472 }
2473 }
2474 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2475 if (nri.request.isRequest()) {
2476 boolean wasKept = false;
2477 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2478 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002479 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002480 nai.removeRequest(nri.request.requestId);
2481 if (VDBG) {
2482 log(" Removing from current network " + nai.name() +
2483 ", leaving " + nai.numNetworkRequests() + " requests.");
2484 }
2485 // If there are still lingered requests on this network, don't tear it down,
2486 // but resume lingering instead.
2487 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002488 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002489 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2490 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002491 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002492 wasKept = true;
2493 }
2494 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002495 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2496 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002497 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002498 }
Erik Klineacdd6392016-07-07 16:50:58 +09002499 }
2500
2501 // TODO: remove this code once we know that the Slog.wtf is never hit.
2502 //
2503 // Find all networks that are satisfying this request and remove the request
2504 // from their request lists.
2505 // TODO - it's my understanding that for a request there is only a single
2506 // network satisfying it, so this loop is wasteful
2507 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2508 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2509 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2510 otherNai.name() + ", but mNetworkAgentInfos says " +
2511 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002512 }
2513 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002514
Erik Klineacdd6392016-07-07 16:50:58 +09002515 // Maintain the illusion. When this request arrived, we might have pretended
2516 // that a network connected to serve it, even though the network was already
2517 // connected. Now that this request has gone away, we might have to pretend
2518 // that the network disconnected. LegacyTypeTracker will generate that
2519 // phantom disconnect for this type.
2520 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2521 boolean doRemove = true;
2522 if (wasKept) {
2523 // check if any of the remaining requests for this network are for the
2524 // same legacy type - if so, don't remove the nai
2525 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2526 NetworkRequest otherRequest = nai.requestAt(i);
2527 if (otherRequest.legacyType == nri.request.legacyType &&
2528 otherRequest.isRequest()) {
2529 if (DBG) log(" still have other legacy request - leaving");
2530 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002531 }
2532 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002533 }
2534
Erik Klineacdd6392016-07-07 16:50:58 +09002535 if (doRemove) {
2536 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002537 }
2538 }
Erik Klineacdd6392016-07-07 16:50:58 +09002539
2540 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2541 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2542 nri.request);
2543 }
2544 } else {
2545 // listens don't have a singular affectedNetwork. Check all networks to see
2546 // if this listen request applies and remove it.
2547 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2548 nai.removeRequest(nri.request.requestId);
2549 if (nri.request.networkCapabilities.hasSignalStrength() &&
2550 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2551 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2552 }
2553 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002554 }
2555 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002556
Lorenzo Colitti18660282016-07-04 12:55:44 +09002557 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002558 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2559 enforceConnectivityInternalPermission();
2560 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002561 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002562 }
2563
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002564 @Override
2565 public void setAvoidUnvalidated(Network network) {
2566 enforceConnectivityInternalPermission();
2567 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2568 }
2569
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002570 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2571 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2572 " accept=" + accept + " always=" + always);
2573
2574 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2575 if (nai == null) {
2576 // Nothing to do.
2577 return;
2578 }
2579
2580 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002581 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002582 return;
2583 }
2584
2585 if (!nai.networkMisc.explicitlySelected) {
2586 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2587 }
2588
2589 if (accept != nai.networkMisc.acceptUnvalidated) {
2590 int oldScore = nai.getCurrentScore();
2591 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002592 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002593 sendUpdatedScoreToFactories(nai);
2594 }
2595
2596 if (always) {
2597 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002598 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002599 }
2600
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002601 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002602 // Tell the NetworkAgent to not automatically reconnect to the network.
2603 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2604 // Teardown the nework.
2605 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002606 }
2607
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002608 }
2609
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002610 private void handleSetAvoidUnvalidated(Network network) {
2611 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2612 if (nai == null || nai.lastValidated) {
2613 // Nothing to do. The network either disconnected or revalidated.
2614 return;
2615 }
2616 if (!nai.avoidUnvalidated) {
2617 int oldScore = nai.getCurrentScore();
2618 nai.avoidUnvalidated = true;
2619 rematchAllNetworksAndRequests(nai, oldScore);
2620 sendUpdatedScoreToFactories(nai);
2621 }
2622 }
2623
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002624 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002625 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002626 mHandler.sendMessageDelayed(
2627 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2628 PROMPT_UNVALIDATED_DELAY_MS);
2629 }
2630
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002631 @Override
2632 public void startCaptivePortalApp(Network network) {
2633 enforceConnectivityInternalPermission();
2634 mHandler.post(() -> {
2635 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2636 if (nai == null) return;
2637 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2638 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2639 });
2640 }
2641
Hugo Benichic8e9e122016-09-14 23:23:08 +00002642 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002643 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002644 }
2645
Erik Kline065ab6e2016-10-02 18:02:14 +09002646 private void rematchForAvoidBadWifiUpdate() {
2647 rematchAllNetworksAndRequests(null, 0);
2648 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2649 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2650 sendUpdatedScoreToFactories(nai);
2651 }
2652 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002653 }
2654
Erik Kline065ab6e2016-10-02 18:02:14 +09002655 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002656 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002657 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002658 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002659 if (!configRestrict) {
2660 pw.println("Bad Wi-Fi avoidance: unrestricted");
2661 return;
2662 }
2663
2664 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2665 pw.increaseIndent();
2666 pw.println("Config restrict: " + configRestrict);
2667
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002668 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002669 String description;
2670 // Can't use a switch statement because strings are legal case labels, but null is not.
2671 if ("0".equals(value)) {
2672 description = "get stuck";
2673 } else if (value == null) {
2674 description = "prompt";
2675 } else if ("1".equals(value)) {
2676 description = "avoid";
2677 } else {
2678 description = value + " (?)";
2679 }
2680 pw.println("User setting: " + description);
2681 pw.println("Network overrides:");
2682 pw.increaseIndent();
2683 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2684 if (nai.avoidUnvalidated) {
2685 pw.println(nai.name());
2686 }
2687 }
2688 pw.decreaseIndent();
2689 pw.decreaseIndent();
2690 }
2691
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002692 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2693 final String action;
2694 switch (type) {
2695 case NO_INTERNET:
2696 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2697 break;
2698 case LOST_INTERNET:
2699 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2700 break;
2701 default:
2702 Slog.wtf(TAG, "Unknown notification type " + type);
2703 return;
2704 }
2705
2706 Intent intent = new Intent(action);
2707 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2708 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2709 intent.setClassName("com.android.settings",
2710 "com.android.settings.wifi.WifiNoInternetDialog");
2711
2712 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2713 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2714 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2715 }
2716
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002717 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002718 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002719 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2720
2721 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2722 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002723 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002724 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002725 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2726 return;
2727 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002728 showValidationNotification(nai, NotificationType.NO_INTERNET);
2729 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002730
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002731 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2732 NetworkCapabilities nc = nai.networkCapabilities;
2733 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002734
Erik Kline065ab6e2016-10-02 18:02:14 +09002735 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002736 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002737 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2738 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002739 }
2740
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002741 @Override
2742 public int getMultipathPreference(Network network) {
2743 enforceAccessPermission();
2744
2745 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Jeff Sharkey43d2a172017-07-12 10:50:42 -06002746 if (nai != null && nai.networkCapabilities
2747 .hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)) {
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002748 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2749 }
2750
2751 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2752 }
2753
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002754 private class InternalHandler extends Handler {
2755 public InternalHandler(Looper looper) {
2756 super(looper);
2757 }
2758
2759 @Override
2760 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002761 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002762 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002763 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002764 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002765 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002766 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002767 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002768 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002769 break;
2770 }
Jason Monkdecd2952013-10-10 14:02:51 -04002771 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002772 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002773 break;
2774 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002775 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002776 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2777 break;
2778 }
2779 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2780 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002781 break;
2782 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002783 case EVENT_REGISTER_NETWORK_AGENT: {
2784 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2785 break;
2786 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002787 case EVENT_REGISTER_NETWORK_REQUEST:
2788 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002789 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002790 break;
2791 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002792 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2793 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002794 handleRegisterNetworkRequestWithIntent(msg);
2795 break;
2796 }
Erik Kline57faba92015-11-25 12:49:38 +09002797 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2798 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2799 handleTimedOutNetworkRequest(nri);
2800 break;
2801 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002802 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2803 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2804 break;
2805 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002806 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002807 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002808 break;
2809 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002810 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002811 Network network = (Network) msg.obj;
2812 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002813 break;
2814 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002815 case EVENT_SET_AVOID_UNVALIDATED: {
2816 handleSetAvoidUnvalidated((Network) msg.obj);
2817 break;
2818 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002819 case EVENT_PROMPT_UNVALIDATED: {
2820 handlePromptUnvalidated((Network) msg.obj);
2821 break;
2822 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002823 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2824 handleMobileDataAlwaysOn();
2825 break;
2826 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002827 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2828 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2829 mKeepaliveTracker.handleStartKeepalive(msg);
2830 break;
2831 }
2832 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2833 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2834 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2835 int slot = msg.arg1;
2836 int reason = msg.arg2;
2837 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2838 break;
2839 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002840 case EVENT_SYSTEM_READY: {
2841 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2842 nai.networkMonitor.systemReady = true;
2843 }
2844 break;
2845 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002846 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002847 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002848 break;
2849 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002850 }
2851 }
2852 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002853
2854 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002855 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002856 public int tether(String iface, String callerPkg) {
2857 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002858 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002859 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002860 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002861 } else {
2862 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2863 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002864 }
2865
2866 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002867 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002868 public int untether(String iface, String callerPkg) {
2869 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002870
2871 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002872 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002873 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002874 } else {
2875 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2876 }
2877 }
2878
2879 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002880 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002881 public int getLastTetherError(String iface) {
2882 enforceTetherAccessPermission();
2883
2884 if (isTetheringSupported()) {
2885 return mTethering.getLastTetherError(iface);
2886 } else {
2887 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2888 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002889 }
2890
2891 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002892 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002893 public String[] getTetherableUsbRegexs() {
2894 enforceTetherAccessPermission();
2895 if (isTetheringSupported()) {
2896 return mTethering.getTetherableUsbRegexs();
2897 } else {
2898 return new String[0];
2899 }
2900 }
2901
Lorenzo Colitti18660282016-07-04 12:55:44 +09002902 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002903 public String[] getTetherableWifiRegexs() {
2904 enforceTetherAccessPermission();
2905 if (isTetheringSupported()) {
2906 return mTethering.getTetherableWifiRegexs();
2907 } else {
2908 return new String[0];
2909 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002910 }
2911
Lorenzo Colitti18660282016-07-04 12:55:44 +09002912 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002913 public String[] getTetherableBluetoothRegexs() {
2914 enforceTetherAccessPermission();
2915 if (isTetheringSupported()) {
2916 return mTethering.getTetherableBluetoothRegexs();
2917 } else {
2918 return new String[0];
2919 }
2920 }
2921
Lorenzo Colitti18660282016-07-04 12:55:44 +09002922 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002923 public int setUsbTethering(boolean enable, String callerPkg) {
2924 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002925 if (isTetheringSupported()) {
2926 return mTethering.setUsbTethering(enable);
2927 } else {
2928 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2929 }
2930 }
2931
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002932 // TODO - move iface listing, queries, etc to new module
2933 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002934 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002935 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002936 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002937 return mTethering.getTetherableIfaces();
2938 }
2939
Lorenzo Colitti18660282016-07-04 12:55:44 +09002940 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002941 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002942 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002943 return mTethering.getTetheredIfaces();
2944 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002945
Lorenzo Colitti18660282016-07-04 12:55:44 +09002946 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002947 public String[] getTetheringErroredIfaces() {
2948 enforceTetherAccessPermission();
2949 return mTethering.getErroredIfaces();
2950 }
2951
Lorenzo Colitti18660282016-07-04 12:55:44 +09002952 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002953 public String[] getTetheredDhcpRanges() {
2954 enforceConnectivityInternalPermission();
2955 return mTethering.getTetheredDhcpRanges();
2956 }
2957
Udam Saini0e94c362017-06-07 12:06:28 -07002958 @Override
2959 public boolean isTetheringSupported(String callerPkg) {
2960 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
2961 return isTetheringSupported();
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.
Udam Saini0e94c362017-06-07 12:06:28 -07002967 private boolean isTetheringSupported() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002968 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
2969 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
2970 Settings.Global.TETHER_SUPPORTED, defaultVal));
2971 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002972 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07002973
2974 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
2975 boolean adminUser = false;
2976 final long token = Binder.clearCallingIdentity();
2977 try {
2978 adminUser = mUserManager.isAdminUser();
2979 } finally {
2980 Binder.restoreCallingIdentity(token);
2981 }
2982
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002983 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002984 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002985
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002986 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002987 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
2988 String callerPkg) {
2989 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002990 if (!isTetheringSupported()) {
2991 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2992 return;
2993 }
2994 mTethering.startTethering(type, receiver, showProvisioningUi);
2995 }
2996
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002997 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002998 public void stopTethering(int type, String callerPkg) {
2999 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003000 mTethering.stopTethering(type);
3001 }
3002
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003003 // Called when we lose the default network and have no replacement yet.
3004 // This will automatically be cleared after X seconds or a new default network
3005 // becomes CONNECTED, whichever happens first. The timer is started by the
3006 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003007 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003008 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003009 if (mNetTransitionWakeLock.isHeld()) {
3010 return;
3011 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003012 mNetTransitionWakeLock.acquire();
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003013 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003014 mWakelockLogs.log("ACQUIRE for " + forWhom);
3015 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3016 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003017 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003018
Hugo Benichi4c31b342017-03-30 23:18:10 +09003019 // Called when we gain a new default network to release the network transition wakelock in a
3020 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3021 // message is cancelled.
3022 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003023 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003024 if (!mNetTransitionWakeLock.isHeld()) {
3025 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003026 }
3027 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003028 // Cancel self timeout on wakelock hold.
3029 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3030 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3031 mHandler.sendMessageDelayed(msg, 1000);
3032 }
3033
3034 // Called when either message of ensureNetworkTransitionWakelock or
3035 // scheduleReleaseNetworkTransitionWakelock is processed.
3036 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3037 String event = eventName(eventId);
3038 synchronized (this) {
3039 if (!mNetTransitionWakeLock.isHeld()) {
3040 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3041 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3042 return;
3043 }
3044 mNetTransitionWakeLock.release();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003045 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003046 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003047 }
3048
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003049 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003050 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003051 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003052 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003053 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003054 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003055 }
3056
Lorenzo Colitti18660282016-07-04 12:55:44 +09003057 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003058 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003059 enforceAccessPermission();
3060 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003061 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003062 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003063 mHandler.sendMessage(
3064 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3065 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003066
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003067 private void handleReportNetworkConnectivity(
3068 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003069 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003070 if (network == null) {
3071 nai = getDefaultNetwork();
3072 } else {
3073 nai = getNetworkAgentInfoForNetwork(network);
3074 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003075 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3076 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3077 return;
3078 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003079 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003080 if (hasConnectivity == nai.lastValidated) {
3081 return;
3082 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003083 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003084 int netid = nai.network.netId;
3085 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003086 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003087 // Validating a network that has not yet connected could result in a call to
3088 // rematchNetworkAndRequests() which is not meant to work on such networks.
3089 if (!nai.everConnected) {
3090 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003091 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003092 LinkProperties lp = getLinkProperties(nai);
3093 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3094 return;
3095 }
3096 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003097 }
3098
Paul Jensencee9b512015-05-06 07:32:40 -04003099 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003100 // this information is already available as a world read/writable jvm property
3101 // so this API change wouldn't have a benifit. It also breaks the passing
3102 // of proxy info to all the JVMs.
3103 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003104 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003105 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003106 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3107 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003108 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003109 }
3110
Lorenzo Colitti18660282016-07-04 12:55:44 +09003111 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003112 public ProxyInfo getProxyForNetwork(Network network) {
3113 if (network == null) return getDefaultProxy();
3114 final ProxyInfo globalProxy = getGlobalProxy();
3115 if (globalProxy != null) return globalProxy;
3116 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3117 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3118 // caller may not have.
3119 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3120 if (nai == null) return null;
3121 synchronized (nai) {
3122 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3123 if (proxyInfo == null) return null;
3124 return new ProxyInfo(proxyInfo);
3125 }
3126 }
3127
Paul Jensene0bef712014-12-10 15:12:18 -05003128 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3129 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3130 // proxy is null then there is no proxy in place).
3131 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3132 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3133 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3134 proxy = null;
3135 }
3136 return proxy;
3137 }
3138
3139 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3140 // better for determining if a new proxy broadcast is necessary:
3141 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3142 // avoid unnecessary broadcasts.
3143 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3144 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3145 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3146 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3147 // all set.
3148 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3149 a = canonicalizeProxyInfo(a);
3150 b = canonicalizeProxyInfo(b);
3151 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3152 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3153 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3154 }
3155
Jason Monk207900c2014-04-25 15:00:09 -04003156 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003157 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003158
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003159 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003160 if (proxyProperties == mGlobalProxy) return;
3161 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3162 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3163
3164 String host = "";
3165 int port = 0;
3166 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003167 String pacFileUrl = "";
3168 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003169 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003170 if (!proxyProperties.isValid()) {
3171 if (DBG)
3172 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3173 return;
3174 }
Jason Monk207900c2014-04-25 15:00:09 -04003175 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003176 host = mGlobalProxy.getHost();
3177 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003178 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003179 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003180 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003181 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003182 } else {
3183 mGlobalProxy = null;
3184 }
3185 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003186 final long token = Binder.clearCallingIdentity();
3187 try {
3188 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3189 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3190 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3191 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003192 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003193 } finally {
3194 Binder.restoreCallingIdentity(token);
3195 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003196
Jason Monkcf0f97a2014-10-02 15:39:38 -04003197 if (mGlobalProxy == null) {
3198 proxyProperties = mDefaultProxy;
3199 }
3200 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003201 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003202 }
3203
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003204 private void loadGlobalProxy() {
3205 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003206 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3207 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3208 String exclList = Settings.Global.getString(res,
3209 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003210 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3211 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003212 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003213 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003214 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003215 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003216 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003217 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003218 if (!proxyProperties.isValid()) {
3219 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3220 return;
3221 }
3222
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003223 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003224 mGlobalProxy = proxyProperties;
3225 }
3226 }
3227 }
3228
Jason Monk207900c2014-04-25 15:00:09 -04003229 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003230 // this information is already available as a world read/writable jvm property
3231 // so this API change wouldn't have a benifit. It also breaks the passing
3232 // of proxy info to all the JVMs.
3233 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003234 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003235 return mGlobalProxy;
3236 }
3237 }
3238
Jason Monk207900c2014-04-25 15:00:09 -04003239 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003240 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003241 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003242 proxy = null;
3243 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003244 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003245 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003246 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003247 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003248 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3249 return;
3250 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003251
3252 // This call could be coming from the PacManager, containing the port of the local
3253 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3254 // global (to get the correct local port), and send a broadcast.
3255 // TODO: Switch PacManager to have its own message to send back rather than
3256 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003257 if ((mGlobalProxy != null) && (proxy != null)
3258 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003259 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3260 mGlobalProxy = proxy;
3261 sendProxyBroadcast(mGlobalProxy);
3262 return;
3263 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003264 mDefaultProxy = proxy;
3265
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003266 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003267 if (!mDefaultProxyDisabled) {
3268 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003269 }
3270 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003271 }
3272
Paul Jensene0bef712014-12-10 15:12:18 -05003273 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3274 // This method gets called when any network changes proxy, but the broadcast only ever contains
3275 // the default proxy (even if it hasn't changed).
3276 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3277 // world where an app might be bound to a non-default network.
3278 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3279 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3280 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3281
3282 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3283 sendProxyBroadcast(getDefaultProxy());
3284 }
3285 }
3286
Robert Greenwalt434203a2010-10-11 16:00:27 -07003287 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003288 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3289 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003290 if (!TextUtils.isEmpty(proxy)) {
3291 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003292 if (data.length == 0) {
3293 return;
3294 }
3295
Robert Greenwalt434203a2010-10-11 16:00:27 -07003296 String proxyHost = data[0];
3297 int proxyPort = 8080;
3298 if (data.length > 1) {
3299 try {
3300 proxyPort = Integer.parseInt(data[1]);
3301 } catch (NumberFormatException e) {
3302 return;
3303 }
3304 }
Jason Monk207900c2014-04-25 15:00:09 -04003305 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003306 setGlobalProxy(p);
3307 }
3308 }
3309
Jason Monk207900c2014-04-25 15:00:09 -04003310 private void sendProxyBroadcast(ProxyInfo proxy) {
3311 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003312 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003313 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003314 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003315 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3316 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003317 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003318 final long ident = Binder.clearCallingIdentity();
3319 try {
3320 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3321 } finally {
3322 Binder.restoreCallingIdentity(ident);
3323 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003324 }
3325
3326 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003327 final private HashMap<Uri, Integer> mUriEventMap;
3328 final private Context mContext;
3329 final private Handler mHandler;
3330
3331 SettingsObserver(Context context, Handler handler) {
3332 super(null);
3333 mUriEventMap = new HashMap<Uri, Integer>();
3334 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003335 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003336 }
3337
Erik Klineda4bfa82015-04-30 12:58:40 +09003338 void observe(Uri uri, int what) {
3339 mUriEventMap.put(uri, what);
3340 final ContentResolver resolver = mContext.getContentResolver();
3341 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003342 }
3343
3344 @Override
3345 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003346 Slog.wtf(TAG, "Should never be reached.");
3347 }
3348
3349 @Override
3350 public void onChange(boolean selfChange, Uri uri) {
3351 final Integer what = mUriEventMap.get(uri);
3352 if (what != null) {
3353 mHandler.obtainMessage(what.intValue()).sendToTarget();
3354 } else {
3355 loge("No matching event to send for URI=" + uri);
3356 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003357 }
3358 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003359
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003360 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003361 Slog.d(TAG, s);
3362 }
3363
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003364 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003365 Slog.e(TAG, s);
3366 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003367
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003368 private static void loge(String s, Throwable t) {
3369 Slog.e(TAG, s, t);
3370 }
3371
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003372 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003373 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003374 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3375 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3376 *
3377 * @param oldPackage Package name of the application which currently controls VPN, which will
3378 * be replaced. If there is no such application, this should should either be
3379 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3380 * @param newPackage Package name of the application which should gain control of VPN, or
3381 * {@code null} to disable.
3382 * @param userId User for whom to prepare the new VPN.
3383 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003384 * @hide
3385 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003386 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003387 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3388 int userId) {
3389 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003390 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003391
Hugo Benichi20035e02017-04-26 14:53:28 +09003392 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003393 Vpn vpn = mVpns.get(userId);
3394 if (vpn != null) {
3395 return vpn.prepare(oldPackage, newPackage);
3396 } else {
3397 return false;
3398 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003399 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003400 }
3401
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003402 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003403 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3404 * This method is used by system-privileged apps.
3405 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3406 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3407 *
3408 * @param packageName The package for which authorization state should change.
3409 * @param userId User for whom {@code packageName} is installed.
3410 * @param authorized {@code true} if this app should be able to start a VPN connection without
3411 * explicit user approval, {@code false} if not.
3412 *
Jeff Davidson05542602014-08-11 14:07:27 -07003413 * @hide
3414 */
3415 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003416 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3417 enforceCrossUserPermission(userId);
3418
Hugo Benichi20035e02017-04-26 14:53:28 +09003419 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003420 Vpn vpn = mVpns.get(userId);
3421 if (vpn != null) {
3422 vpn.setPackageAuthorization(packageName, authorized);
3423 }
Jeff Davidson05542602014-08-11 14:07:27 -07003424 }
3425 }
3426
3427 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003428 * Configure a TUN interface and return its file descriptor. Parameters
3429 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003430 * and not available in ConnectivityManager. Permissions are checked in
3431 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003432 * @hide
3433 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003434 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003435 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003436 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003437 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003438 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003439 return mVpns.get(user).establish(config);
3440 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003441 }
3442
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003443 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003444 * Start legacy VPN, controlling native daemons as needed. Creates a
3445 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003446 */
3447 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003448 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003449 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003450 final LinkProperties egress = getActiveLinkProperties();
3451 if (egress == null) {
3452 throw new IllegalStateException("Missing active network connection");
3453 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003454 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003455 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003456 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3457 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003458 }
3459
3460 /**
3461 * Return the information of the ongoing legacy VPN. This method is used
3462 * by VpnSettings and not available in ConnectivityManager. Permissions
3463 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003464 */
3465 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003466 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3467 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003468
Hugo Benichi20035e02017-04-26 14:53:28 +09003469 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003470 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003471 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003472 }
3473
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003474 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003475 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3476 * and not available in ConnectivityManager.
3477 */
3478 @Override
3479 public VpnInfo[] getAllVpnInfo() {
3480 enforceConnectivityInternalPermission();
3481 if (mLockdownEnabled) {
3482 return new VpnInfo[0];
3483 }
3484
Hugo Benichi20035e02017-04-26 14:53:28 +09003485 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003486 List<VpnInfo> infoList = new ArrayList<>();
3487 for (int i = 0; i < mVpns.size(); i++) {
3488 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3489 if (info != null) {
3490 infoList.add(info);
3491 }
3492 }
3493 return infoList.toArray(new VpnInfo[infoList.size()]);
3494 }
3495 }
3496
3497 /**
3498 * @return VPN information for accounting, or null if we can't retrieve all required
3499 * information, e.g primary underlying iface.
3500 */
3501 @Nullable
3502 private VpnInfo createVpnInfo(Vpn vpn) {
3503 VpnInfo info = vpn.getVpnInfo();
3504 if (info == null) {
3505 return null;
3506 }
3507 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3508 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3509 // the underlyingNetworks list.
3510 if (underlyingNetworks == null) {
3511 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3512 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3513 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3514 }
3515 } else if (underlyingNetworks.length > 0) {
3516 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3517 if (linkProperties != null) {
3518 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3519 }
3520 }
3521 return info.primaryUnderlyingIface == null ? null : info;
3522 }
3523
3524 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003525 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3526 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003527 * Permissions are checked in Vpn class.
3528 * @hide
3529 */
3530 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003531 public VpnConfig getVpnConfig(int userId) {
3532 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003533 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003534 Vpn vpn = mVpns.get(userId);
3535 if (vpn != null) {
3536 return vpn.getVpnConfig();
3537 } else {
3538 return null;
3539 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003540 }
3541 }
3542
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003543 @Override
3544 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003545 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3546 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3547 return false;
3548 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003549
3550 // Tear down existing lockdown if profile was removed
3551 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3552 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003553 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3554 if (profileTag == null) {
3555 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3556 return false;
3557 }
3558 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003559 final VpnProfile profile = VpnProfile.decode(
3560 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003561 if (profile == null) {
3562 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3563 setLockdownTracker(null);
3564 return true;
3565 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003566 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003567 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003568 Vpn vpn = mVpns.get(user);
3569 if (vpn == null) {
3570 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3571 return false;
3572 }
3573 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003574 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003575 } else {
3576 setLockdownTracker(null);
3577 }
3578
3579 return true;
3580 }
3581
3582 /**
3583 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3584 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3585 */
3586 private void setLockdownTracker(LockdownVpnTracker tracker) {
3587 // Shutdown any existing tracker
3588 final LockdownVpnTracker existing = mLockdownTracker;
3589 mLockdownTracker = null;
3590 if (existing != null) {
3591 existing.shutdown();
3592 }
3593
Robin Leec3736bc2017-03-10 16:19:54 +00003594 if (tracker != null) {
3595 mLockdownTracker = tracker;
3596 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003597 }
3598 }
3599
3600 private void throwIfLockdownEnabled() {
3601 if (mLockdownEnabled) {
3602 throw new IllegalStateException("Unavailable in lockdown mode");
3603 }
3604 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003605
Robin Lee244ce8e2016-01-05 18:03:46 +00003606 /**
Robin Lee17e61832016-05-09 13:46:28 +01003607 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3608 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003609 *
Robin Lee17e61832016-05-09 13:46:28 +01003610 * @return {@code true} if the service was started, the service was already connected, or there
3611 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003612 */
Robin Lee17e61832016-05-09 13:46:28 +01003613 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003614 synchronized (mVpns) {
3615 Vpn vpn = mVpns.get(userId);
3616 if (vpn == null) {
3617 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3618 // exists already.
3619 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3620 return false;
3621 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003622
Robin Lee812800c2016-05-13 15:38:08 +01003623 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003624 }
3625 }
3626
3627 @Override
Robin Leedc679712016-05-03 13:23:03 +01003628 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003629 enforceConnectivityInternalPermission();
3630 enforceCrossUserPermission(userId);
3631
3632 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3633 if (LockdownVpnTracker.isEnabled()) {
3634 return false;
3635 }
3636
Robin Lee244ce8e2016-01-05 18:03:46 +00003637 synchronized (mVpns) {
3638 Vpn vpn = mVpns.get(userId);
3639 if (vpn == null) {
3640 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3641 return false;
3642 }
Robin Lee17e61832016-05-09 13:46:28 +01003643 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003644 return false;
3645 }
Robin Lee17e61832016-05-09 13:46:28 +01003646 if (!startAlwaysOnVpn(userId)) {
3647 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003648 return false;
3649 }
3650 }
3651 return true;
3652 }
3653
3654 @Override
3655 public String getAlwaysOnVpnPackage(int userId) {
3656 enforceConnectivityInternalPermission();
3657 enforceCrossUserPermission(userId);
3658
3659 synchronized (mVpns) {
3660 Vpn vpn = mVpns.get(userId);
3661 if (vpn == null) {
3662 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3663 return null;
3664 }
3665 return vpn.getAlwaysOnPackage();
3666 }
3667 }
3668
Wink Savilleab9321d2013-06-29 21:10:57 -07003669 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003670 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003671 // TODO: Remove? Any reason to trigger a provisioning check?
3672 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003673 }
3674
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003675 /** Location to an updatable file listing carrier provisioning urls.
3676 * An example:
3677 *
3678 * <?xml version="1.0" encoding="utf-8"?>
3679 * <provisioningUrls>
3680 * <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 -07003681 * </provisioningUrls>
3682 */
3683 private static final String PROVISIONING_URL_PATH =
3684 "/data/misc/radio/provisioning_urls.xml";
3685 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003686
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003687 /** XML tag for root element. */
3688 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3689 /** XML tag for individual url */
3690 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003691 /** XML attribute for mcc */
3692 private static final String ATTR_MCC = "mcc";
3693 /** XML attribute for mnc */
3694 private static final String ATTR_MNC = "mnc";
3695
Paul Jensen434dde82015-06-11 09:43:30 -04003696 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003697 FileReader fileReader = null;
3698 XmlPullParser parser = null;
3699 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003700
3701 try {
3702 fileReader = new FileReader(mProvisioningUrlFile);
3703 parser = Xml.newPullParser();
3704 parser.setInput(fileReader);
3705 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3706
3707 while (true) {
3708 XmlUtils.nextElement(parser);
3709
3710 String element = parser.getName();
3711 if (element == null) break;
3712
Paul Jensen434dde82015-06-11 09:43:30 -04003713 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003714 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3715 try {
3716 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3717 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3718 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3719 parser.next();
3720 if (parser.getEventType() == XmlPullParser.TEXT) {
3721 return parser.getText();
3722 }
3723 }
3724 }
3725 } catch (NumberFormatException e) {
3726 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3727 }
3728 }
3729 }
3730 return null;
3731 } catch (FileNotFoundException e) {
3732 loge("Carrier Provisioning Urls file not found");
3733 } catch (XmlPullParserException e) {
3734 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3735 } catch (IOException e) {
3736 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3737 } finally {
3738 if (fileReader != null) {
3739 try {
3740 fileReader.close();
3741 } catch (IOException e) {}
3742 }
3743 }
3744 return null;
3745 }
3746
Wink Saville42d4f082013-07-20 20:31:59 -07003747 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003748 public String getMobileProvisioningUrl() {
3749 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003750 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003751 if (TextUtils.isEmpty(url)) {
3752 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003753 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003754 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003755 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003756 }
Wink Saville8cf35602013-07-10 23:00:07 -07003757 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003758 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003759 String phoneNumber = mTelephonyManager.getLine1Number();
3760 if (TextUtils.isEmpty(phoneNumber)) {
3761 phoneNumber = "0000000000";
3762 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003763 url = String.format(url,
3764 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3765 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003766 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003767 }
3768
Wink Savilleab9321d2013-06-29 21:10:57 -07003769 return url;
3770 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003771
Wink Saville948282b2013-08-29 08:55:16 -07003772 @Override
3773 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003774 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003775 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003776 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3777 return;
3778 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003779 final long ident = Binder.clearCallingIdentity();
3780 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003781 // Concatenate the range of types onto the range of NetIDs.
3782 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3783 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003784 } finally {
3785 Binder.restoreCallingIdentity(ident);
3786 }
Wink Saville948282b2013-08-29 08:55:16 -07003787 }
Wink Saville7788c612013-08-29 14:57:08 -07003788
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003789 @Override
3790 public void setAirplaneMode(boolean enable) {
3791 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003792 final long ident = Binder.clearCallingIdentity();
3793 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003794 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003795 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003796 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3797 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003798 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003799 } finally {
3800 Binder.restoreCallingIdentity(ident);
3801 }
3802 }
3803
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003804 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003805 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003806 Vpn userVpn = mVpns.get(userId);
3807 if (userVpn != null) {
3808 loge("Starting user already has a VPN");
3809 return;
3810 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003811 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003812 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003813 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003814 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3815 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003816 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003817 }
3818
3819 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003820 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003821 Vpn userVpn = mVpns.get(userId);
3822 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003823 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003824 return;
3825 }
Robin Lee17e61832016-05-09 13:46:28 +01003826 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003827 mVpns.delete(userId);
3828 }
3829 }
3830
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003831 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003832 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003833 final int vpnsSize = mVpns.size();
3834 for (int i = 0; i < vpnsSize; i++) {
3835 Vpn vpn = mVpns.valueAt(i);
3836 vpn.onUserAdded(userId);
3837 }
3838 }
3839 }
3840
3841 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003842 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003843 final int vpnsSize = mVpns.size();
3844 for (int i = 0; i < vpnsSize; i++) {
3845 Vpn vpn = mVpns.valueAt(i);
3846 vpn.onUserRemoved(userId);
3847 }
3848 }
3849 }
3850
Robin Lee89e7a692016-02-29 14:38:17 +00003851 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003852 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3853 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3854 updateLockdownVpn();
3855 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003856 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003857 }
3858 }
3859
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003860 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3861 @Override
3862 public void onReceive(Context context, Intent intent) {
3863 final String action = intent.getAction();
3864 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3865 if (userId == UserHandle.USER_NULL) return;
3866
Robin Lee323f29d2016-05-04 16:38:06 +01003867 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003868 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003869 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003870 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003871 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3872 onUserAdded(userId);
3873 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3874 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003875 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3876 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003877 }
3878 }
3879 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003880
Robin Lee95204e02017-01-27 11:59:22 +00003881 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3882 @Override
3883 public void onReceive(Context context, Intent intent) {
3884 // Try creating lockdown tracker, since user present usually means
3885 // unlocked keystore.
3886 updateLockdownVpn();
3887 mContext.unregisterReceiver(this);
3888 }
3889 };
3890
Robert Greenwalta67be032014-05-16 15:49:14 -07003891 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3892 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003893 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3894 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003895
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003896 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3897 // Map from UID to number of NetworkRequests that UID has filed.
3898 @GuardedBy("mUidToNetworkRequestCount")
3899 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3900
Robert Greenwalta67be032014-05-16 15:49:14 -07003901 private static class NetworkFactoryInfo {
3902 public final String name;
3903 public final Messenger messenger;
3904 public final AsyncChannel asyncChannel;
3905
3906 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3907 this.name = name;
3908 this.messenger = messenger;
3909 this.asyncChannel = asyncChannel;
3910 }
3911 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003912
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003913 private void ensureNetworkRequestHasType(NetworkRequest request) {
3914 if (request.type == NetworkRequest.Type.NONE) {
3915 throw new IllegalArgumentException(
3916 "All NetworkRequests in ConnectivityService must have a type");
3917 }
3918 }
3919
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003920 /**
3921 * Tracks info about the requester.
3922 * Also used to notice when the calling process dies so we can self-expire
3923 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003924 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003925 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003926 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003927 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003928 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003929 final int mPid;
3930 final int mUid;
3931 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003932
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003933 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003934 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003935 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003936 mPendingIntent = pi;
3937 messenger = null;
3938 mBinder = null;
3939 mPid = getCallingPid();
3940 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003941 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003942 }
3943
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003944 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003945 super();
3946 messenger = m;
3947 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003948 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003949 mBinder = binder;
3950 mPid = getCallingPid();
3951 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003952 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003953 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003954
3955 try {
3956 mBinder.linkToDeath(this, 0);
3957 } catch (RemoteException e) {
3958 binderDied();
3959 }
3960 }
3961
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003962 private void enforceRequestCountLimit() {
3963 synchronized (mUidToNetworkRequestCount) {
3964 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3965 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09003966 throw new ServiceSpecificException(
3967 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003968 }
3969 mUidToNetworkRequestCount.put(mUid, networkRequests);
3970 }
3971 }
3972
Robert Greenwalt9258c642014-03-26 16:47:06 -07003973 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003974 if (mBinder != null) {
3975 mBinder.unlinkToDeath(this, 0);
3976 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003977 }
3978
3979 public void binderDied() {
3980 log("ConnectivityService NetworkRequestInfo binderDied(" +
3981 request + ", " + mBinder + ")");
3982 releaseNetworkRequest(request);
3983 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003984
3985 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003986 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003987 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003988 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003989 }
3990
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003991 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3992 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3993 if (badCapability != null) {
3994 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003995 }
3996 }
3997
Erik Kline9d598e12015-07-13 16:37:51 +09003998 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003999 final SortedSet<Integer> thresholds = new TreeSet();
4000 synchronized (nai) {
4001 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4002 if (nri.request.networkCapabilities.hasSignalStrength() &&
4003 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4004 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4005 }
4006 }
4007 }
Erik Kline9d598e12015-07-13 16:37:51 +09004008 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004009 }
4010
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004011 private void updateSignalStrengthThresholds(
4012 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4013 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004014 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004015 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4016
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004017 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004018 String detail;
4019 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4020 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4021 } else {
4022 detail = reason;
4023 }
4024 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4025 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4026 }
4027
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004028 nai.asyncChannel.sendMessage(
4029 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004030 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004031 }
4032
Etan Cohen859748f2017-04-03 17:42:34 -07004033 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4034 if (nc == null) {
4035 return;
4036 }
4037 NetworkSpecifier ns = nc.getNetworkSpecifier();
4038 if (ns == null) {
4039 return;
4040 }
4041 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4042 ns.assertValidFromUid(Binder.getCallingUid());
4043 }
4044
Robert Greenwalt9258c642014-03-26 16:47:06 -07004045 @Override
4046 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004047 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004048 final NetworkRequest.Type type = (networkCapabilities == null)
4049 ? NetworkRequest.Type.TRACK_DEFAULT
4050 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004051 // If the requested networkCapabilities is null, take them instead from
4052 // the default network request. This allows callers to keep track of
4053 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004054 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004055 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4056 enforceAccessPermission();
4057 } else {
4058 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4059 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004060 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4061 // of the app when the request is filed, but we never change the request if the app
4062 // changes network state. http://b/29964605
4063 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004064 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004065 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004066
Etan Cohenba07c8c2017-02-05 10:42:27 -08004067 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004068 throw new IllegalArgumentException("Bad timeout specified");
4069 }
Etan Cohen859748f2017-04-03 17:42:34 -07004070 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004071
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004072 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004073 nextNetworkRequestId(), type);
4074 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004075 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004076
4077 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004078 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004080 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004081 }
4082 return networkRequest;
4083 }
4084
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004085 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004086 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004087 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004088 } else {
4089 enforceChangePermission();
4090 }
4091 }
4092
fenglub15e72b2015-03-20 11:29:56 -07004093 @Override
fengludb571472015-04-21 17:12:05 -07004094 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004095 enforceAccessPermission();
4096 NetworkAgentInfo nai = null;
4097 if (network == null) {
4098 return false;
4099 }
4100 synchronized (mNetworkForNetId) {
4101 nai = mNetworkForNetId.get(network.netId);
4102 }
4103 if (nai != null) {
4104 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4105 return true;
4106 }
4107 return false;
4108 }
4109
Felipe Lemeee27cab2016-06-20 16:36:29 -07004110 private boolean isSystem(int uid) {
4111 return uid < Process.FIRST_APPLICATION_UID;
4112 }
fenglub15e72b2015-03-20 11:29:56 -07004113
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004114 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004115 final int uid = Binder.getCallingUid();
4116 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004117 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004118 return;
4119 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004120 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4121 // Policy already enforced.
4122 return;
4123 }
4124 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4125 // If UID is restricted, don't allow them to bring up metered APNs.
4126 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004127 }
4128 }
4129
Robert Greenwalt9258c642014-03-26 16:47:06 -07004130 @Override
4131 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4132 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004133 checkNotNull(operation, "PendingIntent cannot be null.");
4134 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4135 enforceNetworkRequestPermissions(networkCapabilities);
4136 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004137 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004138 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004139
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004140 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004141 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4142 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004143 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004144 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4145 nri));
4146 return networkRequest;
4147 }
4148
Jeremy Joslin79294842014-12-03 17:15:28 -08004149 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4150 mHandler.sendMessageDelayed(
4151 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4152 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4153 }
4154
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004155 @Override
4156 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004157 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004158 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4159 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004160 }
4161
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004162 // In order to implement the compatibility measure for pre-M apps that call
4163 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4164 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4165 // This ensures it has permission to do so.
4166 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4167 if (nc == null) {
4168 return false;
4169 }
4170 int[] transportTypes = nc.getTransportTypes();
4171 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4172 return false;
4173 }
4174 try {
4175 mContext.enforceCallingOrSelfPermission(
4176 android.Manifest.permission.ACCESS_WIFI_STATE,
4177 "ConnectivityService");
4178 } catch (SecurityException e) {
4179 return false;
4180 }
4181 return true;
4182 }
4183
Robert Greenwalt9258c642014-03-26 16:47:06 -07004184 @Override
4185 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4186 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004187 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4188 enforceAccessPermission();
4189 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004190
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004191 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4192 if (!ConnectivityManager.checkChangePermission(mContext)) {
4193 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4194 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4195 // onLost and onAvailable callbacks when networks move in and out of the background.
4196 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4197 // can't request networks.
4198 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4199 }
Etan Cohen859748f2017-04-03 17:42:34 -07004200 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004201
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004202 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004203 NetworkRequest.Type.LISTEN);
4204 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004205 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004206
4207 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4208 return networkRequest;
4209 }
4210
4211 @Override
4212 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4213 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004214 checkNotNull(operation, "PendingIntent cannot be null.");
4215 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4216 enforceAccessPermission();
4217 }
Etan Cohen859748f2017-04-03 17:42:34 -07004218 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004219
Erik Kline7523eb32015-07-09 18:24:03 +09004220 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004221 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4222 NetworkRequest.Type.LISTEN);
4223 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004224 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004225
4226 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004227 }
4228
Erik Klineacdd6392016-07-07 16:50:58 +09004229 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004230 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004231 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004232 mHandler.sendMessage(mHandler.obtainMessage(
4233 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004234 }
4235
4236 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004237 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004238 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004239 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4240 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004241 }
4242
Robert Greenwalta67be032014-05-16 15:49:14 -07004243 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004244 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004245 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4246 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4247 }
4248
4249 @Override
4250 public void unregisterNetworkFactory(Messenger messenger) {
4251 enforceConnectivityInternalPermission();
4252 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4253 }
4254
4255 private void handleUnregisterNetworkFactory(Messenger messenger) {
4256 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4257 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004258 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004259 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004260 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004261 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004262 }
4263
Robert Greenwalt7b816022014-04-18 15:25:25 -07004264 /**
4265 * NetworkAgentInfo supporting a request by requestId.
4266 * These have already been vetted (their Capabilities satisfy the request)
4267 * and the are the highest scored network available.
4268 * the are keyed off the Requests requestId.
4269 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004270 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004271 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4272 new SparseArray<NetworkAgentInfo>();
4273
Paul Jensen31a94f42015-02-13 14:18:39 -05004274 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4275 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004276 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4277 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004278 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4279 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4280 // there may not be a strict 1:1 correlation between the two.
4281 @GuardedBy("mNetworkForNetId")
4282 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004283
Robert Greenwalt7b816022014-04-18 15:25:25 -07004284 // NetworkAgentInfo keyed off its connecting messenger
4285 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004286 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004287 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4288 new HashMap<Messenger, NetworkAgentInfo>();
4289
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004290 @GuardedBy("mBlockedAppUids")
4291 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4292
Paul Jensen2c311d62014-11-17 12:34:51 -05004293 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004294 private final NetworkRequest mDefaultRequest;
4295
Erik Klineda4bfa82015-04-30 12:58:40 +09004296 // Request used to optionally keep mobile data active even when higher
4297 // priority networks like Wi-Fi are active.
4298 private final NetworkRequest mDefaultMobileDataRequest;
4299
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004300 private NetworkAgentInfo getDefaultNetwork() {
4301 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4302 }
4303
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004304 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004305 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004306 }
4307
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004308 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4309 return nri.request.requestId == mDefaultRequest.requestId;
4310 }
4311
Paul Jensen31a94f42015-02-13 14:18:39 -05004312 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004313 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004314 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004315 enforceConnectivityInternalPermission();
4316
Paul Jensen2c311d62014-11-17 12:34:51 -05004317 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4318 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004319 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004320 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4321 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004322 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004323 synchronized (this) {
4324 nai.networkMonitor.systemReady = mSystemReady;
4325 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004326 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4327 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004328 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004329 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004330 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 }
4332
4333 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4334 if (VDBG) log("Got NetworkAgent Messenger");
4335 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004336 synchronized (mNetworkForNetId) {
4337 mNetworkForNetId.put(na.network.netId, na);
4338 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4340 NetworkInfo networkInfo = na.networkInfo;
4341 na.networkInfo = null;
4342 updateNetworkInfo(na, networkInfo);
4343 }
4344
4345 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4346 LinkProperties newLp = networkAgent.linkProperties;
4347 int netId = networkAgent.network.netId;
4348
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004349 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4350 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004351 if (networkAgent.clatd != null) {
4352 networkAgent.clatd.fixupLinkProperties(oldLp);
4353 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004354
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004355 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004356 updateMtu(newLp, oldLp);
4357 // TODO - figure out what to do for clat
4358// for (LinkProperties lp : newLp.getStackedLinks()) {
4359// updateMtu(lp, null);
4360// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004361 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004362
Erik Kline94887872016-04-05 13:30:49 +09004363 updateRoutes(newLp, oldLp, netId);
4364 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004365
Paul Jensen3b759822014-05-13 11:44:01 -04004366 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004367 if (isDefaultNetwork(networkAgent)) {
4368 handleApplyDefaultProxy(newLp.getHttpProxy());
4369 } else {
4370 updateProxy(newLp, oldLp, networkAgent);
4371 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004372 // TODO - move this check to cover the whole function
4373 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004374 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004375 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4376 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004377
4378 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004379 }
4380
Lorenzo Colitti95439462014-10-09 13:44:48 +09004381 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4382 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4383 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004384
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004385 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004386 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4387 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004388 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004389 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004390 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004391 }
Paul Jensen992f2522014-04-28 10:33:11 -04004392
Joel Scherpelz668370b2017-06-08 15:35:21 +09004393 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004394 // Marks are only available on WiFi interaces. Checking for
4395 // marks on unsupported interfaces is harmless.
4396 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4397 return;
4398 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004399
Joel Scherpelz668370b2017-06-08 15:35:21 +09004400 int mark = mContext.getResources().getInteger(
4401 com.android.internal.R.integer.config_networkWakeupPacketMark);
4402 int mask = mContext.getResources().getInteger(
4403 com.android.internal.R.integer.config_networkWakeupPacketMask);
4404
4405 // Mask/mark of zero will not detect anything interesting.
4406 // Don't install rules unless both values are nonzero.
4407 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004408 return;
4409 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004410
4411 final String prefix = "iface:" + iface;
4412 try {
4413 if (add) {
4414 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4415 } else {
4416 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4417 }
4418 } catch (Exception e) {
4419 loge("Exception modifying wakeup packet monitoring: " + e);
4420 }
4421
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004422 }
4423
4424 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4425 NetworkCapabilities caps) {
Paul Jensen992f2522014-04-28 10:33:11 -04004426 CompareResult<String> interfaceDiff = new CompareResult<String>();
4427 if (oldLp != null) {
4428 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4429 } else if (newLp != null) {
4430 interfaceDiff.added = newLp.getAllInterfaceNames();
4431 }
4432 for (String iface : interfaceDiff.added) {
4433 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004434 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004435 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004436 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004437 } catch (Exception e) {
4438 loge("Exception adding interface: " + e);
4439 }
4440 }
4441 for (String iface : interfaceDiff.removed) {
4442 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004443 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004444 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004445 mNetd.removeInterfaceFromNetwork(iface, netId);
4446 } catch (Exception e) {
4447 loge("Exception removing interface: " + e);
4448 }
4449 }
4450 }
4451
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004452 /**
4453 * Have netd update routes from oldLp to newLp.
4454 * @return true if routes changed between oldLp and newLp
4455 */
4456 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004457 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4458 if (oldLp != null) {
4459 routeDiff = oldLp.compareAllRoutes(newLp);
4460 } else if (newLp != null) {
4461 routeDiff.added = newLp.getAllRoutes();
4462 }
4463
4464 // add routes before removing old in case it helps with continuous connectivity
4465
4466 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4467 for (RouteInfo route : routeDiff.added) {
4468 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004469 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004470 try {
4471 mNetd.addRoute(netId, route);
4472 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004473 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4474 loge("Exception in addRoute for non-gateway: " + e);
4475 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004476 }
4477 }
4478 for (RouteInfo route : routeDiff.added) {
4479 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004480 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004481 try {
4482 mNetd.addRoute(netId, route);
4483 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004484 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4485 loge("Exception in addRoute for gateway: " + e);
4486 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004487 }
4488 }
4489
4490 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004491 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 try {
4493 mNetd.removeRoute(netId, route);
4494 } catch (Exception e) {
4495 loge("Exception in removeRoute: " + e);
4496 }
4497 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004498 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004499 }
Erik Kline41368502015-06-17 13:19:54 +09004500
Erik Kline94887872016-04-05 13:30:49 +09004501 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4502 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4503 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004504 }
Erik Kline94887872016-04-05 13:30:49 +09004505
4506 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004507 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004508 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004509 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004510 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4511 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004512 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004513 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004514 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4515 if (defaultNai != null && defaultNai.network.netId == netId) {
4516 setDefaultDnsSystemProperties(dnses);
4517 }
Erik Kline94887872016-04-05 13:30:49 +09004518 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004519 }
4520
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004521 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4522 int last = 0;
4523 for (InetAddress dns : dnses) {
4524 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004525 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004526 }
4527 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004528 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004529 }
4530 mNumDnsEntries = last;
4531 }
4532
Erik Kline4edba012017-04-07 15:29:29 +09004533 private void setNetDnsProperty(int which, String value) {
4534 final String key = "net.dns" + which;
4535 // Log and forget errors setting unsupported properties.
4536 try {
4537 mSystemProperties.set(key, value);
4538 } catch (Exception e) {
4539 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4540 }
4541 }
4542
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004543 private String getNetworkPermission(NetworkCapabilities nc) {
4544 // TODO: make these permission strings AIDL constants instead.
4545 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4546 return NetworkManagementService.PERMISSION_SYSTEM;
4547 }
4548 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4549 return NetworkManagementService.PERMISSION_NETWORK;
4550 }
4551 return null;
4552 }
4553
Paul Jensen3d194ea2015-06-16 14:27:36 -04004554 /**
4555 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4556 * augmented with any stateful capabilities implied from {@code networkAgent}
4557 * (e.g., validated status and captive portal status).
4558 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004559 * @param oldScore score of the network before any of the changes that prompted us
4560 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004561 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004562 * @param networkCapabilities the new network capabilities.
4563 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004564 private void updateCapabilities(
4565 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004566 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4567 networkCapabilities)) {
4568 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4569 + nai.networkCapabilities + " -> " + networkCapabilities);
4570 }
4571
Paul Jensen3d194ea2015-06-16 14:27:36 -04004572 // Don't modify caller's NetworkCapabilities.
4573 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004574 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004575 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4576 } else {
4577 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4578 }
Paul Jensene0988542015-06-25 15:30:08 -04004579 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004580 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4581 } else {
4582 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4583 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004584 if (nai.isBackgroundNetwork()) {
4585 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4586 } else {
4587 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4588 }
4589
4590 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4591
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004592 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4593 final String newPermission = getNetworkPermission(networkCapabilities);
4594 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004595 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004596 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004597 } catch (RemoteException e) {
4598 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004599 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004600 }
4601
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004602 final NetworkCapabilities prevNc = nai.networkCapabilities;
4603 synchronized (nai) {
4604 nai.networkCapabilities = networkCapabilities;
4605 }
4606 if (nai.getCurrentScore() == oldScore &&
4607 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4608 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4609 // the change we're processing can't affect any requests, it can only affect the listens
4610 // on this network. We might have been called by rematchNetworkAndRequests when a
4611 // network changed foreground state.
4612 processListenRequests(nai, true);
4613 } else {
4614 // If the requestable capabilities have changed or the score changed, we can't have been
4615 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004616 rematchAllNetworksAndRequests(nai, oldScore);
4617 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004618 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004619 }
4620
Paul Jensenc8b9a742014-09-30 15:37:41 -04004621 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004622 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4623 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004624 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004625 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004626 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4627 }
4628 }
4629
Robert Greenwalt7b816022014-04-18 15:25:25 -07004630 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4631 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004632 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004633 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4634 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004635 }
4636 }
4637
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004638 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4639 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004640 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004641 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004642 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4643 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004644 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004645 sendIntent(nri.mPendingIntent, intent);
4646 }
4647 // else not handled
4648 }
4649
4650 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4651 mPendingIntentWakeLock.acquire();
4652 try {
4653 if (DBG) log("Sending " + pendingIntent);
4654 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4655 } catch (PendingIntent.CanceledException e) {
4656 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4657 mPendingIntentWakeLock.release();
4658 releasePendingNetworkRequest(pendingIntent);
4659 }
4660 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4661 }
4662
4663 @Override
4664 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4665 String resultData, Bundle resultExtras) {
4666 if (DBG) log("Finished sending " + pendingIntent);
4667 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004668 // Release with a delay so the receiving client has an opportunity to put in its
4669 // own request.
4670 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004671 }
4672
Hugo Benichidba33db2017-03-23 22:40:44 +09004673 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004674 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004675 if (nri.messenger == null) {
4676 return; // Default request has no msgr
4677 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004678 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004679 // TODO: check if defensive copies of data is needed.
4680 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004681 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004682 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4683 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004684 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004685 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004686 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004687 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004688 break;
4689 }
4690 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004691 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004692 break;
4693 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004694 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004695 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004696 break;
4697 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004698 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004699 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004700 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004701 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004702 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004703 String notification = ConnectivityManager.getCallbackName(notificationType);
4704 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004705 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004706 nri.messenger.send(msg);
4707 } catch (RemoteException e) {
4708 // may occur naturally in the race of binder death.
4709 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4710 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004711 }
4712
Hugo Benichidba33db2017-03-23 22:40:44 +09004713 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4714 bundle.putParcelable(t.getClass().getSimpleName(), t);
4715 }
4716
Paul Jensenc8b9a742014-09-30 15:37:41 -04004717 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004718 if (nai.numRequestNetworkRequests() != 0) {
4719 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4720 NetworkRequest nr = nai.requestAt(i);
4721 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004722 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004723 loge("Dead network still had at least " + nr);
4724 break;
4725 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004726 }
4727 nai.asyncChannel.disconnect();
4728 }
4729
Robert Greenwalt7b816022014-04-18 15:25:25 -07004730 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4731 if (oldNetwork == null) {
4732 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4733 return;
4734 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004735 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004736
4737 // If we get here it means that the last linger timeout for this network expired. So there
4738 // must be no other active linger timers, and we must stop lingering.
4739 oldNetwork.clearLingerState();
4740
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004741 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004742 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004743 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004744 } else {
4745 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004746 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4747 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004748 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004749 }
4750
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004751 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004752 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004753 setupDataActivityTracking(newNetwork);
4754 try {
4755 mNetd.setDefaultNetId(newNetwork.network.netId);
4756 } catch (Exception e) {
4757 loge("Exception setting default network :" + e);
4758 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004759 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004760 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004761 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004762 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004763 }
4764
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004765 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004766 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4767 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4768 NetworkRequest nr = nri.request;
4769 if (!nr.isListen()) continue;
4770 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4771 nai.removeRequest(nri.request.requestId);
4772 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4773 }
4774 }
4775
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004776 if (capabilitiesChanged) {
4777 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4778 }
4779
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004780 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4781 NetworkRequest nr = nri.request;
4782 if (!nr.isListen()) continue;
4783 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4784 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004785 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004786 }
4787 }
4788 }
4789
Paul Jensen2161a8e2014-09-11 11:00:39 -04004790 // Handles a network appearing or improving its score.
4791 //
4792 // - Evaluates all current NetworkRequests that can be
4793 // satisfied by newNetwork, and reassigns to newNetwork
4794 // any such requests for which newNetwork is the best.
4795 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004796 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004797 // needed. A network is needed if it is the best network for
4798 // one or more NetworkRequests, or if it is a VPN.
4799 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004800 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004801 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004802 //
4803 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4804 // networks that have no chance (i.e. even if validated)
4805 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004806 //
4807 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4808 // it does not remove NetworkRequests that other Networks could better satisfy.
4809 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4810 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4811 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004812 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004813 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004814 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4815 // performed to tear down unvalidated networks that have no chance (i.e. even if
4816 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004817 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004818 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004819 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004820 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004821 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004822 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004823
4824 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4825 final int score = newNetwork.getCurrentScore();
4826
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004827 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004828
Paul Jensen2161a8e2014-09-11 11:00:39 -04004829 // Find and migrate to this Network any NetworkRequests for
4830 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004831 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004832 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004833 NetworkCapabilities nc = newNetwork.networkCapabilities;
4834 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004835 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004836 // Process requests in the first pass and listens in the second pass. This allows us to
4837 // change a network's capabilities depending on which requests it has. This is only
4838 // correct if the change in capabilities doesn't affect whether the network satisfies
4839 // requests or not, and doesn't affect the network's score.
4840 if (nri.request.isListen()) continue;
4841
Paul Jensencf4c2c62015-07-01 14:16:32 -04004842 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4843 final boolean satisfies = newNetwork.satisfies(nri.request);
4844 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004845 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004846 log("Network " + newNetwork.name() + " was already satisfying" +
4847 " request " + nri.request.requestId + ". No change.");
4848 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004849 keep = true;
4850 continue;
4851 }
4852
4853 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004854 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004855 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004856 // next check if it's better than any current network we're using for
4857 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004858 if (VDBG) {
4859 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004860 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004861 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004862 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004863 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004864 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004865 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004866 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004867 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004868 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004869 affectedNetworks.add(currentNetwork);
4870 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004871 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004872 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004873 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004874 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004875 if (!newNetwork.addRequest(nri.request)) {
4876 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4877 }
4878 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004879 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004880 // Tell NetworkFactories about the new score, so they can stop
4881 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004882 // TODO - this could get expensive if we have alot of requests for this
4883 // network. Think about if there is a way to reduce this. Push
4884 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004885 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004886 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004887 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004888 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004889 if (currentNetwork != null) {
4890 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4891 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004892 }
4893 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004894 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004895 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4896 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004897 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004898 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4899 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4900 // This means this code doesn't have to handle the case where "currentNetwork" no
4901 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4902 if (DBG) {
4903 log("Network " + newNetwork.name() + " stopped satisfying" +
4904 " request " + nri.request.requestId);
4905 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004906 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004907 if (currentNetwork == newNetwork) {
4908 mNetworkForRequestId.remove(nri.request.requestId);
4909 sendUpdatedScoreToFactories(nri.request, 0);
4910 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004911 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4912 newNetwork.name() +
4913 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004914 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004915 // TODO: Technically, sending CALLBACK_LOST here is
4916 // incorrect if there is a replacement network currently
4917 // connected that can satisfy nri, which is a request
4918 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004919 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4920 // so this code is only incorrect for a network that loses
4921 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004922 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004923 }
4924 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004925 if (isNewDefault) {
4926 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004927 makeDefault(newNetwork);
4928 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4929 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004930 // Have a new default network, release the transition wakelock in
4931 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004932 }
4933
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004934 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4935 Slog.wtf(TAG, String.format(
4936 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07004937 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004938 }
4939 if (newNetwork.getCurrentScore() != score) {
4940 Slog.wtf(TAG, String.format(
4941 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08004942 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004943 }
4944
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004945 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004946 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4947 // If the network went from background to foreground or vice versa, we need to update
4948 // its foreground state. It is safe to do this after rematching the requests because
4949 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4950 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004951 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004952 } else {
4953 processListenRequests(newNetwork, false);
4954 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004955
Paul Jensencf4c2c62015-07-01 14:16:32 -04004956 // do this after the default net is switched, but
4957 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09004958 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004959
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004960 // Linger any networks that are no longer needed. This should be done after sending the
4961 // available callback for newNetwork.
4962 for (NetworkAgentInfo nai : affectedNetworks) {
4963 updateLingerState(nai, now);
4964 }
4965 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4966 // does not need to be done in any particular order.
4967 updateLingerState(newNetwork, now);
4968
Paul Jensencf4c2c62015-07-01 14:16:32 -04004969 if (isNewDefault) {
4970 // Maintain the illusion: since the legacy API only
4971 // understands one network at a time, we must pretend
4972 // that the current default network disconnected before
4973 // the new one connected.
4974 if (oldDefaultNetwork != null) {
4975 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4976 oldDefaultNetwork, true);
4977 }
4978 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4979 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4980 notifyLockdownVpn(newNetwork);
4981 }
4982
Robert Greenwalt7b816022014-04-18 15:25:25 -07004983 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004984 // Notify battery stats service about this network, both the normal
4985 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004986 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004987 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004988 final IBatteryStats bs = BatteryStatsService.getService();
4989 final int type = newNetwork.networkInfo.getType();
4990
4991 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4992 bs.noteNetworkInterfaceType(baseIface, type);
4993 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4994 final String stackedIface = stacked.getInterfaceName();
4995 bs.noteNetworkInterfaceType(stackedIface, type);
4996 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4997 }
4998 } catch (RemoteException ignored) {
4999 }
5000
Robert Greenwalt152ed372014-12-17 17:19:53 -08005001 // This has to happen after the notifyNetworkCallbacks as that tickles each
5002 // ConnectivityManager instance so that legacy requests correctly bind dns
5003 // requests to this network. The legacy users are listening for this bcast
5004 // and will generally do a dns request so they can ensureRouteToHost and if
5005 // they do that before the callbacks happen they'll use the default network.
5006 //
5007 // TODO: Is there still a race here? We send the broadcast
5008 // after sending the callback, but if the app can receive the
5009 // broadcast before the callback, it might still break.
5010 //
5011 // This *does* introduce a race where if the user uses the new api
5012 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5013 // they may get old info. Reverse this after the old startUsing api is removed.
5014 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005015 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5016 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005017 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005018 // legacy type tracker filters out repeat adds
5019 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5020 }
5021 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005022
5023 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5024 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5025 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5026 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5027 if (newNetwork.isVPN()) {
5028 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5029 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005030 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005031 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5032 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005033 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005034 if (nai.getLingerExpiry() > 0) {
5035 // This network has active linger timers and no requests, but is not
5036 // lingering. Linger it.
5037 //
5038 // One way (the only way?) this can happen if this network is unvalidated
5039 // and became unneeded due to another network improving its score to the
5040 // point where this network will no longer be able to satisfy any requests
5041 // even if it validates.
5042 updateLingerState(nai, now);
5043 } else {
5044 if (DBG) log("Reaping " + nai.name());
5045 teardownUnneededNetwork(nai);
5046 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005047 }
5048 }
5049 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005050 }
5051
Paul Jensen1c7ba022015-06-16 14:27:36 -04005052 /**
5053 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5054 * being disconnected.
5055 * @param changed If only one Network's score or capabilities have been modified since the last
5056 * time this function was called, pass this Network in this argument, otherwise pass
5057 * null.
5058 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5059 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5060 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5061 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5062 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005063 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005064 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005065 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5066 // to avoid the slowness. It is not simply enough to process just "changed", for
5067 // example in the case where "changed"'s score decreases and another network should begin
5068 // satifying a NetworkRequest that "changed" currently satisfies.
5069
5070 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5071 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5072 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005073 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005074 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005075 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005076 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005077 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5078 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5079 // Rematch higher scoring networks first to prevent requests first matching a lower
5080 // scoring network and then a higher scoring network, which could produce multiple
5081 // callbacks and inadvertently unlinger networks.
5082 Arrays.sort(nais);
5083 for (NetworkAgentInfo nai : nais) {
5084 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005085 // Only reap the last time through the loop. Reaping before all rematching
5086 // is complete could incorrectly teardown a network that hasn't yet been
5087 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005088 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005089 : ReapUnvalidatedNetworks.REAP,
5090 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005091 }
5092 }
5093 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005094
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005095 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005096 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005097 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005098 // For now only update icons for default connection.
5099 // TODO: Update WiFi and cellular icons separately. b/17237507
5100 if (!isDefaultNetwork(nai)) return;
5101
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005102 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005103 // Don't repeat publish.
5104 if (newInetCondition == mDefaultInetConditionPublished) return;
5105
5106 mDefaultInetConditionPublished = newInetCondition;
5107 sendInetConditionBroadcast(nai.networkInfo);
5108 }
5109
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005110 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5111 if (mLockdownTracker != null) {
5112 if (nai != null && nai.isVPN()) {
5113 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5114 } else {
5115 mLockdownTracker.onNetworkInfoChanged();
5116 }
5117 }
5118 }
5119
Robert Greenwalt7b816022014-04-18 15:25:25 -07005120 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005121 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005122 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005123 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005124 synchronized (networkAgent) {
5125 oldInfo = networkAgent.networkInfo;
5126 networkAgent.networkInfo = newInfo;
5127 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005128 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005129
5130 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005131 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5132 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5133 notifyIfacesChangedForNetworkStats();
5134 } else if (VDBG) log("ignoring duplicate network state non-change");
5135 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005136 return;
5137 }
5138 if (DBG) {
5139 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5140 (oldInfo == null ? "null" : oldInfo.getState()) +
5141 " to " + state);
5142 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005143
Robin Lee585e2482016-05-01 23:00:00 +01005144 if (!networkAgent.created
5145 && (state == NetworkInfo.State.CONNECTED
5146 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005147
5148 // A network that has just connected has zero requests and is thus a foreground network.
5149 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5150
Robert Greenwalt7b816022014-04-18 15:25:25 -07005151 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005152 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005153 if (networkAgent.isVPN()) {
5154 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005155 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5156 (networkAgent.networkMisc == null ||
5157 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005158 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005159 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005160 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005161 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005162 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005163 loge("Error creating network " + networkAgent.network.netId + ": "
5164 + e.getMessage());
5165 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005166 }
Paul Jenseneec75412014-08-04 12:21:19 -04005167 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005168 }
5169
5170 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5171 networkAgent.everConnected = true;
5172
Robert Greenwalt7b816022014-04-18 15:25:25 -07005173 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005174 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005175
Paul Jensenca8f16a2014-05-09 12:47:55 -04005176 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005177 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005178
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005179 if (networkAgent.isVPN()) {
5180 // Temporarily disable the default proxy (not global).
5181 synchronized (mProxyLock) {
5182 if (!mDefaultProxyDisabled) {
5183 mDefaultProxyDisabled = true;
5184 if (mGlobalProxy == null && mDefaultProxy != null) {
5185 sendProxyBroadcast(null);
5186 }
5187 }
5188 }
5189 // TODO: support proxy per network.
5190 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005191
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005192 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5193 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5194 // capabilities, so it only needs to be done once on initial connect, not every time the
5195 // network's capabilities change. Note that we do this before rematching the network,
5196 // so we could decide to tear it down immediately afterwards. That's fine though - on
5197 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5198 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005199 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005200
Paul Jensen2161a8e2014-09-11 11:00:39 -04005201 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005202 final long now = SystemClock.elapsedRealtime();
5203 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005204
5205 // This has to happen after matching the requests, because callbacks are just requests.
5206 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005207 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005208 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005209 if (networkAgent.isVPN()) {
5210 synchronized (mProxyLock) {
5211 if (mDefaultProxyDisabled) {
5212 mDefaultProxyDisabled = false;
5213 if (mGlobalProxy == null && mDefaultProxy != null) {
5214 sendProxyBroadcast(mDefaultProxy);
5215 }
5216 }
5217 }
5218 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005219 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5220 state == NetworkInfo.State.SUSPENDED) {
5221 // going into or coming out of SUSPEND: rescore and notify
5222 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005223 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005224 }
5225 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5226 ConnectivityManager.CALLBACK_SUSPENDED :
5227 ConnectivityManager.CALLBACK_RESUMED));
5228 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005229 }
5230 }
5231
Robert Greenwaltac96c522014-06-03 16:43:57 -07005232 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005233 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005234 if (score < 0) {
5235 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5236 "). Bumping score to min of 0");
5237 score = 0;
5238 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005239
Paul Jensen2161a8e2014-09-11 11:00:39 -04005240 final int oldScore = nai.getCurrentScore();
5241 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005242
Paul Jensen85cf78e2015-06-25 13:25:07 -04005243 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005244
Paul Jensenc8b9a742014-09-30 15:37:41 -04005245 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005246 }
5247
Erik Klinec75d4fa2017-02-15 19:59:17 +09005248 // Notify only this one new request of the current state. Transfer all the
5249 // current state by calling NetworkCapabilities and LinkProperties callbacks
5250 // so that callers can be guaranteed to have as close to atomicity in state
5251 // transfer as can be supported by this current API.
5252 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005253 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005254 if (nri.mPendingIntent != null) {
5255 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5256 // Attempt no subsequent state pushes where intents are involved.
5257 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005258 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005259
5260 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5261 // Whether a network is currently suspended is also an important
5262 // element of state to be transferred (it would not otherwise be
5263 // delivered by any currently available mechanism).
5264 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5265 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5266 }
5267 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5268 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005269 }
5270
Robert Greenwalt8d482522015-06-24 13:23:42 -07005271 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005272 // The NetworkInfo we actually send out has no bearing on the real
5273 // state of affairs. For example, if the default connection is mobile,
5274 // and a request for HIPRI has just gone away, we need to pretend that
5275 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5276 // the state to DISCONNECTED, even though the network is of type MOBILE
5277 // and is still connected.
5278 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5279 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005280 if (state != DetailedState.DISCONNECTED) {
5281 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005282 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005283 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005284 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005285 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5286 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5287 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5288 if (info.isFailover()) {
5289 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5290 nai.networkInfo.setFailover(false);
5291 }
5292 if (info.getReason() != null) {
5293 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5294 }
5295 if (info.getExtraInfo() != null) {
5296 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5297 }
5298 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005299 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005300 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005301 if (newDefaultAgent != null) {
5302 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5303 newDefaultAgent.networkInfo);
5304 } else {
5305 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5306 }
5307 }
5308 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5309 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005310 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005311 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005312 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005313 }
5314 }
5315 }
5316
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005317 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005318 if (VDBG) {
5319 String notification = ConnectivityManager.getCallbackName(notifyType);
5320 log("notifyType " + notification + " for " + networkAgent.name());
5321 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005322 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5323 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005324 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5325 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005326 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5327 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005328 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005329 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005330 } else {
5331 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5332 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005333 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005334 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005335
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005336 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5337 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5338 }
5339
Jeff Sharkey69736342014-12-08 14:50:12 -08005340 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005341 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5342 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005343 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005344 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005345 try {
5346 mStatsService.forceUpdateIfaces();
5347 } catch (Exception ignored) {
5348 }
5349 }
5350
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005351 @Override
5352 public boolean addVpnAddress(String address, int prefixLength) {
5353 throwIfLockdownEnabled();
5354 int user = UserHandle.getUserId(Binder.getCallingUid());
5355 synchronized (mVpns) {
5356 return mVpns.get(user).addAddress(address, prefixLength);
5357 }
5358 }
5359
5360 @Override
5361 public boolean removeVpnAddress(String address, int prefixLength) {
5362 throwIfLockdownEnabled();
5363 int user = UserHandle.getUserId(Binder.getCallingUid());
5364 synchronized (mVpns) {
5365 return mVpns.get(user).removeAddress(address, prefixLength);
5366 }
5367 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005368
5369 @Override
5370 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5371 throwIfLockdownEnabled();
5372 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005373 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005374 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005375 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005376 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005377 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005378 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005379 }
5380 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005381 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005382
5383 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005384 public String getCaptivePortalServerUrl() {
Udam Saini0e94c362017-06-07 12:06:28 -07005385 enforceConnectivityInternalPermission();
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005386 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005387 }
5388
5389 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005390 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5391 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5392 enforceKeepalivePermission();
5393 mKeepaliveTracker.startNattKeepalive(
5394 getNetworkAgentInfoForNetwork(network),
5395 intervalSeconds, messenger, binder,
5396 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5397 }
5398
5399 @Override
5400 public void stopKeepalive(Network network, int slot) {
5401 mHandler.sendMessage(mHandler.obtainMessage(
5402 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5403 }
5404
5405 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005406 public void factoryReset() {
5407 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005408
5409 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5410 return;
5411 }
5412
Robin Lee3b3dd942015-05-12 18:14:58 +01005413 final int userId = UserHandle.getCallingUserId();
5414
Stuart Scottf1fb3972015-04-02 18:00:02 -07005415 // Turn airplane mode off
5416 setAirplaneMode(false);
5417
Stuart Scotte3e314d2015-04-20 14:07:45 -07005418 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5419 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005420 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005421 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005422 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005423 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005424 }
5425
Stuart Scotte3e314d2015-04-20 14:07:45 -07005426 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005427 // Remove always-on package
5428 synchronized (mVpns) {
5429 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5430 if (alwaysOnPackage != null) {
5431 setAlwaysOnVpnPackage(userId, null, false);
5432 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5433 }
5434 }
5435
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005436 // Turn Always-on VPN off
5437 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5438 final long ident = Binder.clearCallingIdentity();
5439 try {
5440 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5441 mLockdownEnabled = false;
5442 setLockdownTracker(null);
5443 } finally {
5444 Binder.restoreCallingIdentity(ident);
5445 }
5446 }
5447
Stuart Scotte3e314d2015-04-20 14:07:45 -07005448 // Turn VPN off
5449 VpnConfig vpnConfig = getVpnConfig(userId);
5450 if (vpnConfig != null) {
5451 if (vpnConfig.legacy) {
5452 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5453 } else {
5454 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5455 // in the future without user intervention.
5456 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005457
Victor Changb04a5ea2016-05-30 20:36:30 +01005458 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005459 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005460 }
5461 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005462
5463 Settings.Global.putString(mContext.getContentResolver(),
5464 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005465 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005466
5467 @VisibleForTesting
5468 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5469 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5470 return new NetworkMonitor(context, handler, nai, defaultRequest);
5471 }
Erik Kline48f12f22016-04-14 17:30:59 +09005472
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005473 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005474 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5475 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005476 }
5477
5478 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005479 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5480 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5481 }
5482
Hugo Benichicfddd682016-05-31 16:28:06 +09005483 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005484 int newNetid = NETID_UNSET;
5485 int prevNetid = NETID_UNSET;
5486 int[] transports = new int[0];
5487 boolean hadIPv4 = false;
5488 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005489
Hugo Benichi5f16f762016-04-20 12:09:33 +09005490 if (newNai != null) {
5491 newNetid = newNai.network.netId;
5492 transports = newNai.networkCapabilities.getTransportTypes();
5493 }
5494 if (prevNai != null) {
5495 prevNetid = prevNai.network.netId;
5496 final LinkProperties lp = prevNai.linkProperties;
5497 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5498 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5499 }
5500
Hugo Benichicfddd682016-05-31 16:28:06 +09005501 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5502 }
5503
5504 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5505 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005506 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005507
5508 private static boolean toBool(int encodedBoolean) {
5509 return encodedBoolean != 0; // Only 0 means false.
5510 }
5511
5512 private static int encodeBool(boolean b) {
5513 return b ? 1 : 0;
5514 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005515}