blob: cee81a88047401de907d7a5fe1f0546eb65723b6 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Hugo Benichia0385682017-03-22 17:07:57 +090032import static com.android.internal.util.Preconditions.checkNotNull;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060033
Wenchao Tongf5ea3402015-03-04 13:26:38 -080034import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080035import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090036import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070038import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.ContentResolver;
40import android.content.Context;
41import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070042import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070044import android.content.res.Configuration;
Robert Greenwalt434203a2010-10-11 16:00:27 -070045import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090047import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070049import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070050import android.net.INetworkPolicyListener;
51import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070052import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080053import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070054import android.net.LinkProperties.CompareResult;
Hugo Benichib577d652017-06-27 15:13:20 +090055import android.net.MatchAllNetworkSpecifier;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070056import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070057import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070058import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070062import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070063import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkRequest;
Etan Cohen859748f2017-04-03 17:42:34 -070065import android.net.NetworkSpecifier;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070066import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070067import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070068import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040069import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070070import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040071import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040072import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090073import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090074import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090075import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090076import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080078import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070079import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040080import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070082import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070083import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070084import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.os.Looper;
86import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070087import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070088import android.os.ParcelFileDescriptor;
Hugo Benichidba33db2017-03-23 22:40:44 +090089import android.os.Parcelable;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070090import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070091import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070092import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080093import android.os.ResultReceiver;
Hugo Benichicb883232017-05-11 13:16:17 +090094import android.os.ServiceSpecificException;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090095import android.os.SystemClock;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070096import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040097import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080098import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070099import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700100import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -0700101import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700102import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700103import android.util.LocalLog;
104import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600105import android.util.Log;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800106import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700107import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500108import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700109import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700110import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800111
Wink Savilleab9321d2013-06-29 21:10:57 -0700112import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400113import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400114import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700115import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700116import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700117import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700118import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800119import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700120import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700121import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600122import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700123import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900124import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900125import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700126import com.android.internal.util.XmlUtils;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900127import com.android.server.LocalServices;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700128import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400129import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900130import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700131import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900132import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900133import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700134import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600135import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400136import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900137import com.android.server.connectivity.NetworkNotificationManager;
138import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400139import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700140import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800141import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700142import com.android.server.connectivity.Vpn;
Hugo Benichib577d652017-06-27 15:13:20 +0900143import com.android.server.connectivity.tethering.TetheringDependencies;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700144import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700145import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900146import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600147
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700148import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700149
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700150import org.xmlpull.v1.XmlPullParser;
151import org.xmlpull.v1.XmlPullParserException;
152
153import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700155import java.io.FileNotFoundException;
156import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700157import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800158import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700159import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700160import java.net.InetAddress;
161import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700162import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700163import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700165import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700166import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700167import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700168import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700169import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700170import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600171import java.util.SortedSet;
172import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800173
174/**
175 * @hide
176 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800177public class ConnectivityService extends IConnectivityManager.Stub
178 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900179 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Erik Kline7747fd42017-05-12 16:52:48 +0900181 public static final String DIAG_ARG = "--diag";
182 public static final String SHORT_ARG = "--short";
Erik Klineee363c42017-05-29 09:11:03 +0900183 public static final String TETHERING_ARG = "tethering";
Erik Kline7747fd42017-05-12 16:52:48 +0900184
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900185 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700186 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800187
Jake Hamby786e71a2014-02-06 14:43:50 -0800188 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900189 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700190
Jeff Sharkey899223b2012-08-04 15:24:58 -0700191 // TODO: create better separation between radio types and network types
192
Robert Greenwalt42acef32009-08-12 16:08:25 -0700193 // how long to wait before switching back to a radio's default network
194 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
195 // system property that can override the above value
196 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
197 "android.telephony.apn-restore";
198
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900199 // How long to wait before putting up a "This network doesn't have an Internet connection,
200 // connect anyway?" dialog after the user selects a network that doesn't validate.
201 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
202
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900203 // Default to 30s linger time-out. Modifiable only for testing.
204 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
205 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
206 @VisibleForTesting
207 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
208
Jeremy Joslin79294842014-12-03 17:15:28 -0800209 // How long to delay to removal of a pending intent based request.
210 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
211 private final int mReleasePendingIntentDelayMs;
212
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900213 private MockableSystemProperties mSystemProperties;
214
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800215 private Tethering mTethering;
216
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700217 private final PermissionMonitor mPermissionMonitor;
218
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700219 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700220
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700221 @GuardedBy("mVpns")
222 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700223
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700224 private boolean mLockdownEnabled;
225 private LockdownVpnTracker mLockdownTracker;
226
Erik Klineda4bfa82015-04-30 12:58:40 +0900227 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800228 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700229 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700230 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800231
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800232 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800233
234 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700235 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800236
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700237 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800238 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700239 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900240 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700241
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700242 private String mCurrentTcpBufferSizes;
243
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700244 private static final int ENABLED = 1;
245 private static final int DISABLED = 0;
246
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900247 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900248 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
249 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900250
Paul Jensenb10e37f2014-11-25 12:33:08 -0500251 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400252 // Tear down networks that have no chance (e.g. even if validated) of becoming
253 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500254 // all networks have been rematched against all NetworkRequests.
255 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400256 // Don't reap networks. This should be passed when some networks have not yet been
257 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500258 DONT_REAP
259 };
260
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900261 private enum UnneededFor {
262 LINGER, // Determine whether this network is unneeded and should be lingered.
263 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
264 }
265
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700266 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700267 * used internally to change our mobile data enabled flag
268 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700269 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700270
271 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700272 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700273 * from one net to another. Clear happens when we get a new
274 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
275 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700276 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700277 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700278
Robert Greenwalt434203a2010-10-11 16:00:27 -0700279 /**
280 * used internally to reload global proxy settings
281 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700282 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700283
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700284 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400285 * PAC manager has received new port.
286 */
287 private static final int EVENT_PROXY_HAS_CHANGED = 16;
288
Robert Greenwalte049c232014-04-11 15:53:27 -0700289 /**
290 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700291 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700292 */
293 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
294
Robert Greenwalt7b816022014-04-18 15:25:25 -0700295 /**
296 * used internally when registering NetworkAgents
297 * obj = Messenger
298 */
299 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
300
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 /**
302 * used to add a network request
303 * includes a NetworkRequestInfo
304 */
305 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
306
307 /**
308 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900309 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700310 * cancel it.
311 * includes a NetworkRequestInfo
312 */
313 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
314
315 /**
316 * used to add a network listener - no request
317 * includes a NetworkRequestInfo
318 */
319 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
320
321 /**
322 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400323 * arg1 = UID of caller
324 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700325 */
326 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
327
Robert Greenwalta67be032014-05-16 15:49:14 -0700328 /**
329 * used internally when registering NetworkFactories
330 * obj = Messenger
331 */
332 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
333
Robert Greenwalt27711812014-06-25 16:45:57 -0700334 /**
335 * used internally to expire a wakelock when transitioning
336 * from one net to another. Expire happens when we fail to find
337 * a new network (typically after 1 minute) -
338 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
339 * a replacement network.
340 */
341 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
342
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700343 /**
344 * Used internally to indicate the system is ready.
345 */
346 private static final int EVENT_SYSTEM_READY = 25;
347
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800348 /**
349 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400350 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800351 */
352 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
353
354 /**
355 * used to remove a pending intent and its associated network request.
356 * arg1 = UID of caller
357 * obj = PendingIntent
358 */
359 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
360
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900361 /**
362 * used to specify whether a network should be used even if unvalidated.
363 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
364 * arg2 = whether to remember this choice in the future (1 or 0)
365 * obj = network
366 */
367 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
368
369 /**
370 * used to ask the user to confirm a connection to an unvalidated network.
371 * obj = network
372 */
373 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700374
Erik Klineda4bfa82015-04-30 12:58:40 +0900375 /**
376 * used internally to (re)configure mobile data always-on settings.
377 */
378 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
379
Paul Jensen694f2b82015-06-17 14:15:39 -0400380 /**
381 * used to add a network listener with a pending intent
382 * obj = NetworkRequestInfo
383 */
384 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
385
Hugo Benichi1c51d7a2017-04-06 17:22:18 +0900386 /**
387 * used to specify whether a network should not be penalized when it becomes unvalidated.
388 */
389 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
390
391 /**
392 * used to trigger revalidation of a network.
393 */
394 private static final int EVENT_REVALIDATE_NETWORK = 36;
395
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900396 private static String eventName(int what) {
397 return sMagicDecoderRing.get(what, Integer.toString(what));
398 }
399
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900400 /** Handler thread used for both of the handlers below. */
401 @VisibleForTesting
402 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700403 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700404 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700405 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700406 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700407
Mike Lockwood0f79b542009-08-14 14:18:49 -0400408 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800409 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400410
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700411 private PowerManager.WakeLock mNetTransitionWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700412 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800413 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700414
Robert Greenwalt434203a2010-10-11 16:00:27 -0700415 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400416 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700417 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700418 private boolean mDefaultProxyDisabled = false;
419
Robert Greenwalt434203a2010-10-11 16:00:27 -0700420 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400421 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700422
Jason Monk602b2322013-07-03 17:04:33 -0400423 private PacManager mPacManager = null;
424
Erik Klineda4bfa82015-04-30 12:58:40 +0900425 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700426
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400427 private UserManager mUserManager;
428
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700429 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700430 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700431
Robert Greenwalt50393202011-06-21 17:26:14 -0700432 // the set of network types that can only be enabled by system/sig apps
433 List mProtectedNetworks;
434
John Spurlockbf991a82013-06-24 14:20:23 -0400435 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700436
Wink Savilleab9321d2013-06-29 21:10:57 -0700437 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400438
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900439 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900440 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900441 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900442
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700443 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
444 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700445 private final static int MAX_NET_ID = 65535;
446 private int mNextNetId = MIN_NET_ID;
447
Robert Greenwalt34524f02014-05-18 16:22:10 -0700448 // sequence number of NetworkRequests
449 private int mNextNetworkRequestId = 1;
450
Erik Kline7523eb32015-07-09 18:24:03 +0900451 // NetworkRequest activity String log entries.
452 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
453 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
454
Hugo Benichic2ae2872016-07-11 11:05:12 +0900455 // NetworkInfo blocked and unblocked String log entries
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900456 private static final int MAX_NETWORK_INFO_LOGS = 40;
Hugo Benichic2ae2872016-07-11 11:05:12 +0900457 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
458
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900459 private static final int MAX_WAKELOCK_LOGS = 20;
460 private final LocalLog mWakelockLogs = new LocalLog(MAX_WAKELOCK_LOGS);
Hugo Benichic3318aa2017-09-05 13:25:07 +0900461 private int mTotalWakelockAcquisitions = 0;
462 private int mTotalWakelockReleases = 0;
463 private long mTotalWakelockDurationMs = 0;
464 private long mMaxWakelockDurationMs = 0;
465 private long mLastWakeLockAcquireTimestamp = 0;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +0900466
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700467 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
468 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400469 private static class ValidationLog {
470 final Network mNetwork;
471 final String mNetworkExtraInfo;
472 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700473
Paul Jensen0808eb82016-06-03 13:51:21 -0400474 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
475 mNetwork = network;
476 mNetworkExtraInfo = networkExtraInfo;
477 mLog = log;
478 }
479 }
480 private final ArrayDeque<ValidationLog> mValidationLogs =
481 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
482
483 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Hugo Benichi20035e02017-04-26 14:53:28 +0900484 synchronized (mValidationLogs) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700485 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
486 mValidationLogs.removeLast();
487 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400488 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700489 }
490 }
491
Hugo Benichif9fdf872016-07-28 17:53:06 +0900492 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900493
Erik Kline065ab6e2016-10-02 18:02:14 +0900494 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900495 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900496
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700497 /**
498 * Implements support for the legacy "one network per network type" model.
499 *
500 * We used to have a static array of NetworkStateTrackers, one for each
501 * network type, but that doesn't work any more now that we can have,
502 * for example, more that one wifi network. This class stores all the
503 * NetworkAgentInfo objects that support a given type, but the legacy
504 * API will only see the first one.
505 *
506 * It serves two main purposes:
507 *
508 * 1. Provide information about "the network for a given type" (since this
509 * API only supports one).
510 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
511 * the first network for a given type changes, or if the default network
512 * changes.
513 */
514 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900515
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900516 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900517 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900518
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 /**
520 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
521 * Each list holds references to all NetworkAgentInfos that are used to
522 * satisfy requests for that network type.
523 *
524 * This array is built out at startup such that an unsupported network
525 * doesn't get an ArrayList instance, making this a tristate:
526 * unsupported, supported but not active and active.
527 *
528 * The actual lists are populated when we scan the network types that
529 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900530 *
531 * Threading model:
532 * - addSupportedType() is only called in the constructor
533 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
534 * They are therefore not thread-safe with respect to each other.
535 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
536 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
537 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700538 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900539 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700540
541 public LegacyTypeTracker() {
542 mTypeLists = (ArrayList<NetworkAgentInfo>[])
543 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
544 }
545
546 public void addSupportedType(int type) {
547 if (mTypeLists[type] != null) {
548 throw new IllegalStateException(
549 "legacy list for type " + type + "already initialized");
550 }
551 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
552 }
553
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700554 public boolean isTypeSupported(int type) {
555 return isNetworkTypeValid(type) && mTypeLists[type] != null;
556 }
557
558 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900559 synchronized (mTypeLists) {
560 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
561 return mTypeLists[type].get(0);
562 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900564 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700565 }
566
Robert Greenwalt8d482522015-06-24 13:23:42 -0700567 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900568 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900569 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700570 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900571 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900572 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900573 }
574 }
575
576 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700577 public void add(int type, NetworkAgentInfo nai) {
578 if (!isTypeSupported(type)) {
579 return; // Invalid network type.
580 }
581 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
582
583 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
584 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700585 return;
586 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900587 synchronized (mTypeLists) {
588 list.add(nai);
589 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900590
591 // 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 +0900592 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900593 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700594 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
595 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700596 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700597 }
598
Lorenzo Colittia793a672014-07-31 23:20:17 +0900599 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900600 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900601 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
602 if (list == null || list.isEmpty()) {
603 return;
604 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900605 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606
Hugo Benichi78caa2582016-06-21 09:48:07 +0900607 synchronized (mTypeLists) {
608 if (!list.remove(nai)) {
609 return;
610 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900611 }
612
Robert Greenwalt8d482522015-06-24 13:23:42 -0700613 final DetailedState state = DetailedState.DISCONNECTED;
614
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900615 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700616 maybeLogBroadcast(nai, state, type, wasDefault);
617 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900618 }
619
620 if (!list.isEmpty() && wasFirstNetwork) {
621 if (DBG) log("Other network available for type " + type +
622 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900623 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700624 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
625 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900626 }
627 }
628
629 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900630 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
631 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700632 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900633 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700634 }
635 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700636
Robert Greenwalt8d482522015-06-24 13:23:42 -0700637 // send out another legacy broadcast - currently only used for suspend/unsuspend
638 // toggle
639 public void update(NetworkAgentInfo nai) {
640 final boolean isDefault = isDefaultNetwork(nai);
641 final DetailedState state = nai.networkInfo.getDetailedState();
642 for (int type = 0; type < mTypeLists.length; type++) {
643 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700644 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900645 final boolean isFirst = contains && (nai == list.get(0));
646 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700647 maybeLogBroadcast(nai, state, type, isDefault);
648 sendLegacyNetworkBroadcast(nai, state, type);
649 }
650 }
651 }
652
Lorenzo Colittia793a672014-07-31 23:20:17 +0900653 private String naiToString(NetworkAgentInfo nai) {
654 String name = (nai != null) ? nai.name() : "null";
655 String state = (nai.networkInfo != null) ?
656 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
657 "???/???";
658 return name + " " + state;
659 }
660
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700661 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900662 pw.println("mLegacyTypeTracker:");
663 pw.increaseIndent();
664 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700665 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900666 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700667 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900668 pw.println();
669 pw.println("Current state:");
670 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900671 synchronized (mTypeLists) {
672 for (int type = 0; type < mTypeLists.length; type++) {
673 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
674 for (NetworkAgentInfo nai : mTypeLists[type]) {
675 pw.println(type + " " + naiToString(nai));
676 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900677 }
678 }
679 pw.decreaseIndent();
680 pw.decreaseIndent();
681 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700682 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700683 }
684 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
685
Jeff Sharkey899223b2012-08-04 15:24:58 -0700686 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700687 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900688 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
689 }
690
691 @VisibleForTesting
692 protected ConnectivityService(Context context, INetworkManagementService netManager,
693 INetworkStatsService statsService, INetworkPolicyManager policyManager,
694 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800695 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800696
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900697 mSystemProperties = getSystemProperties();
698
Hugo Benichif9fdf872016-07-28 17:53:06 +0900699 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900700 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900701 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900702 mNetworkRequests.put(mDefaultRequest, defaultNRI);
703 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900704
705 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900706 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700707
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900708 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900709 mHandlerThread.start();
710 mHandler = new InternalHandler(mHandlerThread.getLooper());
711 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700712
Jeremy Joslin79294842014-12-03 17:15:28 -0800713 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
714 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
715
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900716 mLingerDelayMs = mSystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900717
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700718 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700719 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800720 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700721 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900722 mPolicyManagerInternal = checkNotNull(
723 LocalServices.getService(NetworkPolicyManagerInternal.class),
724 "missing NetworkPolicyManagerInternal");
725
Jeff Sharkey82f85212012-08-24 11:17:25 -0700726 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700727 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700728
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700729 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900730 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700731 } catch (RemoteException e) {
732 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700733 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700734 }
735
736 final PowerManager powerManager = (PowerManager) context.getSystemService(
737 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700738 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
739 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
740 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800741 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700742
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700743 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700744
Wink Saville51f456f2013-04-23 14:26:51 -0700745 // TODO: What is the "correct" way to do determine if this is a wifi only device?
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900746 boolean wifiOnly = mSystemProperties.getBoolean("ro.radio.noril", false);
Wink Saville51f456f2013-04-23 14:26:51 -0700747 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700748 String[] naStrings = context.getResources().getStringArray(
749 com.android.internal.R.array.networkAttributes);
750 for (String naString : naStrings) {
751 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700752 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700753 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700754 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800755 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700756 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700757 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700758 }
Wink Saville51f456f2013-04-23 14:26:51 -0700759 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
760 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
761 n.type);
762 continue;
763 }
Wink Saville975c8482011-04-07 14:23:45 -0700764 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800765 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700766 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700767 continue;
768 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700769 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700770
Wink Saville975c8482011-04-07 14:23:45 -0700771 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700772 mNetworksDefined++;
773 } catch(Exception e) {
774 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700775 }
776 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700777
778 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
779 if (mNetConfigs[TYPE_VPN] == null) {
780 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
781 // don't need to add TYPE_VPN to mNetConfigs.
782 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
783 mNetworksDefined++; // used only in the log() statement below.
784 }
785
Wink Saville5e56bc52013-07-29 15:00:57 -0700786 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700787
Robert Greenwalt50393202011-06-21 17:26:14 -0700788 mProtectedNetworks = new ArrayList<Integer>();
789 int[] protectedNetworks = context.getResources().getIntArray(
790 com.android.internal.R.array.config_protectedNetworks);
791 for (int p : protectedNetworks) {
792 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
793 mProtectedNetworks.add(p);
794 } else {
795 if (DBG) loge("Ignoring protectedNetwork " + p);
796 }
797 }
798
Lorenzo Colitti42cdf572017-03-21 18:54:11 +0900799 mTestMode = mSystemProperties.get("cm.test.mode").equals("true")
800 && mSystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700801
Erik Kline47222fc2017-04-30 19:36:15 +0900802 mTethering = makeTethering();
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800803
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700804 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
805
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700806 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700807 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100808 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700809 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700810 intentFilter.addAction(Intent.ACTION_USER_ADDED);
811 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000812 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700813 mContext.registerReceiverAsUser(
814 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000815 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
816 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900817
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700818 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700819 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700820 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700821 } catch (RemoteException e) {
822 loge("Error registering observer :" + e);
823 }
824
Erik Klineda4bfa82015-04-30 12:58:40 +0900825 mSettingsObserver = new SettingsObserver(mContext, mHandler);
826 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800827
John Spurlockbf991a82013-06-24 14:20:23 -0400828 mDataConnectionStats = new DataConnectionStats(mContext);
829 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400830
Jason Monkdecd2952013-10-10 14:02:51 -0400831 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700832
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400833 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900834
835 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900836 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
837 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900838
839 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
840 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
841 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
842 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
843 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
844 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
845 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900846
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900847 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900848 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900849 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800850 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700851
Erik Kline47222fc2017-04-30 19:36:15 +0900852 private Tethering makeTethering() {
853 // TODO: Move other elements into @Overridden getters.
854 final TetheringDependencies deps = new TetheringDependencies();
855 return new Tethering(mContext, mNetd, mStatsService, mPolicyManager,
856 IoThread.get().getLooper(), new MockableSystemProperties(),
857 deps);
858 }
859
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900860 private NetworkRequest createInternetRequestForTransport(
861 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900862 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900863 netCap.addCapability(NET_CAPABILITY_INTERNET);
864 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900865 if (transportType > -1) {
866 netCap.addTransportType(transportType);
867 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900868 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900869 }
870
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900871 // Used only for testing.
872 // TODO: Delete this and either:
873 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
874 // changing ContentResolver to make registerContentObserver non-final).
875 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
876 // by subclassing SettingsObserver.
877 @VisibleForTesting
878 void updateMobileDataAlwaysOn() {
879 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
880 }
881
Erik Klineda4bfa82015-04-30 12:58:40 +0900882 private void handleMobileDataAlwaysOn() {
Hugo Benichiab7d2e62017-04-21 15:07:12 +0900883 final boolean enable = toBool(Settings.Global.getInt(
884 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1));
Erik Klineda4bfa82015-04-30 12:58:40 +0900885 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
886 if (enable == isEnabled) {
887 return; // Nothing to do.
888 }
889
890 if (enable) {
891 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900892 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900893 } else {
894 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
895 }
896 }
897
898 private void registerSettingsCallbacks() {
899 // Watch for global HTTP proxy changes.
900 mSettingsObserver.observe(
901 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
902 EVENT_APPLY_GLOBAL_HTTP_PROXY);
903
904 // Watch for whether or not to keep mobile data always on.
905 mSettingsObserver.observe(
906 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
907 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
908 }
909
Robert Greenwalt34524f02014-05-18 16:22:10 -0700910 private synchronized int nextNetworkRequestId() {
911 return mNextNetworkRequestId++;
912 }
913
Paul Jensen67b0b072015-06-10 11:22:17 -0400914 @VisibleForTesting
915 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400916 synchronized (mNetworkForNetId) {
917 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
918 int netId = mNextNetId;
919 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
920 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500921 if (!mNetIdInUse.get(netId)) {
922 mNetIdInUse.put(netId, true);
923 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400924 }
925 }
926 }
927 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700928 }
929
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600930 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800931 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600932 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
933 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600935 state = nai.getNetworkState();
936 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800937 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600938 final NetworkInfo info = new NetworkInfo(networkType, 0,
939 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800940 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
941 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600942 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
943 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800944 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600945 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600946 return state;
947 } else {
948 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800949 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400950 }
951
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800952 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
953 if (network == null) {
954 return null;
955 }
956 synchronized (mNetworkForNetId) {
957 return mNetworkForNetId.get(network.netId);
958 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600959 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800960
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900961 private Network[] getVpnUnderlyingNetworks(int uid) {
962 if (!mLockdownEnabled) {
963 int user = UserHandle.getUserId(uid);
964 synchronized (mVpns) {
965 Vpn vpn = mVpns.get(user);
966 if (vpn != null && vpn.appliesToUid(uid)) {
967 return vpn.getUnderlyingNetworks();
968 }
969 }
970 }
971 return null;
972 }
973
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800974 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400975 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800976
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900977 final Network[] networks = getVpnUnderlyingNetworks(uid);
978 if (networks != null) {
979 // getUnderlyingNetworks() returns:
980 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
981 // empty array => the VPN explicitly said "no default network".
982 // non-empty array => the VPN specified one or more default networks; we use the
983 // first one.
984 if (networks.length > 0) {
985 nai = getNetworkAgentInfoForNetwork(networks[0]);
986 } else {
987 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800988 }
989 }
990
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800991 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600992 return nai.getNetworkState();
993 } else {
994 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800995 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400996 }
997
998 /**
999 * Check if UID should be blocked from using the network with the given LinkProperties.
1000 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001001 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
1002 boolean ignoreBlocked) {
1003 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001004 if (ignoreBlocked) {
1005 return false;
1006 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001007 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001008 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
1009 if (isSystem(uid)) {
1010 return false;
1011 }
Robin Lee17e61832016-05-09 13:46:28 +01001012 synchronized (mVpns) {
1013 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
1014 if (vpn != null && vpn.isBlockingUid(uid)) {
1015 return true;
1016 }
1017 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07001018 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001019 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001020 }
1021
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001022 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +09001023 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1024 return;
1025 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001026 final boolean blocked;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001027 synchronized (mBlockedAppUids) {
1028 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001029 blocked = true;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001030 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001031 blocked = false;
1032 } else {
1033 return;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001034 }
1035 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001036 String action = blocked ? "BLOCKED" : "UNBLOCKED";
1037 log(String.format("Returning %s NetworkInfo to uid=%d", action, uid));
1038 mNetworkInfoBlockingLogs.log(action + " " + uid);
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001039 }
1040
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001041 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001042 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1043 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1044 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1045 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001046 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001047 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001048 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1049
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001050 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001051 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001053 if (mLockdownTracker != null) {
1054 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001055 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001056
1057 // TODO: apply metered state closer to NetworkAgentInfo
1058 final long token = Binder.clearCallingIdentity();
1059 try {
1060 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1061 } catch (RemoteException e) {
1062 } finally {
1063 Binder.restoreCallingIdentity(token);
1064 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001065 }
1066
1067 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001068 * Return NetworkInfo for the active (i.e., connected) network interface.
1069 * It is assumed that at most one network is active at a time. If more
1070 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001071 * @return the info for the active network, or {@code null} if none is
1072 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001073 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001074 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001076 enforceAccessPermission();
1077 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001078 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001079 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001080 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1081 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001082 }
1083
Paul Jensen31a94f42015-02-13 14:18:39 -05001084 @Override
1085 public Network getActiveNetwork() {
1086 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001087 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001088 }
1089
1090 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001091 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001092 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001093 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001094 }
1095
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001096 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001097 final int user = UserHandle.getUserId(uid);
1098 int vpnNetId = NETID_UNSET;
1099 synchronized (mVpns) {
1100 final Vpn vpn = mVpns.get(user);
1101 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1102 }
1103 NetworkAgentInfo nai;
1104 if (vpnNetId != NETID_UNSET) {
1105 synchronized (mNetworkForNetId) {
1106 nai = mNetworkForNetId.get(vpnNetId);
1107 }
1108 if (nai != null) return nai.network;
1109 }
1110 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001111 if (nai != null
1112 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1113 nai = null;
1114 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001115 return nai != null ? nai.network : null;
1116 }
1117
Lorenzo Colitti18660282016-07-04 12:55:44 +09001118 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001119 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1120 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001121 final int uid = Binder.getCallingUid();
1122 NetworkState state = getUnfilteredActiveNetworkState(uid);
1123 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001124 }
1125
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001126 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001127 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001128 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001129 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001130 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001131 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001132 }
1133
1134 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001135 public NetworkInfo getNetworkInfo(int networkType) {
1136 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001137 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001138 if (getVpnUnderlyingNetworks(uid) != null) {
1139 // A VPN is active, so we may need to return one of its underlying networks. This
1140 // information is not available in LegacyTypeTracker, so we have to get it from
1141 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001142 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001143 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001144 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001145 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001146 }
1147 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001148 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001149 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001150 }
1151
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001153 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001154 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001155 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001156 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001157 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001158 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001159 return state.networkInfo;
1160 } else {
1161 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001163 }
1164
1165 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001166 public NetworkInfo[] getAllNetworkInfo() {
1167 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001168 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001169 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1170 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001171 NetworkInfo info = getNetworkInfo(networkType);
1172 if (info != null) {
1173 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001174 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001176 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001177 }
1178
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001179 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001180 public Network getNetworkForType(int networkType) {
1181 enforceAccessPermission();
1182 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001183 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1184 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001185 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001186 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001188 }
1189
1190 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001191 public Network[] getAllNetworks() {
1192 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001193 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001194 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001195 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001196 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001197 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001198 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001199 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001200 }
1201
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001202 @Override
1203 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1204 // The basic principle is: if an app's traffic could possibly go over a
1205 // network, without the app doing anything multinetwork-specific,
1206 // (hence, by "default"), then include that network's capabilities in
1207 // the array.
1208 //
1209 // In the normal case, app traffic only goes over the system's default
1210 // network connection, so that's the only network returned.
1211 //
1212 // With a VPN in force, some app traffic may go into the VPN, and thus
1213 // over whatever underlying networks the VPN specifies, while other app
1214 // traffic may go over the system default network (e.g.: a split-tunnel
1215 // VPN, or an app disallowed by the VPN), so the set of networks
1216 // returned includes the VPN's underlying networks and the system
1217 // default.
1218 enforceAccessPermission();
1219
1220 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1221
1222 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001223 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001224 if (nc != null) {
1225 result.put(nai.network, nc);
1226 }
1227
1228 if (!mLockdownEnabled) {
1229 synchronized (mVpns) {
1230 Vpn vpn = mVpns.get(userId);
1231 if (vpn != null) {
1232 Network[] networks = vpn.getUnderlyingNetworks();
1233 if (networks != null) {
1234 for (Network network : networks) {
1235 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001236 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001237 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001238 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001239 }
1240 }
1241 }
1242 }
1243 }
1244 }
1245
1246 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1247 out = result.values().toArray(out);
1248 return out;
1249 }
1250
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001251 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001252 public boolean isNetworkSupported(int networkType) {
1253 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001254 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001255 }
1256
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001257 /**
1258 * Return LinkProperties for the active (i.e., connected) default
1259 * network interface. It is assumed that at most one default network
1260 * is active at a time. If more than one is active, it is indeterminate
1261 * which will be returned.
1262 * @return the ip properties for the active network, or {@code null} if
1263 * none is active
1264 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001265 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001266 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001267 enforceAccessPermission();
1268 final int uid = Binder.getCallingUid();
1269 NetworkState state = getUnfilteredActiveNetworkState(uid);
1270 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001271 }
1272
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001273 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001274 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001275 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001276 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1277 if (nai != null) {
1278 synchronized (nai) {
1279 return new LinkProperties(nai.linkProperties);
1280 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001281 }
1282 return null;
1283 }
1284
Robert Greenwalt12e67352014-05-13 21:41:06 -07001285 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001286 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001287 public LinkProperties getLinkProperties(Network network) {
1288 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001289 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1290 }
1291
1292 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1293 if (nai == null) {
1294 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001295 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001296 synchronized (nai) {
1297 return new LinkProperties(nai.linkProperties);
1298 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001299 }
1300
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001301 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001302 if (nai != null) {
1303 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001304 if (nai.networkCapabilities != null) {
1305 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001306 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001307 }
1308 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001309 return null;
1310 }
1311
1312 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001313 public NetworkCapabilities getNetworkCapabilities(Network network) {
1314 enforceAccessPermission();
1315 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1316 }
1317
1318 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001319 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001320 // Require internal since we're handing out IMSI details
1321 enforceConnectivityInternalPermission();
1322
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001323 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001324 for (Network network : getAllNetworks()) {
1325 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1326 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001327 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001328 }
1329 }
1330 return result.toArray(new NetworkState[result.size()]);
1331 }
1332
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001333 @Override
1334 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1335 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001336 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001337 final long token = Binder.clearCallingIdentity();
1338 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001339 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1340 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001341 try {
1342 return mPolicyManager.getNetworkQuotaInfo(state);
1343 } catch (RemoteException e) {
1344 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001345 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001346 return null;
1347 } finally {
1348 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001349 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001350 }
1351
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001352 @Override
1353 public boolean isActiveNetworkMetered() {
1354 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001355
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001356 final NetworkInfo info = getActiveNetworkInfo();
1357 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001358 }
1359
Jeff Sharkey216c1812012-08-05 14:29:23 -07001360 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1361 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001362 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001363 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001364 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001365 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001366 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001367
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001368 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 * Ensure that a network route exists to deliver traffic to the specified
1370 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001371 * @param networkType the type of the network over which traffic to the
1372 * specified host is to be routed
1373 * @param hostAddress the IP address of the host to which the route is
1374 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001375 * @return {@code true} on success, {@code false} on failure
1376 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001377 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001378 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001379 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001380 if (mProtectedNetworks.contains(networkType)) {
1381 enforceConnectivityInternalPermission();
1382 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001383
Chad Brubakerc0234532014-02-14 13:24:29 -08001384 InetAddress addr;
1385 try {
1386 addr = InetAddress.getByAddress(hostAddress);
1387 } catch (UnknownHostException e) {
1388 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1389 return false;
1390 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001391
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001392 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001393 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 return false;
1395 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001396
1397 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1398 if (nai == null) {
1399 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1400 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1401 } else {
1402 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1403 }
1404 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001405 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001406
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001407 DetailedState netState;
1408 synchronized (nai) {
1409 netState = nai.networkInfo.getDetailedState();
1410 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001411
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001412 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001413 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001414 log("requestRouteToHostAddress on down network "
1415 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001416 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001417 }
1418 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001420
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001421 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001422 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001423 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001424 LinkProperties lp;
1425 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001426 synchronized (nai) {
1427 lp = nai.linkProperties;
1428 netId = nai.network.netId;
1429 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001430 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001431 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1432 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001433 } finally {
1434 Binder.restoreCallingIdentity(token);
1435 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001436 }
1437
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001438 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001439 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001440 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001441 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001442 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001443 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001444 if (bestRoute.getGateway().equals(addr)) {
1445 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001446 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001447 } else {
1448 // if we will connect to this through another route, add a direct route
1449 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001450 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001451 }
1452 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001453 if (DBG) log("Adding legacy route " + bestRoute +
1454 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001455 try {
1456 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1457 } catch (Exception e) {
1458 // never crash - catch them all
1459 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001460 return false;
1461 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001462 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001463 }
1464
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001465 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001466 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001467 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001468 // TODO: notify UID when it has requested targeted updates
1469 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001470 @Override
1471 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001472 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001473 @Override
1474 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001475 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001476 if (restrictBackground) {
1477 log("onRestrictBackgroundChanged(true): disabling tethering");
1478 mTethering.untetherAll();
1479 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001480 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001481 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001482 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001483 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001484 };
1485
Robin Lee3b3dd942015-05-12 18:14:58 +01001486 /**
1487 * Require that the caller is either in the same user or has appropriate permission to interact
1488 * across users.
1489 *
1490 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1491 */
1492 private void enforceCrossUserPermission(int userId) {
1493 if (userId == UserHandle.getCallingUserId()) {
1494 // Not a cross-user call.
1495 return;
1496 }
1497 mContext.enforceCallingOrSelfPermission(
1498 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1499 "ConnectivityService");
1500 }
1501
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001502 private void enforceInternetPermission() {
1503 mContext.enforceCallingOrSelfPermission(
1504 android.Manifest.permission.INTERNET,
1505 "ConnectivityService");
1506 }
1507
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001508 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001509 mContext.enforceCallingOrSelfPermission(
1510 android.Manifest.permission.ACCESS_NETWORK_STATE,
1511 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 }
1513
1514 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001515 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001516 }
1517
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001518 private void enforceTetherAccessPermission() {
1519 mContext.enforceCallingOrSelfPermission(
1520 android.Manifest.permission.ACCESS_NETWORK_STATE,
1521 "ConnectivityService");
1522 }
1523
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001524 private void enforceConnectivityInternalPermission() {
1525 mContext.enforceCallingOrSelfPermission(
1526 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1527 "ConnectivityService");
1528 }
1529
Hugo Benichi514da602016-07-19 15:59:27 +09001530 private void enforceConnectivityRestrictedNetworksPermission() {
1531 try {
1532 mContext.enforceCallingOrSelfPermission(
1533 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1534 "ConnectivityService");
1535 return;
1536 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1537 enforceConnectivityInternalPermission();
1538 }
1539
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001540 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001541 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001542 }
1543
Lorenzo Colitti18660282016-07-04 12:55:44 +09001544 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001545 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001546 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001547 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001548 }
1549
1550 private void sendInetConditionBroadcast(NetworkInfo info) {
1551 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1552 }
1553
Wink Saville628b0852011-08-04 15:01:58 -07001554 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001555 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001556 info = new NetworkInfo(info);
1557 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001558 }
1559
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001560 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001561 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001562 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001563 if (info.isFailover()) {
1564 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1565 info.setFailover(false);
1566 }
1567 if (info.getReason() != null) {
1568 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1569 }
1570 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001571 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1572 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001573 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001574 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001575 return intent;
1576 }
1577
1578 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1579 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1580 }
1581
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001582 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001583 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1584 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1585 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001586 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001587 final long ident = Binder.clearCallingIdentity();
1588 try {
1589 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1590 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1591 } finally {
1592 Binder.restoreCallingIdentity(ident);
1593 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001594 }
1595
Mike Lockwood0f79b542009-08-14 14:18:49 -04001596 private void sendStickyBroadcast(Intent intent) {
Hugo Benichi20035e02017-04-26 14:53:28 +09001597 synchronized (this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001598 if (!mSystemReady) {
1599 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001600 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001601 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001602 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001603 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001604 }
1605
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001606 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001607 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001608 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001609 final NetworkInfo ni = intent.getParcelableExtra(
1610 ConnectivityManager.EXTRA_NETWORK_INFO);
1611 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1612 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1613 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001614 } else {
1615 BroadcastOptions opts = BroadcastOptions.makeBasic();
1616 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1617 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001618 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001619 final IBatteryStats bs = BatteryStatsService.getService();
1620 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001621 bs.noteConnectivityChanged(intent.getIntExtra(
1622 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1623 ni != null ? ni.getState().toString() : "?");
1624 } catch (RemoteException e) {
1625 }
1626 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001627 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001628 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001629 } finally {
1630 Binder.restoreCallingIdentity(ident);
1631 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001632 }
1633 }
1634
1635 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001636 loadGlobalProxy();
1637
Hugo Benichi20035e02017-04-26 14:53:28 +09001638 synchronized (this) {
Mike Lockwood0f79b542009-08-14 14:18:49 -04001639 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001640 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001641 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001642 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001643 }
1644 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001645 // load the global proxy at startup
1646 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001647
Robin Lee244ce8e2016-01-05 18:03:46 +00001648 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1649 // for user to unlock device too.
1650 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001651
Erik Klineda4bfa82015-04-30 12:58:40 +09001652 // Configure whether mobile data is always on.
1653 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1654
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001655 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001656
1657 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001658 }
1659
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001660 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001661 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001662 *
1663 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001664 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001665 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001666 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1667 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001668
1669 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001670 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001671
Robert Greenwalt7b816022014-04-18 15:25:25 -07001672 if (networkAgent.networkCapabilities.hasTransport(
1673 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001674 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1675 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001676 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001677 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001678 } else if (networkAgent.networkCapabilities.hasTransport(
1679 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001680 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1681 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001682 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001683 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001684 } else {
1685 // do not track any other networks
1686 timeout = 0;
1687 }
1688
Robert Greenwalt7b816022014-04-18 15:25:25 -07001689 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001690 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001691 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001692 } catch (Exception e) {
1693 // You shall not crash!
1694 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001695 }
1696 }
1697 }
1698
1699 /**
1700 * Remove data activity tracking when network disconnects.
1701 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001702 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1703 final String iface = networkAgent.linkProperties.getInterfaceName();
1704 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001705
Robert Greenwalt7b816022014-04-18 15:25:25 -07001706 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1707 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001708 try {
1709 // the call fails silently if no idletimer setup for this interface
1710 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001711 } catch (Exception e) {
1712 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001713 }
1714 }
1715 }
1716
1717 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001718 * Reads the network specific MTU size from reources.
1719 * and set it on it's iface.
1720 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001721 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1722 final String iface = newLp.getInterfaceName();
1723 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001724 if (oldLp == null && mtu == 0) {
1725 // Silently ignore unset MTU value.
1726 return;
1727 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001728 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1729 if (VDBG) log("identical MTU - not setting");
1730 return;
1731 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001732 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001733 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001734 return;
1735 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001736
w1997615afd812014-08-05 15:18:11 -07001737 // Cannot set MTU without interface name
1738 if (TextUtils.isEmpty(iface)) {
1739 loge("Setting MTU size with null iface.");
1740 return;
1741 }
1742
Robert Greenwalt7b816022014-04-18 15:25:25 -07001743 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001744 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001745 mNetd.setMtu(iface, mtu);
1746 } catch (Exception e) {
1747 Slog.e(TAG, "exception in setMtu()" + e);
1748 }
1749 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001750
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001751 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001752 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1753
1754 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001755 @VisibleForTesting
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001756 protected MockableSystemProperties getSystemProperties() {
1757 return new MockableSystemProperties();
Paul Jensend7b6ca92015-05-13 14:05:12 -04001758 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001759
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001760 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1761 if (isDefaultNetwork(nai) == false) {
1762 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001763 }
1764
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001765 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1766 String[] values = null;
1767 if (tcpBufferSizes != null) {
1768 values = tcpBufferSizes.split(",");
1769 }
1770
1771 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001772 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001773 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1774 values = tcpBufferSizes.split(",");
1775 }
1776
1777 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1778
1779 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001780 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001781
1782 final String prefix = "/sys/kernel/ipv4/tcp_";
1783 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1784 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1785 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1786 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1787 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1788 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1789 mCurrentTcpBufferSizes = tcpBufferSizes;
1790 } catch (IOException e) {
1791 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001792 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001793
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001794 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001795 Settings.Global.TCP_DEFAULT_INIT_RWND,
1796 mSystemProperties.getInt("net.tcp.default_init_rwnd", 0));
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001797 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1798 if (rwndValue != 0) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001799 mSystemProperties.set(sysctlKey, rwndValue.toString());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001800 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001801 }
1802
Mattias Falk8b47b362011-08-23 14:15:13 +02001803 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001804 /*
1805 * Tell the VMs to toss their DNS caches
1806 */
1807 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1808 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001809 /*
1810 * Connectivity events can happen before boot has completed ...
1811 */
1812 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001813 final long ident = Binder.clearCallingIdentity();
1814 try {
1815 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1816 } finally {
1817 Binder.restoreCallingIdentity(ident);
1818 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001819 }
1820
Robert Greenwalt562cc542014-05-15 18:07:26 -07001821 @Override
1822 public int getRestoreDefaultNetworkDelay(int networkType) {
Lorenzo Colitti42cdf572017-03-21 18:54:11 +09001823 String restoreDefaultNetworkDelayStr = mSystemProperties.get(
Robert Greenwalt42acef32009-08-12 16:08:25 -07001824 NETWORK_RESTORE_DELAY_PROP_NAME);
1825 if(restoreDefaultNetworkDelayStr != null &&
1826 restoreDefaultNetworkDelayStr.length() != 0) {
1827 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001828 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001829 } catch (NumberFormatException e) {
1830 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001831 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001832 // if the system property isn't set, use the value for the apn type
1833 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1834
1835 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1836 (mNetConfigs[networkType] != null)) {
1837 ret = mNetConfigs[networkType].restoreTime;
1838 }
1839 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001840 }
1841
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001842 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001843 for (String arg : args) {
Erik Klineee363c42017-05-29 09:11:03 +09001844 if (target.equals(arg)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001845 }
1846 return false;
1847 }
1848
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001849 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1850 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1851 final long DIAG_TIME_MS = 5000;
1852 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1853 // Start gathering diagnostic information.
1854 netDiags.add(new NetworkDiagnostics(
1855 nai.network,
1856 new LinkProperties(nai.linkProperties), // Must be a copy.
1857 DIAG_TIME_MS));
1858 }
1859
1860 for (NetworkDiagnostics netDiag : netDiags) {
1861 pw.println();
1862 netDiag.waitForMeasurements();
1863 netDiag.dump(pw);
1864 }
1865 }
1866
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001867 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001868 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1869 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001870 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001871
Erik Kline7747fd42017-05-12 16:52:48 +09001872 if (argsContain(args, DIAG_ARG)) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001873 dumpNetworkDiagnostics(pw);
1874 return;
Erik Klineee363c42017-05-29 09:11:03 +09001875 } else if (argsContain(args, TETHERING_ARG)) {
1876 mTethering.dump(fd, pw, args);
1877 return;
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001878 }
Erik Kline379747a2015-06-05 17:47:34 +09001879
Lorenzo Colittie3805462015-06-03 11:18:24 +09001880 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001881 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001882 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001883 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001884 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001885 pw.println();
1886
Paul Jensen85cf78e2015-06-25 13:25:07 -04001887 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001888 pw.print("Active default network: ");
1889 if (defaultNai == null) {
1890 pw.println("none");
1891 } else {
1892 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001893 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001894 pw.println();
1895
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001896 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001897 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001898 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1899 pw.println(nai.toString());
1900 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001901 pw.println(String.format(
1902 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1903 nai.numForegroundNetworkRequests(),
1904 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1905 nai.numBackgroundNetworkRequests(),
1906 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001907 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001908 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1909 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001910 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001911 pw.decreaseIndent();
1912 pw.println("Lingered:");
1913 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001914 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001915 pw.decreaseIndent();
1916 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001917 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001918 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001919 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001920
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001921 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001922 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001923 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1924 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001925 }
1926 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001927 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001928
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001929 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001930
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001931 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001932 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001933
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001934 pw.println();
1935 mKeepaliveTracker.dump(pw);
1936
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001937 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001938 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001939
Erik Kline7747fd42017-05-12 16:52:48 +09001940 if (argsContain(args, SHORT_ARG) == false) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001941 pw.println();
1942 synchronized (mValidationLogs) {
1943 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001944 for (ValidationLog p : mValidationLogs) {
1945 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001946 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001947 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001948 pw.decreaseIndent();
1949 }
1950 }
Erik Kline7523eb32015-07-09 18:24:03 +09001951
1952 pw.println();
1953 pw.println("mNetworkRequestInfoLogs (most recent first):");
1954 pw.increaseIndent();
1955 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1956 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001957
1958 pw.println();
1959 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1960 pw.increaseIndent();
1961 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1962 pw.decreaseIndent();
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001963
1964 pw.println();
1965 pw.println("NetTransition WakeLock activity (most recent first):");
1966 pw.increaseIndent();
Hugo Benichic3318aa2017-09-05 13:25:07 +09001967 pw.println("total acquisitions: " + mTotalWakelockAcquisitions);
1968 pw.println("total releases: " + mTotalWakelockReleases);
1969 pw.println("cumulative duration: " + (mTotalWakelockDurationMs / 1000) + "s");
1970 pw.println("longest duration: " + (mMaxWakelockDurationMs / 1000) + "s");
1971 if (mTotalWakelockAcquisitions > mTotalWakelockReleases) {
1972 long duration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
1973 pw.println("currently holding WakeLock for: " + (duration / 1000) + "s");
1974 }
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001975 mWakelockLogs.reverseDump(fd, pw, args);
1976 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001977 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001978 }
1979
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001980 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001981 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001982 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001983 if (officialNai != null && officialNai.equals(nai)) return true;
1984 if (officialNai != null || VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09001985 loge(eventName(what) + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001986 " - " + nai);
1987 }
1988 return false;
1989 }
1990
Robert Greenwalt42acef32009-08-12 16:08:25 -07001991 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001992 private class NetworkStateTrackerHandler extends Handler {
1993 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001994 super(looper);
1995 }
1996
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001997 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001998 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001999 default:
2000 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07002001 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002002 handleAsyncChannelHalfConnect(msg);
2003 break;
2004 }
2005 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
2006 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2007 if (nai != null) nai.asyncChannel.disconnect();
2008 break;
2009 }
2010 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
2011 handleAsyncChannelDisconnected(msg);
2012 break;
2013 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002014 }
2015 return true;
2016 }
2017
2018 private void maybeHandleNetworkAgentMessage(Message msg) {
2019 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2020 if (nai == null) {
2021 if (VDBG) {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09002022 log(String.format("%s from unknown NetworkAgent", eventName(msg.what)));
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002023 }
2024 return;
2025 }
2026
2027 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002028 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002029 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2030 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002031 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2032 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002033 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002034 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002035 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002036 break;
2037 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002038 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Hugo Benichief502882017-09-01 01:23:32 +00002039 handleUpdateLinkProperties(nai, (LinkProperties) msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002040 break;
2041 }
2042 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002043 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002044 updateNetworkInfo(nai, info);
2045 break;
2046 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002047 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002048 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002049 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002050 break;
2051 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002052 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002053 try {
2054 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002055 } catch (Exception e) {
2056 // Never crash!
2057 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002058 }
2059 break;
2060 }
2061 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002062 try {
2063 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002064 } catch (Exception e) {
2065 // Never crash!
2066 loge("Exception in removeVpnUidRanges: " + e);
2067 }
2068 break;
2069 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002070 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002071 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2072 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002073 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002074 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002075 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002076 break;
2077 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002078 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002079 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2080 break;
2081 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002082 }
2083 }
2084
2085 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2086 switch (msg.what) {
2087 default:
2088 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002089 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002090 final NetworkAgentInfo nai;
2091 synchronized (mNetworkForNetId) {
2092 nai = mNetworkForNetId.get(msg.arg2);
2093 }
2094 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002095 final boolean valid =
2096 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002097 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002098 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2099 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002100 if (valid != nai.lastValidated) {
2101 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002102 nai.lastValidated = valid;
2103 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002104 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002105 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2106 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002107 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002108 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002109 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002110 Bundle redirectUrlBundle = new Bundle();
2111 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002112 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002113 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002114 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002115 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002116 if (wasValidated && !nai.lastValidated) {
2117 handleNetworkUnvalidated(nai);
2118 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002119 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002120 break;
2121 }
Paul Jensen869868be2014-05-15 10:33:05 -04002122 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002123 final int netId = msg.arg2;
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002124 final boolean visible = toBool(msg.arg1);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002125 final NetworkAgentInfo nai;
2126 synchronized (mNetworkForNetId) {
2127 nai = mNetworkForNetId.get(netId);
2128 }
Calvin Onbe96da12016-10-11 15:10:46 -07002129 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002130 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002131 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002132 nai.lastCaptivePortalDetected = visible;
2133 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002134 if (nai.lastCaptivePortalDetected &&
2135 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2136 if (DBG) log("Avoiding captive portal network: " + nai.name());
2137 nai.asyncChannel.sendMessage(
2138 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2139 teardownUnneededNetwork(nai);
2140 break;
2141 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002142 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002143 }
2144 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002145 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002146 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002147 if (nai == null) {
2148 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2149 break;
2150 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002151 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002152 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002153 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002154 }
Paul Jensen869868be2014-05-15 10:33:05 -04002155 }
Paul Jensen869868be2014-05-15 10:33:05 -04002156 break;
2157 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002158 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002159 return true;
2160 }
2161
Calvin Onbe96da12016-10-11 15:10:46 -07002162 private int getCaptivePortalMode() {
2163 return Settings.Global.getInt(mContext.getContentResolver(),
2164 Settings.Global.CAPTIVE_PORTAL_MODE,
2165 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2166 }
2167
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002168 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2169 switch (msg.what) {
2170 default:
2171 return false;
2172 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2173 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2174 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2175 handleLingerComplete(nai);
2176 }
2177 break;
2178 }
2179 }
2180 return true;
2181 }
2182
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002183 @Override
2184 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002185 if (!maybeHandleAsyncChannelMessage(msg) &&
2186 !maybeHandleNetworkMonitorMessage(msg) &&
2187 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002188 maybeHandleNetworkAgentMessage(msg);
2189 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002190 }
2191 }
2192
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002193 private void updateLingerState(NetworkAgentInfo nai, long now) {
2194 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2195 // 2. If the network was lingering and there are now requests, unlinger it.
2196 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2197 // one lingered request, start lingering.
2198 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002199 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002200 if (DBG) log("Unlingering " + nai.name());
2201 nai.unlinger();
2202 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002203 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002204 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002205 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002206 nai.linger();
2207 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2208 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2209 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002210 }
2211
Robert Greenwalt7b816022014-04-18 15:25:25 -07002212 private void handleAsyncChannelHalfConnect(Message msg) {
2213 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002214 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002215 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2216 if (VDBG) log("NetworkFactory connected");
2217 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002218 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002219 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002220 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002221 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002222 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002223 }
2224 } else {
2225 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002226 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002227 }
2228 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2229 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2230 if (VDBG) log("NetworkAgent connected");
2231 // A network agent has requested a connection. Establish the connection.
2232 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2233 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2234 } else {
2235 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002236 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002237 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002238 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002239 synchronized (mNetworkForNetId) {
2240 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002241 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002242 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002243 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002244 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002245 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002246 }
2247 }
2248 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002249
Robert Greenwalt7b816022014-04-18 15:25:25 -07002250 private void handleAsyncChannelDisconnected(Message msg) {
2251 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2252 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002253 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002254 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002255 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002256 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002257 // TODO - if we move the logic to the network agent (have them disconnect
2258 // because they lost all their requests or because their score isn't good)
2259 // then they would disconnect organically, report their new state and then
2260 // disconnect the channel.
2261 if (nai.networkInfo.isConnected()) {
2262 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2263 null, null);
2264 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002265 final boolean wasDefault = isDefaultNetwork(nai);
2266 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002267 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002268 // Log default network disconnection before required book-keeping.
2269 // Let rematchAllNetworksAndRequests() below record a new default network event
2270 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2271 // whose timestamps tell how long it takes to recover a default network.
2272 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002273 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002274 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002275 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2276 // by other networks that are already connected. Perhaps that can be done by
2277 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2278 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002279 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002280 mKeepaliveTracker.handleStopAllKeepalives(nai,
2281 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Joel Scherpelz668370b2017-06-08 15:35:21 +09002282 for (String iface : nai.linkProperties.getAllInterfaceNames()) {
2283 // Disable wakeup packet monitoring for each interface.
2284 wakeupModifyInterface(iface, nai.networkCapabilities, false);
2285 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002286 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002287 mNetworkAgentInfos.remove(msg.replyTo);
Hugo Benichief502882017-09-01 01:23:32 +00002288 nai.maybeStopClat();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002289 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002290 // Remove the NetworkAgent, but don't mark the netId as
2291 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002292 mNetworkForNetId.remove(nai.network.netId);
2293 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002294 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002295 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2296 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002297 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2298 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2299 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002300 sendUpdatedScoreToFactories(request, 0);
2301 }
2302 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002303 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002304 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002305 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002306 notifyLockdownVpn(nai);
Hugo Benichi4c31b342017-03-30 23:18:10 +09002307 ensureNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002308 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002309 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002310 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002311 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002312 if (nai.created) {
2313 // Tell netd to clean up the configuration for this network
2314 // (routing rules, DNS, etc).
2315 // This may be slow as it requires a lot of netd shelling out to ip and
2316 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2317 // after we've rematched networks with requests which should make a potential
2318 // fallback network the default or requested a new network from the
2319 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2320 // long time.
2321 try {
2322 mNetd.removeNetwork(nai.network.netId);
2323 } catch (Exception e) {
2324 loge("Exception removing network: " + e);
2325 }
2326 }
2327 synchronized (mNetworkForNetId) {
2328 mNetIdInUse.delete(nai.network.netId);
2329 }
2330 } else {
2331 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2332 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002333 }
2334 }
2335
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002336 // If this method proves to be too slow then we can maintain a separate
2337 // pendingIntent => NetworkRequestInfo map.
2338 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2339 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2340 Intent intent = pendingIntent.getIntent();
2341 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2342 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2343 if (existingPendingIntent != null &&
2344 existingPendingIntent.getIntent().filterEquals(intent)) {
2345 return entry.getValue();
2346 }
2347 }
2348 return null;
2349 }
2350
2351 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2352 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2353
2354 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2355 if (existingRequest != null) { // remove the existing request.
2356 if (DBG) log("Replacing " + existingRequest.request + " with "
2357 + nri.request + " because their intents matched.");
2358 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2359 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002360 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002361 }
2362
Erik Klineda4bfa82015-04-30 12:58:40 +09002363 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002364 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002365 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002366 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002367 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002368 if (nri.request.networkCapabilities.hasSignalStrength() &&
2369 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2370 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002371 }
2372 }
2373 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002374 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002375 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002376 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002377 }
2378 }
2379
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002380 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2381 int callingUid) {
2382 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2383 if (nri != null) {
2384 handleReleaseNetworkRequest(nri.request, callingUid);
2385 }
2386 }
2387
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002388 // Determines whether the network is the best (or could become the best, if it validated), for
2389 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2390 // on the value of reason:
2391 //
2392 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2393 // then it should be torn down.
2394 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2395 // then it should be lingered.
2396 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2397 final int numRequests;
2398 switch (reason) {
2399 case TEARDOWN:
2400 numRequests = nai.numRequestNetworkRequests();
2401 break;
2402 case LINGER:
2403 numRequests = nai.numForegroundNetworkRequests();
2404 break;
2405 default:
2406 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2407 return true;
2408 }
2409
2410 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002411 return false;
2412 }
Paul Jensene0988542015-06-25 15:30:08 -04002413 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002414 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2415 // Background requests don't affect lingering.
2416 continue;
2417 }
2418
Paul Jensene0988542015-06-25 15:30:08 -04002419 // If this Network is already the highest scoring Network for a request, or if
2420 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002421 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002422 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002423 // Note that this catches two important cases:
2424 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2425 // is currently satisfying the request. This is desirable when
2426 // cellular ends up validating but WiFi does not.
2427 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002428 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002429 // WiFi ends up validating and out scoring cellular.
2430 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2431 nai.getCurrentScoreAsValidated())) {
2432 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002433 }
2434 }
Paul Jensene0988542015-06-25 15:30:08 -04002435 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002436 }
2437
Erik Klineacdd6392016-07-07 16:50:58 +09002438 private NetworkRequestInfo getNriForAppRequest(
2439 NetworkRequest request, int callingUid, String requestedOperation) {
2440 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2441
Robert Greenwalt9258c642014-03-26 16:47:06 -07002442 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002443 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002444 log(String.format("UID %d attempted to %s for unowned request %s",
2445 callingUid, requestedOperation, nri));
2446 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002447 }
Erik Klineacdd6392016-07-07 16:50:58 +09002448 }
2449
2450 return nri;
2451 }
2452
Erik Kline57faba92015-11-25 12:49:38 +09002453 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002454 if (mNetworkRequests.get(nri.request) == null) {
2455 return;
Erik Kline57faba92015-11-25 12:49:38 +09002456 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002457 if (mNetworkForRequestId.get(nri.request.requestId) != null) {
2458 return;
2459 }
2460 if (VDBG || (DBG && nri.request.isRequest())) {
2461 log("releasing " + nri.request + " (timeout)");
2462 }
2463 handleRemoveNetworkRequest(nri);
2464 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_UNAVAIL, 0);
Erik Kline57faba92015-11-25 12:49:38 +09002465 }
2466
Erik Klineacdd6392016-07-07 16:50:58 +09002467 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
Hugo Benichidba33db2017-03-23 22:40:44 +09002468 final NetworkRequestInfo nri =
2469 getNriForAppRequest(request, callingUid, "release NetworkRequest");
2470 if (nri == null) {
2471 return;
Erik Kline57faba92015-11-25 12:49:38 +09002472 }
Hugo Benichidba33db2017-03-23 22:40:44 +09002473 if (VDBG || (DBG && nri.request.isRequest())) {
2474 log("releasing " + nri.request + " (release request)");
2475 }
2476 handleRemoveNetworkRequest(nri);
Erik Kline57faba92015-11-25 12:49:38 +09002477 }
Erik Klineacdd6392016-07-07 16:50:58 +09002478
Hugo Benichidba33db2017-03-23 22:40:44 +09002479 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri) {
Erik Klineacdd6392016-07-07 16:50:58 +09002480 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002481 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002482 synchronized (mUidToNetworkRequestCount) {
2483 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2484 if (requests < 1) {
2485 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2486 nri.mUid);
2487 } else if (requests == 1) {
2488 mUidToNetworkRequestCount.removeAt(
2489 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2490 } else {
2491 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2492 }
2493 }
2494 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2495 if (nri.request.isRequest()) {
2496 boolean wasKept = false;
2497 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2498 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002499 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002500 nai.removeRequest(nri.request.requestId);
2501 if (VDBG) {
2502 log(" Removing from current network " + nai.name() +
2503 ", leaving " + nai.numNetworkRequests() + " requests.");
2504 }
2505 // If there are still lingered requests on this network, don't tear it down,
2506 // but resume lingering instead.
2507 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002508 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002509 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2510 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002511 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002512 wasKept = true;
2513 }
2514 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002515 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2516 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002517 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002518 }
Erik Klineacdd6392016-07-07 16:50:58 +09002519 }
2520
2521 // TODO: remove this code once we know that the Slog.wtf is never hit.
2522 //
2523 // Find all networks that are satisfying this request and remove the request
2524 // from their request lists.
2525 // TODO - it's my understanding that for a request there is only a single
2526 // network satisfying it, so this loop is wasteful
2527 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2528 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2529 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2530 otherNai.name() + ", but mNetworkAgentInfos says " +
2531 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002532 }
2533 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002534
Erik Klineacdd6392016-07-07 16:50:58 +09002535 // Maintain the illusion. When this request arrived, we might have pretended
2536 // that a network connected to serve it, even though the network was already
2537 // connected. Now that this request has gone away, we might have to pretend
2538 // that the network disconnected. LegacyTypeTracker will generate that
2539 // phantom disconnect for this type.
2540 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2541 boolean doRemove = true;
2542 if (wasKept) {
2543 // check if any of the remaining requests for this network are for the
2544 // same legacy type - if so, don't remove the nai
2545 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2546 NetworkRequest otherRequest = nai.requestAt(i);
2547 if (otherRequest.legacyType == nri.request.legacyType &&
2548 otherRequest.isRequest()) {
2549 if (DBG) log(" still have other legacy request - leaving");
2550 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002551 }
2552 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002553 }
2554
Erik Klineacdd6392016-07-07 16:50:58 +09002555 if (doRemove) {
2556 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002557 }
2558 }
Erik Klineacdd6392016-07-07 16:50:58 +09002559
2560 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2561 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2562 nri.request);
2563 }
2564 } else {
2565 // listens don't have a singular affectedNetwork. Check all networks to see
2566 // if this listen request applies and remove it.
2567 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2568 nai.removeRequest(nri.request.requestId);
2569 if (nri.request.networkCapabilities.hasSignalStrength() &&
2570 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2571 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2572 }
2573 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002574 }
2575 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002576
Lorenzo Colitti18660282016-07-04 12:55:44 +09002577 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002578 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2579 enforceConnectivityInternalPermission();
2580 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002581 encodeBool(accept), encodeBool(always), network));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002582 }
2583
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002584 @Override
2585 public void setAvoidUnvalidated(Network network) {
2586 enforceConnectivityInternalPermission();
2587 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2588 }
2589
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002590 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2591 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2592 " accept=" + accept + " always=" + always);
2593
2594 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2595 if (nai == null) {
2596 // Nothing to do.
2597 return;
2598 }
2599
2600 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002601 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002602 return;
2603 }
2604
2605 if (!nai.networkMisc.explicitlySelected) {
2606 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2607 }
2608
2609 if (accept != nai.networkMisc.acceptUnvalidated) {
2610 int oldScore = nai.getCurrentScore();
2611 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002612 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002613 sendUpdatedScoreToFactories(nai);
2614 }
2615
2616 if (always) {
2617 nai.asyncChannel.sendMessage(
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002618 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, encodeBool(accept));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002619 }
2620
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002621 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002622 // Tell the NetworkAgent to not automatically reconnect to the network.
2623 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2624 // Teardown the nework.
2625 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002626 }
2627
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002628 }
2629
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002630 private void handleSetAvoidUnvalidated(Network network) {
2631 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2632 if (nai == null || nai.lastValidated) {
2633 // Nothing to do. The network either disconnected or revalidated.
2634 return;
2635 }
2636 if (!nai.avoidUnvalidated) {
2637 int oldScore = nai.getCurrentScore();
2638 nai.avoidUnvalidated = true;
2639 rematchAllNetworksAndRequests(nai, oldScore);
2640 sendUpdatedScoreToFactories(nai);
2641 }
2642 }
2643
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002644 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002645 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002646 mHandler.sendMessageDelayed(
2647 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2648 PROMPT_UNVALIDATED_DELAY_MS);
2649 }
2650
Lorenzo Colitti4734cdb2017-04-27 14:30:21 +09002651 @Override
2652 public void startCaptivePortalApp(Network network) {
2653 enforceConnectivityInternalPermission();
2654 mHandler.post(() -> {
2655 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2656 if (nai == null) return;
2657 if (!nai.networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL)) return;
2658 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_LAUNCH_CAPTIVE_PORTAL_APP);
2659 });
2660 }
2661
Hugo Benichic8e9e122016-09-14 23:23:08 +00002662 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002663 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002664 }
2665
Erik Kline065ab6e2016-10-02 18:02:14 +09002666 private void rematchForAvoidBadWifiUpdate() {
2667 rematchAllNetworksAndRequests(null, 0);
2668 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2669 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2670 sendUpdatedScoreToFactories(nai);
2671 }
2672 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002673 }
2674
Erik Kline065ab6e2016-10-02 18:02:14 +09002675 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002676 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002677 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002678 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002679 if (!configRestrict) {
2680 pw.println("Bad Wi-Fi avoidance: unrestricted");
2681 return;
2682 }
2683
2684 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2685 pw.increaseIndent();
2686 pw.println("Config restrict: " + configRestrict);
2687
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002688 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002689 String description;
2690 // Can't use a switch statement because strings are legal case labels, but null is not.
2691 if ("0".equals(value)) {
2692 description = "get stuck";
2693 } else if (value == null) {
2694 description = "prompt";
2695 } else if ("1".equals(value)) {
2696 description = "avoid";
2697 } else {
2698 description = value + " (?)";
2699 }
2700 pw.println("User setting: " + description);
2701 pw.println("Network overrides:");
2702 pw.increaseIndent();
2703 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2704 if (nai.avoidUnvalidated) {
2705 pw.println(nai.name());
2706 }
2707 }
2708 pw.decreaseIndent();
2709 pw.decreaseIndent();
2710 }
2711
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002712 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2713 final String action;
2714 switch (type) {
2715 case NO_INTERNET:
2716 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2717 break;
2718 case LOST_INTERNET:
2719 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2720 break;
2721 default:
2722 Slog.wtf(TAG, "Unknown notification type " + type);
2723 return;
2724 }
2725
2726 Intent intent = new Intent(action);
2727 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2728 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2729 intent.setClassName("com.android.settings",
2730 "com.android.settings.wifi.WifiNoInternetDialog");
2731
2732 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2733 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2734 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2735 }
2736
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002737 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002738 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002739 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2740
2741 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2742 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002743 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002744 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002745 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2746 return;
2747 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002748 showValidationNotification(nai, NotificationType.NO_INTERNET);
2749 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002750
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002751 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2752 NetworkCapabilities nc = nai.networkCapabilities;
2753 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002754
Erik Kline065ab6e2016-10-02 18:02:14 +09002755 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002756 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002757 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2758 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002759 }
2760
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002761 @Override
2762 public int getMultipathPreference(Network network) {
2763 enforceAccessPermission();
2764
2765 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2766 if (nai != null && !nai.networkInfo.isMetered()) {
2767 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2768 }
2769
2770 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2771 }
2772
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002773 private class InternalHandler extends Handler {
2774 public InternalHandler(Looper looper) {
2775 super(looper);
2776 }
2777
2778 @Override
2779 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002780 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002781 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002782 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Hugo Benichi4c31b342017-03-30 23:18:10 +09002783 handleReleaseNetworkTransitionWakelock(msg.what);
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002784 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002785 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002786 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002787 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002788 break;
2789 }
Jason Monkdecd2952013-10-10 14:02:51 -04002790 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002791 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002792 break;
2793 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002794 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002795 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2796 break;
2797 }
2798 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2799 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002800 break;
2801 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002802 case EVENT_REGISTER_NETWORK_AGENT: {
2803 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2804 break;
2805 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002806 case EVENT_REGISTER_NETWORK_REQUEST:
2807 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002808 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002809 break;
2810 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002811 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2812 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002813 handleRegisterNetworkRequestWithIntent(msg);
2814 break;
2815 }
Erik Kline57faba92015-11-25 12:49:38 +09002816 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2817 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2818 handleTimedOutNetworkRequest(nri);
2819 break;
2820 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002821 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2822 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2823 break;
2824 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002825 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002826 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002827 break;
2828 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002829 case EVENT_SET_ACCEPT_UNVALIDATED: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002830 Network network = (Network) msg.obj;
2831 handleSetAcceptUnvalidated(network, toBool(msg.arg1), toBool(msg.arg2));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002832 break;
2833 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002834 case EVENT_SET_AVOID_UNVALIDATED: {
2835 handleSetAvoidUnvalidated((Network) msg.obj);
2836 break;
2837 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002838 case EVENT_PROMPT_UNVALIDATED: {
2839 handlePromptUnvalidated((Network) msg.obj);
2840 break;
2841 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002842 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2843 handleMobileDataAlwaysOn();
2844 break;
2845 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002846 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2847 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2848 mKeepaliveTracker.handleStartKeepalive(msg);
2849 break;
2850 }
2851 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2852 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2853 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2854 int slot = msg.arg1;
2855 int reason = msg.arg2;
2856 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2857 break;
2858 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002859 case EVENT_SYSTEM_READY: {
2860 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2861 nai.networkMonitor.systemReady = true;
2862 }
2863 break;
2864 }
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002865 case EVENT_REVALIDATE_NETWORK: {
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002866 handleReportNetworkConnectivity((Network) msg.obj, msg.arg1, toBool(msg.arg2));
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09002867 break;
2868 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002869 }
2870 }
2871 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002872
2873 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002874 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002875 public int tether(String iface, String callerPkg) {
2876 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002877 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002878 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002879 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002880 } else {
2881 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2882 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002883 }
2884
2885 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002886 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002887 public int untether(String iface, String callerPkg) {
2888 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002889
2890 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002891 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002892 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002893 } else {
2894 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2895 }
2896 }
2897
2898 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002899 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002900 public int getLastTetherError(String iface) {
2901 enforceTetherAccessPermission();
2902
2903 if (isTetheringSupported()) {
2904 return mTethering.getLastTetherError(iface);
2905 } else {
2906 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2907 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002908 }
2909
2910 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002911 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002912 public String[] getTetherableUsbRegexs() {
2913 enforceTetherAccessPermission();
2914 if (isTetheringSupported()) {
2915 return mTethering.getTetherableUsbRegexs();
2916 } else {
2917 return new String[0];
2918 }
2919 }
2920
Lorenzo Colitti18660282016-07-04 12:55:44 +09002921 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002922 public String[] getTetherableWifiRegexs() {
2923 enforceTetherAccessPermission();
2924 if (isTetheringSupported()) {
2925 return mTethering.getTetherableWifiRegexs();
2926 } else {
2927 return new String[0];
2928 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002929 }
2930
Lorenzo Colitti18660282016-07-04 12:55:44 +09002931 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002932 public String[] getTetherableBluetoothRegexs() {
2933 enforceTetherAccessPermission();
2934 if (isTetheringSupported()) {
2935 return mTethering.getTetherableBluetoothRegexs();
2936 } else {
2937 return new String[0];
2938 }
2939 }
2940
Lorenzo Colitti18660282016-07-04 12:55:44 +09002941 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09002942 public int setUsbTethering(boolean enable, String callerPkg) {
2943 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002944 if (isTetheringSupported()) {
2945 return mTethering.setUsbTethering(enable);
2946 } else {
2947 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2948 }
2949 }
2950
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002951 // TODO - move iface listing, queries, etc to new module
2952 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002953 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002954 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002955 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002956 return mTethering.getTetherableIfaces();
2957 }
2958
Lorenzo Colitti18660282016-07-04 12:55:44 +09002959 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002960 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002961 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002962 return mTethering.getTetheredIfaces();
2963 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002964
Lorenzo Colitti18660282016-07-04 12:55:44 +09002965 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002966 public String[] getTetheringErroredIfaces() {
2967 enforceTetherAccessPermission();
2968 return mTethering.getErroredIfaces();
2969 }
2970
Lorenzo Colitti18660282016-07-04 12:55:44 +09002971 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002972 public String[] getTetheredDhcpRanges() {
2973 enforceConnectivityInternalPermission();
2974 return mTethering.getTetheredDhcpRanges();
2975 }
2976
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002977 // if ro.tether.denied = true we default to no tethering
2978 // gservices could set the secure setting to 1 though to enable it on a build where it
2979 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002980 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002981 public boolean isTetheringSupported() {
2982 enforceTetherAccessPermission();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002983 int defaultVal = encodeBool(!mSystemProperties.get("ro.tether.denied").equals("true"));
2984 boolean tetherSupported = toBool(Settings.Global.getInt(mContext.getContentResolver(),
2985 Settings.Global.TETHER_SUPPORTED, defaultVal));
2986 boolean tetherEnabledInSettings = tetherSupported
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002987 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07002988
2989 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
2990 boolean adminUser = false;
2991 final long token = Binder.clearCallingIdentity();
2992 try {
2993 adminUser = mUserManager.isAdminUser();
2994 } finally {
2995 Binder.restoreCallingIdentity(token);
2996 }
2997
Hugo Benichiab7d2e62017-04-21 15:07:12 +09002998 return tetherEnabledInSettings && adminUser && mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002999 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003000
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003001 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003002 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi,
3003 String callerPkg) {
3004 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003005 if (!isTetheringSupported()) {
3006 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
3007 return;
3008 }
3009 mTethering.startTethering(type, receiver, showProvisioningUi);
3010 }
3011
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08003012 @Override
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09003013 public void stopTethering(int type, String callerPkg) {
3014 ConnectivityManager.enforceTetherChangePermission(mContext, callerPkg);
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003015 mTethering.stopTethering(type);
3016 }
3017
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003018 // Called when we lose the default network and have no replacement yet.
3019 // This will automatically be cleared after X seconds or a new default network
3020 // becomes CONNECTED, whichever happens first. The timer is started by the
3021 // first caller and not restarted by subsequent callers.
Hugo Benichi4c31b342017-03-30 23:18:10 +09003022 private void ensureNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003023 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003024 if (mNetTransitionWakeLock.isHeld()) {
3025 return;
3026 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003027 mNetTransitionWakeLock.acquire();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003028 mLastWakeLockAcquireTimestamp = SystemClock.elapsedRealtime();
3029 mTotalWakelockAcquisitions++;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003030 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003031 mWakelockLogs.log("ACQUIRE for " + forWhom);
3032 Message msg = mHandler.obtainMessage(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3033 mHandler.sendMessageDelayed(msg, mNetTransitionWakeLockTimeout);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003034 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003035
Hugo Benichi4c31b342017-03-30 23:18:10 +09003036 // Called when we gain a new default network to release the network transition wakelock in a
3037 // second, to allow a grace period for apps to reconnect over the new network. Pending expiry
3038 // message is cancelled.
3039 private void scheduleReleaseNetworkTransitionWakelock() {
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003040 synchronized (this) {
Hugo Benichi4c31b342017-03-30 23:18:10 +09003041 if (!mNetTransitionWakeLock.isHeld()) {
3042 return; // expiry message released the lock first.
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003043 }
3044 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003045 // Cancel self timeout on wakelock hold.
3046 mHandler.removeMessages(EVENT_EXPIRE_NET_TRANSITION_WAKELOCK);
3047 Message msg = mHandler.obtainMessage(EVENT_CLEAR_NET_TRANSITION_WAKELOCK);
3048 mHandler.sendMessageDelayed(msg, 1000);
3049 }
3050
3051 // Called when either message of ensureNetworkTransitionWakelock or
3052 // scheduleReleaseNetworkTransitionWakelock is processed.
3053 private void handleReleaseNetworkTransitionWakelock(int eventId) {
3054 String event = eventName(eventId);
3055 synchronized (this) {
3056 if (!mNetTransitionWakeLock.isHeld()) {
3057 mWakelockLogs.log(String.format("RELEASE: already released (%s)", event));
3058 Slog.w(TAG, "expected Net Transition WakeLock to be held");
3059 return;
3060 }
3061 mNetTransitionWakeLock.release();
Hugo Benichic3318aa2017-09-05 13:25:07 +09003062 long lockDuration = SystemClock.elapsedRealtime() - mLastWakeLockAcquireTimestamp;
3063 mTotalWakelockDurationMs += lockDuration;
3064 mMaxWakelockDurationMs = Math.max(mMaxWakelockDurationMs, lockDuration);
3065 mTotalWakelockReleases++;
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003066 }
Hugo Benichi4c31b342017-03-30 23:18:10 +09003067 mWakelockLogs.log(String.format("RELEASE (%s)", event));
Hugo Benichiaf52d7a2017-03-30 10:46:05 +09003068 }
3069
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003070 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003071 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003072 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003073 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003074 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003075 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003076 }
3077
Lorenzo Colitti18660282016-07-04 12:55:44 +09003078 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003079 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003080 enforceAccessPermission();
3081 enforceInternetPermission();
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003082 final int uid = Binder.getCallingUid();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003083 final int connectivityInfo = encodeBool(hasConnectivity);
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003084 mHandler.sendMessage(
3085 mHandler.obtainMessage(EVENT_REVALIDATE_NETWORK, uid, connectivityInfo, network));
3086 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003087
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003088 private void handleReportNetworkConnectivity(
3089 Network network, int uid, boolean hasConnectivity) {
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003090 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003091 if (network == null) {
3092 nai = getDefaultNetwork();
3093 } else {
3094 nai = getNetworkAgentInfoForNetwork(network);
3095 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003096 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3097 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3098 return;
3099 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003100 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003101 if (hasConnectivity == nai.lastValidated) {
3102 return;
3103 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003104 if (DBG) {
Hugo Benichi1c51d7a2017-04-06 17:22:18 +09003105 int netid = nai.network.netId;
3106 log("reportNetworkConnectivity(" + netid + ", " + hasConnectivity + ") by " + uid);
Paul Jensenbfd17b72015-04-07 12:43:13 -04003107 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003108 // Validating a network that has not yet connected could result in a call to
3109 // rematchNetworkAndRequests() which is not meant to work on such networks.
3110 if (!nai.everConnected) {
3111 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003112 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003113 LinkProperties lp = getLinkProperties(nai);
3114 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3115 return;
3116 }
3117 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003118 }
3119
Paul Jensencee9b512015-05-06 07:32:40 -04003120 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003121 // this information is already available as a world read/writable jvm property
3122 // so this API change wouldn't have a benifit. It also breaks the passing
3123 // of proxy info to all the JVMs.
3124 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003125 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003126 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003127 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3128 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003129 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003130 }
3131
Lorenzo Colitti18660282016-07-04 12:55:44 +09003132 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003133 public ProxyInfo getProxyForNetwork(Network network) {
3134 if (network == null) return getDefaultProxy();
3135 final ProxyInfo globalProxy = getGlobalProxy();
3136 if (globalProxy != null) return globalProxy;
3137 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3138 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3139 // caller may not have.
3140 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3141 if (nai == null) return null;
3142 synchronized (nai) {
3143 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3144 if (proxyInfo == null) return null;
3145 return new ProxyInfo(proxyInfo);
3146 }
3147 }
3148
Paul Jensene0bef712014-12-10 15:12:18 -05003149 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3150 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3151 // proxy is null then there is no proxy in place).
3152 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3153 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3154 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3155 proxy = null;
3156 }
3157 return proxy;
3158 }
3159
3160 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3161 // better for determining if a new proxy broadcast is necessary:
3162 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3163 // avoid unnecessary broadcasts.
3164 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3165 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3166 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3167 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3168 // all set.
3169 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3170 a = canonicalizeProxyInfo(a);
3171 b = canonicalizeProxyInfo(b);
3172 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3173 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3174 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3175 }
3176
Jason Monk207900c2014-04-25 15:00:09 -04003177 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003178 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003179
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003180 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003181 if (proxyProperties == mGlobalProxy) return;
3182 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3183 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3184
3185 String host = "";
3186 int port = 0;
3187 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003188 String pacFileUrl = "";
3189 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003190 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003191 if (!proxyProperties.isValid()) {
3192 if (DBG)
3193 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3194 return;
3195 }
Jason Monk207900c2014-04-25 15:00:09 -04003196 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003197 host = mGlobalProxy.getHost();
3198 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003199 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003200 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003201 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003202 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003203 } else {
3204 mGlobalProxy = null;
3205 }
3206 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003207 final long token = Binder.clearCallingIdentity();
3208 try {
3209 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3210 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3211 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3212 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003213 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003214 } finally {
3215 Binder.restoreCallingIdentity(token);
3216 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003217
Jason Monkcf0f97a2014-10-02 15:39:38 -04003218 if (mGlobalProxy == null) {
3219 proxyProperties = mDefaultProxy;
3220 }
3221 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003222 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003223 }
3224
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003225 private void loadGlobalProxy() {
3226 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003227 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3228 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3229 String exclList = Settings.Global.getString(res,
3230 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003231 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3232 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003233 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003234 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003235 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003236 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003237 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003238 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003239 if (!proxyProperties.isValid()) {
3240 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3241 return;
3242 }
3243
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003244 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003245 mGlobalProxy = proxyProperties;
3246 }
3247 }
3248 }
3249
Jason Monk207900c2014-04-25 15:00:09 -04003250 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003251 // this information is already available as a world read/writable jvm property
3252 // so this API change wouldn't have a benifit. It also breaks the passing
3253 // of proxy info to all the JVMs.
3254 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003255 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003256 return mGlobalProxy;
3257 }
3258 }
3259
Jason Monk207900c2014-04-25 15:00:09 -04003260 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003261 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003262 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003263 proxy = null;
3264 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003265 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003266 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003267 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003268 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003269 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3270 return;
3271 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003272
3273 // This call could be coming from the PacManager, containing the port of the local
3274 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3275 // global (to get the correct local port), and send a broadcast.
3276 // TODO: Switch PacManager to have its own message to send back rather than
3277 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003278 if ((mGlobalProxy != null) && (proxy != null)
3279 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003280 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3281 mGlobalProxy = proxy;
3282 sendProxyBroadcast(mGlobalProxy);
3283 return;
3284 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003285 mDefaultProxy = proxy;
3286
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003287 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003288 if (!mDefaultProxyDisabled) {
3289 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003290 }
3291 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003292 }
3293
Paul Jensene0bef712014-12-10 15:12:18 -05003294 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3295 // This method gets called when any network changes proxy, but the broadcast only ever contains
3296 // the default proxy (even if it hasn't changed).
3297 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3298 // world where an app might be bound to a non-default network.
3299 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3300 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3301 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3302
3303 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3304 sendProxyBroadcast(getDefaultProxy());
3305 }
3306 }
3307
Robert Greenwalt434203a2010-10-11 16:00:27 -07003308 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003309 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3310 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003311 if (!TextUtils.isEmpty(proxy)) {
3312 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003313 if (data.length == 0) {
3314 return;
3315 }
3316
Robert Greenwalt434203a2010-10-11 16:00:27 -07003317 String proxyHost = data[0];
3318 int proxyPort = 8080;
3319 if (data.length > 1) {
3320 try {
3321 proxyPort = Integer.parseInt(data[1]);
3322 } catch (NumberFormatException e) {
3323 return;
3324 }
3325 }
Jason Monk207900c2014-04-25 15:00:09 -04003326 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003327 setGlobalProxy(p);
3328 }
3329 }
3330
Jason Monk207900c2014-04-25 15:00:09 -04003331 private void sendProxyBroadcast(ProxyInfo proxy) {
3332 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003333 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003334 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003335 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003336 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3337 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003338 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003339 final long ident = Binder.clearCallingIdentity();
3340 try {
3341 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3342 } finally {
3343 Binder.restoreCallingIdentity(ident);
3344 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003345 }
3346
3347 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003348 final private HashMap<Uri, Integer> mUriEventMap;
3349 final private Context mContext;
3350 final private Handler mHandler;
3351
3352 SettingsObserver(Context context, Handler handler) {
3353 super(null);
3354 mUriEventMap = new HashMap<Uri, Integer>();
3355 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003356 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003357 }
3358
Erik Klineda4bfa82015-04-30 12:58:40 +09003359 void observe(Uri uri, int what) {
3360 mUriEventMap.put(uri, what);
3361 final ContentResolver resolver = mContext.getContentResolver();
3362 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003363 }
3364
3365 @Override
3366 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003367 Slog.wtf(TAG, "Should never be reached.");
3368 }
3369
3370 @Override
3371 public void onChange(boolean selfChange, Uri uri) {
3372 final Integer what = mUriEventMap.get(uri);
3373 if (what != null) {
3374 mHandler.obtainMessage(what.intValue()).sendToTarget();
3375 } else {
3376 loge("No matching event to send for URI=" + uri);
3377 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003378 }
3379 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003380
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003381 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003382 Slog.d(TAG, s);
3383 }
3384
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003385 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003386 Slog.e(TAG, s);
3387 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003388
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003389 private static void loge(String s, Throwable t) {
3390 Slog.e(TAG, s, t);
3391 }
3392
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003393 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003394 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003395 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3396 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3397 *
3398 * @param oldPackage Package name of the application which currently controls VPN, which will
3399 * be replaced. If there is no such application, this should should either be
3400 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3401 * @param newPackage Package name of the application which should gain control of VPN, or
3402 * {@code null} to disable.
3403 * @param userId User for whom to prepare the new VPN.
3404 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003405 * @hide
3406 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003407 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003408 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3409 int userId) {
3410 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003411 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003412
Hugo Benichi20035e02017-04-26 14:53:28 +09003413 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003414 Vpn vpn = mVpns.get(userId);
3415 if (vpn != null) {
3416 return vpn.prepare(oldPackage, newPackage);
3417 } else {
3418 return false;
3419 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003420 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003421 }
3422
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003423 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003424 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3425 * This method is used by system-privileged apps.
3426 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3427 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3428 *
3429 * @param packageName The package for which authorization state should change.
3430 * @param userId User for whom {@code packageName} is installed.
3431 * @param authorized {@code true} if this app should be able to start a VPN connection without
3432 * explicit user approval, {@code false} if not.
3433 *
Jeff Davidson05542602014-08-11 14:07:27 -07003434 * @hide
3435 */
3436 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003437 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3438 enforceCrossUserPermission(userId);
3439
Hugo Benichi20035e02017-04-26 14:53:28 +09003440 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003441 Vpn vpn = mVpns.get(userId);
3442 if (vpn != null) {
3443 vpn.setPackageAuthorization(packageName, authorized);
3444 }
Jeff Davidson05542602014-08-11 14:07:27 -07003445 }
3446 }
3447
3448 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003449 * Configure a TUN interface and return its file descriptor. Parameters
3450 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003451 * and not available in ConnectivityManager. Permissions are checked in
3452 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003453 * @hide
3454 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003455 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003456 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003457 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003458 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003459 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003460 return mVpns.get(user).establish(config);
3461 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003462 }
3463
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003464 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003465 * Start legacy VPN, controlling native daemons as needed. Creates a
3466 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003467 */
3468 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003469 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003470 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003471 final LinkProperties egress = getActiveLinkProperties();
3472 if (egress == null) {
3473 throw new IllegalStateException("Missing active network connection");
3474 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003475 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003476 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003477 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3478 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003479 }
3480
3481 /**
3482 * Return the information of the ongoing legacy VPN. This method is used
3483 * by VpnSettings and not available in ConnectivityManager. Permissions
3484 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003485 */
3486 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003487 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3488 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003489
Hugo Benichi20035e02017-04-26 14:53:28 +09003490 synchronized (mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003491 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003492 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003493 }
3494
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003495 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003496 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3497 * and not available in ConnectivityManager.
3498 */
3499 @Override
3500 public VpnInfo[] getAllVpnInfo() {
3501 enforceConnectivityInternalPermission();
3502 if (mLockdownEnabled) {
3503 return new VpnInfo[0];
3504 }
3505
Hugo Benichi20035e02017-04-26 14:53:28 +09003506 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003507 List<VpnInfo> infoList = new ArrayList<>();
3508 for (int i = 0; i < mVpns.size(); i++) {
3509 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3510 if (info != null) {
3511 infoList.add(info);
3512 }
3513 }
3514 return infoList.toArray(new VpnInfo[infoList.size()]);
3515 }
3516 }
3517
3518 /**
3519 * @return VPN information for accounting, or null if we can't retrieve all required
3520 * information, e.g primary underlying iface.
3521 */
3522 @Nullable
3523 private VpnInfo createVpnInfo(Vpn vpn) {
3524 VpnInfo info = vpn.getVpnInfo();
3525 if (info == null) {
3526 return null;
3527 }
3528 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3529 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3530 // the underlyingNetworks list.
3531 if (underlyingNetworks == null) {
3532 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3533 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3534 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3535 }
3536 } else if (underlyingNetworks.length > 0) {
3537 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3538 if (linkProperties != null) {
3539 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3540 }
3541 }
3542 return info.primaryUnderlyingIface == null ? null : info;
3543 }
3544
3545 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003546 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3547 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003548 * Permissions are checked in Vpn class.
3549 * @hide
3550 */
3551 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003552 public VpnConfig getVpnConfig(int userId) {
3553 enforceCrossUserPermission(userId);
Hugo Benichi20035e02017-04-26 14:53:28 +09003554 synchronized (mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003555 Vpn vpn = mVpns.get(userId);
3556 if (vpn != null) {
3557 return vpn.getVpnConfig();
3558 } else {
3559 return null;
3560 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003561 }
3562 }
3563
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003564 @Override
3565 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003566 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3567 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3568 return false;
3569 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003570
3571 // Tear down existing lockdown if profile was removed
3572 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3573 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003574 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3575 if (profileTag == null) {
3576 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3577 return false;
3578 }
3579 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003580 final VpnProfile profile = VpnProfile.decode(
3581 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003582 if (profile == null) {
3583 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3584 setLockdownTracker(null);
3585 return true;
3586 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003587 int user = UserHandle.getUserId(Binder.getCallingUid());
Hugo Benichi20035e02017-04-26 14:53:28 +09003588 synchronized (mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003589 Vpn vpn = mVpns.get(user);
3590 if (vpn == null) {
3591 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3592 return false;
3593 }
3594 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003595 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003596 } else {
3597 setLockdownTracker(null);
3598 }
3599
3600 return true;
3601 }
3602
3603 /**
3604 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3605 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3606 */
3607 private void setLockdownTracker(LockdownVpnTracker tracker) {
3608 // Shutdown any existing tracker
3609 final LockdownVpnTracker existing = mLockdownTracker;
3610 mLockdownTracker = null;
3611 if (existing != null) {
3612 existing.shutdown();
3613 }
3614
Robin Leec3736bc2017-03-10 16:19:54 +00003615 if (tracker != null) {
3616 mLockdownTracker = tracker;
3617 mLockdownTracker.init();
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003618 }
3619 }
3620
3621 private void throwIfLockdownEnabled() {
3622 if (mLockdownEnabled) {
3623 throw new IllegalStateException("Unavailable in lockdown mode");
3624 }
3625 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003626
Robin Lee244ce8e2016-01-05 18:03:46 +00003627 /**
Robin Lee17e61832016-05-09 13:46:28 +01003628 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3629 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003630 *
Robin Lee17e61832016-05-09 13:46:28 +01003631 * @return {@code true} if the service was started, the service was already connected, or there
3632 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003633 */
Robin Lee17e61832016-05-09 13:46:28 +01003634 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003635 synchronized (mVpns) {
3636 Vpn vpn = mVpns.get(userId);
3637 if (vpn == null) {
3638 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3639 // exists already.
3640 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3641 return false;
3642 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003643
Robin Lee812800c2016-05-13 15:38:08 +01003644 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003645 }
3646 }
3647
3648 @Override
Robin Leedc679712016-05-03 13:23:03 +01003649 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003650 enforceConnectivityInternalPermission();
3651 enforceCrossUserPermission(userId);
3652
3653 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3654 if (LockdownVpnTracker.isEnabled()) {
3655 return false;
3656 }
3657
Robin Lee244ce8e2016-01-05 18:03:46 +00003658 synchronized (mVpns) {
3659 Vpn vpn = mVpns.get(userId);
3660 if (vpn == null) {
3661 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3662 return false;
3663 }
Robin Lee17e61832016-05-09 13:46:28 +01003664 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003665 return false;
3666 }
Robin Lee17e61832016-05-09 13:46:28 +01003667 if (!startAlwaysOnVpn(userId)) {
3668 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003669 return false;
3670 }
3671 }
3672 return true;
3673 }
3674
3675 @Override
3676 public String getAlwaysOnVpnPackage(int userId) {
3677 enforceConnectivityInternalPermission();
3678 enforceCrossUserPermission(userId);
3679
3680 synchronized (mVpns) {
3681 Vpn vpn = mVpns.get(userId);
3682 if (vpn == null) {
3683 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3684 return null;
3685 }
3686 return vpn.getAlwaysOnPackage();
3687 }
3688 }
3689
Wink Savilleab9321d2013-06-29 21:10:57 -07003690 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003691 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003692 // TODO: Remove? Any reason to trigger a provisioning check?
3693 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003694 }
3695
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003696 /** Location to an updatable file listing carrier provisioning urls.
3697 * An example:
3698 *
3699 * <?xml version="1.0" encoding="utf-8"?>
3700 * <provisioningUrls>
3701 * <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 -07003702 * </provisioningUrls>
3703 */
3704 private static final String PROVISIONING_URL_PATH =
3705 "/data/misc/radio/provisioning_urls.xml";
3706 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003707
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003708 /** XML tag for root element. */
3709 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3710 /** XML tag for individual url */
3711 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003712 /** XML attribute for mcc */
3713 private static final String ATTR_MCC = "mcc";
3714 /** XML attribute for mnc */
3715 private static final String ATTR_MNC = "mnc";
3716
Paul Jensen434dde82015-06-11 09:43:30 -04003717 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003718 FileReader fileReader = null;
3719 XmlPullParser parser = null;
3720 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003721
3722 try {
3723 fileReader = new FileReader(mProvisioningUrlFile);
3724 parser = Xml.newPullParser();
3725 parser.setInput(fileReader);
3726 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3727
3728 while (true) {
3729 XmlUtils.nextElement(parser);
3730
3731 String element = parser.getName();
3732 if (element == null) break;
3733
Paul Jensen434dde82015-06-11 09:43:30 -04003734 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003735 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3736 try {
3737 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3738 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3739 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3740 parser.next();
3741 if (parser.getEventType() == XmlPullParser.TEXT) {
3742 return parser.getText();
3743 }
3744 }
3745 }
3746 } catch (NumberFormatException e) {
3747 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3748 }
3749 }
3750 }
3751 return null;
3752 } catch (FileNotFoundException e) {
3753 loge("Carrier Provisioning Urls file not found");
3754 } catch (XmlPullParserException e) {
3755 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3756 } catch (IOException e) {
3757 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3758 } finally {
3759 if (fileReader != null) {
3760 try {
3761 fileReader.close();
3762 } catch (IOException e) {}
3763 }
3764 }
3765 return null;
3766 }
3767
Wink Saville42d4f082013-07-20 20:31:59 -07003768 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003769 public String getMobileProvisioningUrl() {
3770 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003771 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003772 if (TextUtils.isEmpty(url)) {
3773 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003774 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003775 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003776 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003777 }
Wink Saville8cf35602013-07-10 23:00:07 -07003778 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003779 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003780 String phoneNumber = mTelephonyManager.getLine1Number();
3781 if (TextUtils.isEmpty(phoneNumber)) {
3782 phoneNumber = "0000000000";
3783 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003784 url = String.format(url,
3785 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3786 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003787 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003788 }
3789
Wink Savilleab9321d2013-06-29 21:10:57 -07003790 return url;
3791 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003792
Wink Saville948282b2013-08-29 08:55:16 -07003793 @Override
3794 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003795 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003796 enforceConnectivityInternalPermission();
Hugo Benichi16f0a942017-06-20 14:07:59 +09003797 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
3798 return;
3799 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003800 final long ident = Binder.clearCallingIdentity();
3801 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003802 // Concatenate the range of types onto the range of NetIDs.
3803 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3804 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003805 } finally {
3806 Binder.restoreCallingIdentity(ident);
3807 }
Wink Saville948282b2013-08-29 08:55:16 -07003808 }
Wink Saville7788c612013-08-29 14:57:08 -07003809
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003810 @Override
3811 public void setAirplaneMode(boolean enable) {
3812 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003813 final long ident = Binder.clearCallingIdentity();
3814 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003815 final ContentResolver cr = mContext.getContentResolver();
Hugo Benichiab7d2e62017-04-21 15:07:12 +09003816 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, encodeBool(enable));
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003817 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3818 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003819 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003820 } finally {
3821 Binder.restoreCallingIdentity(ident);
3822 }
3823 }
3824
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003825 private void onUserStart(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003826 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003827 Vpn userVpn = mVpns.get(userId);
3828 if (userVpn != null) {
3829 loge("Starting user already has a VPN");
3830 return;
3831 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003832 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003833 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003834 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003835 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3836 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003837 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003838 }
3839
3840 private void onUserStop(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003841 synchronized (mVpns) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003842 Vpn userVpn = mVpns.get(userId);
3843 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003844 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003845 return;
3846 }
Robin Lee17e61832016-05-09 13:46:28 +01003847 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003848 mVpns.delete(userId);
3849 }
3850 }
3851
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003852 private void onUserAdded(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003853 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003854 final int vpnsSize = mVpns.size();
3855 for (int i = 0; i < vpnsSize; i++) {
3856 Vpn vpn = mVpns.valueAt(i);
3857 vpn.onUserAdded(userId);
3858 }
3859 }
3860 }
3861
3862 private void onUserRemoved(int userId) {
Hugo Benichi20035e02017-04-26 14:53:28 +09003863 synchronized (mVpns) {
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003864 final int vpnsSize = mVpns.size();
3865 for (int i = 0; i < vpnsSize; i++) {
3866 Vpn vpn = mVpns.valueAt(i);
3867 vpn.onUserRemoved(userId);
3868 }
3869 }
3870 }
3871
Robin Lee89e7a692016-02-29 14:38:17 +00003872 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003873 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3874 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3875 updateLockdownVpn();
3876 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003877 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003878 }
3879 }
3880
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003881 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3882 @Override
3883 public void onReceive(Context context, Intent intent) {
3884 final String action = intent.getAction();
3885 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3886 if (userId == UserHandle.USER_NULL) return;
3887
Robin Lee323f29d2016-05-04 16:38:06 +01003888 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003889 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003890 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003891 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003892 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3893 onUserAdded(userId);
3894 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3895 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003896 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3897 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003898 }
3899 }
3900 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003901
Robin Lee95204e02017-01-27 11:59:22 +00003902 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3903 @Override
3904 public void onReceive(Context context, Intent intent) {
3905 // Try creating lockdown tracker, since user present usually means
3906 // unlocked keystore.
3907 updateLockdownVpn();
3908 mContext.unregisterReceiver(this);
3909 }
3910 };
3911
Robert Greenwalta67be032014-05-16 15:49:14 -07003912 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3913 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003914 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3915 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003916
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003917 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3918 // Map from UID to number of NetworkRequests that UID has filed.
3919 @GuardedBy("mUidToNetworkRequestCount")
3920 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3921
Robert Greenwalta67be032014-05-16 15:49:14 -07003922 private static class NetworkFactoryInfo {
3923 public final String name;
3924 public final Messenger messenger;
3925 public final AsyncChannel asyncChannel;
3926
3927 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3928 this.name = name;
3929 this.messenger = messenger;
3930 this.asyncChannel = asyncChannel;
3931 }
3932 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003933
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003934 private void ensureNetworkRequestHasType(NetworkRequest request) {
3935 if (request.type == NetworkRequest.Type.NONE) {
3936 throw new IllegalArgumentException(
3937 "All NetworkRequests in ConnectivityService must have a type");
3938 }
3939 }
3940
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003941 /**
3942 * Tracks info about the requester.
3943 * Also used to notice when the calling process dies so we can self-expire
3944 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003945 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003946 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003947 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003948 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003949 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003950 final int mPid;
3951 final int mUid;
3952 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003953
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003954 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003955 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003956 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003957 mPendingIntent = pi;
3958 messenger = null;
3959 mBinder = null;
3960 mPid = getCallingPid();
3961 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003962 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003963 }
3964
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003965 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003966 super();
3967 messenger = m;
3968 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003969 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003970 mBinder = binder;
3971 mPid = getCallingPid();
3972 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003973 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003974 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003975
3976 try {
3977 mBinder.linkToDeath(this, 0);
3978 } catch (RemoteException e) {
3979 binderDied();
3980 }
3981 }
3982
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003983 private void enforceRequestCountLimit() {
3984 synchronized (mUidToNetworkRequestCount) {
3985 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3986 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
Hugo Benichicb883232017-05-11 13:16:17 +09003987 throw new ServiceSpecificException(
3988 ConnectivityManager.Errors.TOO_MANY_REQUESTS);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003989 }
3990 mUidToNetworkRequestCount.put(mUid, networkRequests);
3991 }
3992 }
3993
Robert Greenwalt9258c642014-03-26 16:47:06 -07003994 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003995 if (mBinder != null) {
3996 mBinder.unlinkToDeath(this, 0);
3997 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003998 }
3999
4000 public void binderDied() {
4001 log("ConnectivityService NetworkRequestInfo binderDied(" +
4002 request + ", " + mBinder + ")");
4003 releaseNetworkRequest(request);
4004 }
Robert Greenwalta67be032014-05-16 15:49:14 -07004005
4006 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004007 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004008 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07004009 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004010 }
4011
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004012 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
4013 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
4014 if (badCapability != null) {
4015 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04004016 }
4017 }
4018
Erik Kline9d598e12015-07-13 16:37:51 +09004019 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004020 final SortedSet<Integer> thresholds = new TreeSet();
4021 synchronized (nai) {
4022 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4023 if (nri.request.networkCapabilities.hasSignalStrength() &&
4024 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
4025 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
4026 }
4027 }
4028 }
Erik Kline9d598e12015-07-13 16:37:51 +09004029 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004030 }
4031
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004032 private void updateSignalStrengthThresholds(
4033 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4034 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004035 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004036 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4037
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004038 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004039 String detail;
4040 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4041 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4042 } else {
4043 detail = reason;
4044 }
4045 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4046 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4047 }
4048
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004049 nai.asyncChannel.sendMessage(
4050 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004051 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004052 }
4053
Etan Cohen859748f2017-04-03 17:42:34 -07004054 private void ensureValidNetworkSpecifier(NetworkCapabilities nc) {
4055 if (nc == null) {
4056 return;
4057 }
4058 NetworkSpecifier ns = nc.getNetworkSpecifier();
4059 if (ns == null) {
4060 return;
4061 }
4062 MatchAllNetworkSpecifier.checkNotMatchAllNetworkSpecifier(ns);
4063 ns.assertValidFromUid(Binder.getCallingUid());
4064 }
4065
Robert Greenwalt9258c642014-03-26 16:47:06 -07004066 @Override
4067 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004068 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004069 final NetworkRequest.Type type = (networkCapabilities == null)
4070 ? NetworkRequest.Type.TRACK_DEFAULT
4071 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004072 // If the requested networkCapabilities is null, take them instead from
4073 // the default network request. This allows callers to keep track of
4074 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004075 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004076 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4077 enforceAccessPermission();
4078 } else {
4079 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4080 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004081 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4082 // of the app when the request is filed, but we never change the request if the app
4083 // changes network state. http://b/29964605
4084 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004085 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004086 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004087
Etan Cohenba07c8c2017-02-05 10:42:27 -08004088 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004089 throw new IllegalArgumentException("Bad timeout specified");
4090 }
Etan Cohen859748f2017-04-03 17:42:34 -07004091 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohenddb9ef02015-11-18 10:56:15 -08004092
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004093 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004094 nextNetworkRequestId(), type);
4095 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004096 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004097
4098 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004099 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004100 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004101 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004102 }
4103 return networkRequest;
4104 }
4105
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004106 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004107 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004108 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004109 } else {
4110 enforceChangePermission();
4111 }
4112 }
4113
fenglub15e72b2015-03-20 11:29:56 -07004114 @Override
fengludb571472015-04-21 17:12:05 -07004115 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004116 enforceAccessPermission();
4117 NetworkAgentInfo nai = null;
4118 if (network == null) {
4119 return false;
4120 }
4121 synchronized (mNetworkForNetId) {
4122 nai = mNetworkForNetId.get(network.netId);
4123 }
4124 if (nai != null) {
4125 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4126 return true;
4127 }
4128 return false;
4129 }
4130
Felipe Lemeee27cab2016-06-20 16:36:29 -07004131 private boolean isSystem(int uid) {
4132 return uid < Process.FIRST_APPLICATION_UID;
4133 }
fenglub15e72b2015-03-20 11:29:56 -07004134
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004135 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004136 final int uid = Binder.getCallingUid();
4137 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004138 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004139 return;
4140 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004141 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4142 // Policy already enforced.
4143 return;
4144 }
4145 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4146 // If UID is restricted, don't allow them to bring up metered APNs.
4147 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004148 }
4149 }
4150
Robert Greenwalt9258c642014-03-26 16:47:06 -07004151 @Override
4152 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4153 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004154 checkNotNull(operation, "PendingIntent cannot be null.");
4155 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4156 enforceNetworkRequestPermissions(networkCapabilities);
4157 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004158 ensureRequestableCapabilities(networkCapabilities);
Etan Cohen859748f2017-04-03 17:42:34 -07004159 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004160
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004161 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004162 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4163 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004164 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004165 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4166 nri));
4167 return networkRequest;
4168 }
4169
Jeremy Joslin79294842014-12-03 17:15:28 -08004170 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4171 mHandler.sendMessageDelayed(
4172 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4173 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4174 }
4175
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004176 @Override
4177 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004178 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004179 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4180 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004181 }
4182
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004183 // In order to implement the compatibility measure for pre-M apps that call
4184 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4185 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4186 // This ensures it has permission to do so.
4187 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4188 if (nc == null) {
4189 return false;
4190 }
4191 int[] transportTypes = nc.getTransportTypes();
4192 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4193 return false;
4194 }
4195 try {
4196 mContext.enforceCallingOrSelfPermission(
4197 android.Manifest.permission.ACCESS_WIFI_STATE,
4198 "ConnectivityService");
4199 } catch (SecurityException e) {
4200 return false;
4201 }
4202 return true;
4203 }
4204
Robert Greenwalt9258c642014-03-26 16:47:06 -07004205 @Override
4206 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4207 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004208 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4209 enforceAccessPermission();
4210 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004211
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004212 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4213 if (!ConnectivityManager.checkChangePermission(mContext)) {
4214 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4215 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4216 // onLost and onAvailable callbacks when networks move in and out of the background.
4217 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4218 // can't request networks.
4219 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4220 }
Etan Cohen859748f2017-04-03 17:42:34 -07004221 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004222
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004223 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004224 NetworkRequest.Type.LISTEN);
4225 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004226 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004227
4228 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4229 return networkRequest;
4230 }
4231
4232 @Override
4233 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4234 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004235 checkNotNull(operation, "PendingIntent cannot be null.");
4236 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4237 enforceAccessPermission();
4238 }
Etan Cohen859748f2017-04-03 17:42:34 -07004239 ensureValidNetworkSpecifier(networkCapabilities);
Etan Cohena7434272017-04-03 12:17:51 -07004240
Erik Kline7523eb32015-07-09 18:24:03 +09004241 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004242 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4243 NetworkRequest.Type.LISTEN);
4244 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004245 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004246
4247 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004248 }
4249
Erik Klineacdd6392016-07-07 16:50:58 +09004250 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004251 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004252 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004253 mHandler.sendMessage(mHandler.obtainMessage(
4254 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004255 }
4256
4257 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004258 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004259 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004260 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4261 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004262 }
4263
Robert Greenwalta67be032014-05-16 15:49:14 -07004264 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004265 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004266 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4267 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4268 }
4269
4270 @Override
4271 public void unregisterNetworkFactory(Messenger messenger) {
4272 enforceConnectivityInternalPermission();
4273 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4274 }
4275
4276 private void handleUnregisterNetworkFactory(Messenger messenger) {
4277 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4278 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004279 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004280 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004281 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004282 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004283 }
4284
Robert Greenwalt7b816022014-04-18 15:25:25 -07004285 /**
4286 * NetworkAgentInfo supporting a request by requestId.
4287 * These have already been vetted (their Capabilities satisfy the request)
4288 * and the are the highest scored network available.
4289 * the are keyed off the Requests requestId.
4290 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004291 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004292 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4293 new SparseArray<NetworkAgentInfo>();
4294
Paul Jensen31a94f42015-02-13 14:18:39 -05004295 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4296 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004297 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4298 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004299 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4300 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4301 // there may not be a strict 1:1 correlation between the two.
4302 @GuardedBy("mNetworkForNetId")
4303 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004304
Robert Greenwalt7b816022014-04-18 15:25:25 -07004305 // NetworkAgentInfo keyed off its connecting messenger
4306 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004307 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004308 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4309 new HashMap<Messenger, NetworkAgentInfo>();
4310
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004311 @GuardedBy("mBlockedAppUids")
4312 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4313
Paul Jensen2c311d62014-11-17 12:34:51 -05004314 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004315 private final NetworkRequest mDefaultRequest;
4316
Erik Klineda4bfa82015-04-30 12:58:40 +09004317 // Request used to optionally keep mobile data active even when higher
4318 // priority networks like Wi-Fi are active.
4319 private final NetworkRequest mDefaultMobileDataRequest;
4320
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004321 private NetworkAgentInfo getDefaultNetwork() {
4322 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4323 }
4324
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004325 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004326 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004327 }
4328
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004329 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4330 return nri.request.requestId == mDefaultRequest.requestId;
4331 }
4332
Paul Jensen31a94f42015-02-13 14:18:39 -05004333 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004334 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004335 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004336 enforceConnectivityInternalPermission();
4337
Rubin Xu1bb5c082017-09-05 18:40:49 +01004338 LinkProperties lp = new LinkProperties(linkProperties);
4339 lp.ensureDirectlyConnectedRoutes();
Paul Jensen2c311d62014-11-17 12:34:51 -05004340 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4341 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004342 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Rubin Xu1bb5c082017-09-05 18:40:49 +01004343 new Network(reserveNetId()), new NetworkInfo(networkInfo), lp,
4344 new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004345 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004346 synchronized (this) {
4347 nai.networkMonitor.systemReady = mSystemReady;
4348 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004349 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4350 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004351 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004352 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004353 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004354 }
4355
4356 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4357 if (VDBG) log("Got NetworkAgent Messenger");
4358 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004359 synchronized (mNetworkForNetId) {
4360 mNetworkForNetId.put(na.network.netId, na);
4361 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004362 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4363 NetworkInfo networkInfo = na.networkInfo;
4364 na.networkInfo = null;
4365 updateNetworkInfo(na, networkInfo);
4366 }
4367
4368 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4369 LinkProperties newLp = networkAgent.linkProperties;
4370 int netId = networkAgent.network.netId;
4371
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004372 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4373 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004374 if (networkAgent.clatd != null) {
4375 networkAgent.clatd.fixupLinkProperties(oldLp);
4376 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004377
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004378 updateInterfaces(newLp, oldLp, netId, networkAgent.networkCapabilities);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004379 updateMtu(newLp, oldLp);
4380 // TODO - figure out what to do for clat
4381// for (LinkProperties lp : newLp.getStackedLinks()) {
4382// updateMtu(lp, null);
4383// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004384 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004385
Erik Kline94887872016-04-05 13:30:49 +09004386 updateRoutes(newLp, oldLp, netId);
4387 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004388
Hugo Benichib577d652017-06-27 15:13:20 +09004389 // Start or stop clat accordingly to network state.
Hugo Benichief502882017-09-01 01:23:32 +00004390 networkAgent.updateClat(mNetd);
Paul Jensene0bef712014-12-10 15:12:18 -05004391 if (isDefaultNetwork(networkAgent)) {
4392 handleApplyDefaultProxy(newLp.getHttpProxy());
4393 } else {
4394 updateProxy(newLp, oldLp, networkAgent);
4395 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004396 // TODO - move this check to cover the whole function
4397 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004398 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004399 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4400 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004401
4402 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004403 }
4404
Joel Scherpelz668370b2017-06-08 15:35:21 +09004405 private void wakeupModifyInterface(String iface, NetworkCapabilities caps, boolean add) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004406 // Marks are only available on WiFi interaces. Checking for
4407 // marks on unsupported interfaces is harmless.
4408 if (!caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
4409 return;
4410 }
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004411
Joel Scherpelz668370b2017-06-08 15:35:21 +09004412 int mark = mContext.getResources().getInteger(
4413 com.android.internal.R.integer.config_networkWakeupPacketMark);
4414 int mask = mContext.getResources().getInteger(
4415 com.android.internal.R.integer.config_networkWakeupPacketMask);
4416
4417 // Mask/mark of zero will not detect anything interesting.
4418 // Don't install rules unless both values are nonzero.
4419 if (mark == 0 || mask == 0) {
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004420 return;
4421 }
Joel Scherpelz668370b2017-06-08 15:35:21 +09004422
4423 final String prefix = "iface:" + iface;
4424 try {
4425 if (add) {
4426 mNetd.getNetdService().wakeupAddInterface(iface, prefix, mark, mask);
4427 } else {
4428 mNetd.getNetdService().wakeupDelInterface(iface, prefix, mark, mask);
4429 }
4430 } catch (Exception e) {
4431 loge("Exception modifying wakeup packet monitoring: " + e);
4432 }
4433
Joel Scherpelzb369bf52017-05-22 13:47:41 +09004434 }
4435
4436 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId,
4437 NetworkCapabilities caps) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004438 CompareResult<String> interfaceDiff = new CompareResult<String>(
4439 oldLp != null ? oldLp.getAllInterfaceNames() : null,
4440 newLp != null ? newLp.getAllInterfaceNames() : null);
Paul Jensen992f2522014-04-28 10:33:11 -04004441 for (String iface : interfaceDiff.added) {
4442 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004443 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004444 mNetd.addInterfaceToNetwork(iface, netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004445 wakeupModifyInterface(iface, caps, true);
Paul Jensen992f2522014-04-28 10:33:11 -04004446 } catch (Exception e) {
4447 loge("Exception adding interface: " + e);
4448 }
4449 }
4450 for (String iface : interfaceDiff.removed) {
4451 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004452 if (DBG) log("Removing iface " + iface + " from network " + netId);
Joel Scherpelz668370b2017-06-08 15:35:21 +09004453 wakeupModifyInterface(iface, caps, false);
Paul Jensen992f2522014-04-28 10:33:11 -04004454 mNetd.removeInterfaceFromNetwork(iface, netId);
4455 } catch (Exception e) {
4456 loge("Exception removing interface: " + e);
4457 }
4458 }
4459 }
4460
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004461 /**
4462 * Have netd update routes from oldLp to newLp.
4463 * @return true if routes changed between oldLp and newLp
4464 */
4465 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Rubin Xu2fc72f72017-08-22 16:35:52 +01004466 // Compare the route diff to determine which routes should be added and removed.
4467 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>(
4468 oldLp != null ? oldLp.getAllRoutes() : null,
4469 newLp != null ? newLp.getAllRoutes() : null);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004470
4471 // add routes before removing old in case it helps with continuous connectivity
4472
4473 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4474 for (RouteInfo route : routeDiff.added) {
4475 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004476 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004477 try {
4478 mNetd.addRoute(netId, route);
4479 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004480 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4481 loge("Exception in addRoute for non-gateway: " + e);
4482 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004483 }
4484 }
4485 for (RouteInfo route : routeDiff.added) {
4486 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004487 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004488 try {
4489 mNetd.addRoute(netId, route);
4490 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004491 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4492 loge("Exception in addRoute for gateway: " + e);
4493 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004494 }
4495 }
4496
4497 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004498 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004499 try {
4500 mNetd.removeRoute(netId, route);
4501 } catch (Exception e) {
4502 loge("Exception in removeRoute: " + e);
4503 }
4504 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004505 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004506 }
Erik Kline41368502015-06-17 13:19:54 +09004507
Erik Kline94887872016-04-05 13:30:49 +09004508 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4509 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4510 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004511 }
Erik Kline94887872016-04-05 13:30:49 +09004512
4513 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004514 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004515 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004516 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004517 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4518 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004519 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004520 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004521 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4522 if (defaultNai != null && defaultNai.network.netId == netId) {
4523 setDefaultDnsSystemProperties(dnses);
4524 }
Erik Kline94887872016-04-05 13:30:49 +09004525 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004526 }
4527
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004528 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4529 int last = 0;
4530 for (InetAddress dns : dnses) {
4531 ++last;
Erik Kline4edba012017-04-07 15:29:29 +09004532 setNetDnsProperty(last, dns.getHostAddress());
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004533 }
4534 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
Erik Kline4edba012017-04-07 15:29:29 +09004535 setNetDnsProperty(i, "");
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004536 }
4537 mNumDnsEntries = last;
4538 }
4539
Erik Kline4edba012017-04-07 15:29:29 +09004540 private void setNetDnsProperty(int which, String value) {
4541 final String key = "net.dns" + which;
4542 // Log and forget errors setting unsupported properties.
4543 try {
4544 mSystemProperties.set(key, value);
4545 } catch (Exception e) {
4546 Log.e(TAG, "Error setting unsupported net.dns property: ", e);
4547 }
4548 }
4549
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004550 private String getNetworkPermission(NetworkCapabilities nc) {
4551 // TODO: make these permission strings AIDL constants instead.
4552 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4553 return NetworkManagementService.PERMISSION_SYSTEM;
4554 }
4555 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4556 return NetworkManagementService.PERMISSION_NETWORK;
4557 }
4558 return null;
4559 }
4560
Paul Jensen3d194ea2015-06-16 14:27:36 -04004561 /**
4562 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4563 * augmented with any stateful capabilities implied from {@code networkAgent}
4564 * (e.g., validated status and captive portal status).
4565 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004566 * @param oldScore score of the network before any of the changes that prompted us
4567 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004568 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004569 * @param networkCapabilities the new network capabilities.
4570 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004571 private void updateCapabilities(
4572 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004573 // Once a NetworkAgent is connected, complain if some immutable capabilities are removed.
Hugo Benichia60c6ea2017-08-18 14:41:22 +09004574 if (nai.everConnected && !nai.networkCapabilities.satisfiedByImmutableNetworkCapabilities(
4575 networkCapabilities)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004576 // TODO: consider not complaining when a network agent degrade its capabilities if this
4577 // does not cause any request (that is not a listen) currently matching that agent to
4578 // stop being matched by the updated agent.
Hugo Benichieae7a222017-07-25 11:40:56 +09004579 String diff = nai.networkCapabilities.describeImmutableDifferences(networkCapabilities);
4580 if (!TextUtils.isEmpty(diff)) {
Hugo Benichibae105a2017-08-16 13:19:04 +09004581 Slog.wtf(TAG, "BUG: " + nai + " lost immutable capabilities:" + diff);
Hugo Benichieae7a222017-07-25 11:40:56 +09004582 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004583 }
4584
Paul Jensen3d194ea2015-06-16 14:27:36 -04004585 // Don't modify caller's NetworkCapabilities.
4586 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004587 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004588 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4589 } else {
4590 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4591 }
Paul Jensene0988542015-06-25 15:30:08 -04004592 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004593 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4594 } else {
4595 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4596 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004597 if (nai.isBackgroundNetwork()) {
4598 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4599 } else {
4600 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4601 }
4602
4603 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4604
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004605 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4606 final String newPermission = getNetworkPermission(networkCapabilities);
4607 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004608 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004609 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004610 } catch (RemoteException e) {
4611 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004612 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004613 }
4614
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004615 final NetworkCapabilities prevNc = nai.networkCapabilities;
4616 synchronized (nai) {
4617 nai.networkCapabilities = networkCapabilities;
4618 }
4619 if (nai.getCurrentScore() == oldScore &&
4620 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4621 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4622 // the change we're processing can't affect any requests, it can only affect the listens
4623 // on this network. We might have been called by rematchNetworkAndRequests when a
4624 // network changed foreground state.
4625 processListenRequests(nai, true);
4626 } else {
4627 // If the requestable capabilities have changed or the score changed, we can't have been
4628 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004629 rematchAllNetworksAndRequests(nai, oldScore);
4630 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004631 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004632 }
4633
Hugo Benichief502882017-09-01 01:23:32 +00004634 public void handleUpdateLinkProperties(NetworkAgentInfo nai, LinkProperties newLp) {
4635 if (mNetworkForNetId.get(nai.network.netId) != nai) {
4636 // Ignore updates for disconnected networks
4637 return;
4638 }
4639
4640 if (VDBG) {
4641 log("Update of LinkProperties for " + nai.name() +
4642 "; created=" + nai.created +
4643 "; everConnected=" + nai.everConnected);
4644 }
4645 LinkProperties oldLp = nai.linkProperties;
4646 synchronized (nai) {
4647 nai.linkProperties = newLp;
4648 }
Rubin Xu1bb5c082017-09-05 18:40:49 +01004649 // msg.obj is already a defensive copy.
4650 nai.linkProperties.ensureDirectlyConnectedRoutes();
Hugo Benichief502882017-09-01 01:23:32 +00004651 if (nai.everConnected) {
4652 updateLinkProperties(nai, oldLp);
4653 }
4654 }
4655
Paul Jensenc8b9a742014-09-30 15:37:41 -04004656 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004657 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4658 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004659 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004660 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004661 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4662 }
4663 }
4664
Robert Greenwalt7b816022014-04-18 15:25:25 -07004665 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4666 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004667 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004668 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4669 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004670 }
4671 }
4672
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004673 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4674 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004675 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004676 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004677 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4678 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004679 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004680 sendIntent(nri.mPendingIntent, intent);
4681 }
4682 // else not handled
4683 }
4684
4685 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4686 mPendingIntentWakeLock.acquire();
4687 try {
4688 if (DBG) log("Sending " + pendingIntent);
4689 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4690 } catch (PendingIntent.CanceledException e) {
4691 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4692 mPendingIntentWakeLock.release();
4693 releasePendingNetworkRequest(pendingIntent);
4694 }
4695 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4696 }
4697
4698 @Override
4699 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4700 String resultData, Bundle resultExtras) {
4701 if (DBG) log("Finished sending " + pendingIntent);
4702 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004703 // Release with a delay so the receiving client has an opportunity to put in its
4704 // own request.
4705 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004706 }
4707
Hugo Benichidba33db2017-03-23 22:40:44 +09004708 private static void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004709 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Hugo Benichidba33db2017-03-23 22:40:44 +09004710 if (nri.messenger == null) {
4711 return; // Default request has no msgr
4712 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004713 Bundle bundle = new Bundle();
Hugo Benichidba33db2017-03-23 22:40:44 +09004714 // TODO: check if defensive copies of data is needed.
4715 putParcelable(bundle, new NetworkRequest(nri.request));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004716 Message msg = Message.obtain();
Hugo Benichidba33db2017-03-23 22:40:44 +09004717 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL) {
4718 putParcelable(bundle, networkAgent.network);
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004719 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004720 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004721 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004722 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004723 break;
4724 }
4725 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004726 putParcelable(bundle, new NetworkCapabilities(networkAgent.networkCapabilities));
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004727 break;
4728 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004729 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Hugo Benichidba33db2017-03-23 22:40:44 +09004730 putParcelable(bundle, new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004731 break;
4732 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004733 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004734 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004735 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004736 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004737 if (VDBG) {
Hugo Benichia0385682017-03-22 17:07:57 +09004738 String notification = ConnectivityManager.getCallbackName(notificationType);
4739 log("sending notification " + notification + " for " + nri.request);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004740 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004741 nri.messenger.send(msg);
4742 } catch (RemoteException e) {
4743 // may occur naturally in the race of binder death.
4744 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4745 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004746 }
4747
Hugo Benichidba33db2017-03-23 22:40:44 +09004748 private static <T extends Parcelable> void putParcelable(Bundle bundle, T t) {
4749 bundle.putParcelable(t.getClass().getSimpleName(), t);
4750 }
4751
Paul Jensenc8b9a742014-09-30 15:37:41 -04004752 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004753 if (nai.numRequestNetworkRequests() != 0) {
4754 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4755 NetworkRequest nr = nai.requestAt(i);
4756 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004757 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004758 loge("Dead network still had at least " + nr);
4759 break;
4760 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004761 }
4762 nai.asyncChannel.disconnect();
4763 }
4764
Robert Greenwalt7b816022014-04-18 15:25:25 -07004765 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4766 if (oldNetwork == null) {
4767 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4768 return;
4769 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004770 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004771
4772 // If we get here it means that the last linger timeout for this network expired. So there
4773 // must be no other active linger timers, and we must stop lingering.
4774 oldNetwork.clearLingerState();
4775
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004776 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004777 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004778 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004779 } else {
4780 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004781 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4782 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004783 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004784 }
4785
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004786 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004787 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004788 setupDataActivityTracking(newNetwork);
4789 try {
4790 mNetd.setDefaultNetId(newNetwork.network.netId);
4791 } catch (Exception e) {
4792 loge("Exception setting default network :" + e);
4793 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004794 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004795 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004796 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004797 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004798 }
4799
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004800 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004801 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4802 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4803 NetworkRequest nr = nri.request;
4804 if (!nr.isListen()) continue;
4805 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4806 nai.removeRequest(nri.request.requestId);
4807 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4808 }
4809 }
4810
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004811 if (capabilitiesChanged) {
4812 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4813 }
4814
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004815 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4816 NetworkRequest nr = nri.request;
4817 if (!nr.isListen()) continue;
4818 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4819 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004820 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004821 }
4822 }
4823 }
4824
Paul Jensen2161a8e2014-09-11 11:00:39 -04004825 // Handles a network appearing or improving its score.
4826 //
4827 // - Evaluates all current NetworkRequests that can be
4828 // satisfied by newNetwork, and reassigns to newNetwork
4829 // any such requests for which newNetwork is the best.
4830 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004831 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004832 // needed. A network is needed if it is the best network for
4833 // one or more NetworkRequests, or if it is a VPN.
4834 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004835 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004836 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004837 //
4838 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4839 // networks that have no chance (i.e. even if validated)
4840 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004841 //
4842 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4843 // it does not remove NetworkRequests that other Networks could better satisfy.
4844 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4845 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4846 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004847 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004848 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004849 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4850 // performed to tear down unvalidated networks that have no chance (i.e. even if
4851 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004852 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004853 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004854 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004855 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004856 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004857 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004858
4859 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4860 final int score = newNetwork.getCurrentScore();
4861
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004862 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004863
Paul Jensen2161a8e2014-09-11 11:00:39 -04004864 // Find and migrate to this Network any NetworkRequests for
4865 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004866 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004867 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004868 NetworkCapabilities nc = newNetwork.networkCapabilities;
4869 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004870 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004871 // Process requests in the first pass and listens in the second pass. This allows us to
4872 // change a network's capabilities depending on which requests it has. This is only
4873 // correct if the change in capabilities doesn't affect whether the network satisfies
4874 // requests or not, and doesn't affect the network's score.
4875 if (nri.request.isListen()) continue;
4876
Paul Jensencf4c2c62015-07-01 14:16:32 -04004877 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4878 final boolean satisfies = newNetwork.satisfies(nri.request);
4879 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004880 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004881 log("Network " + newNetwork.name() + " was already satisfying" +
4882 " request " + nri.request.requestId + ". No change.");
4883 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004884 keep = true;
4885 continue;
4886 }
4887
4888 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004889 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004890 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004891 // next check if it's better than any current network we're using for
4892 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004893 if (VDBG) {
4894 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004895 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004896 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004897 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004898 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004899 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004900 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004901 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004902 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004903 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004904 affectedNetworks.add(currentNetwork);
4905 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004906 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004907 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004908 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004909 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004910 if (!newNetwork.addRequest(nri.request)) {
4911 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4912 }
4913 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004914 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004915 // Tell NetworkFactories about the new score, so they can stop
4916 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004917 // TODO - this could get expensive if we have alot of requests for this
4918 // network. Think about if there is a way to reduce this. Push
4919 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004920 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004921 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004922 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004923 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004924 if (currentNetwork != null) {
4925 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4926 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004927 }
4928 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004929 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004930 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4931 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004932 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004933 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4934 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4935 // This means this code doesn't have to handle the case where "currentNetwork" no
4936 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4937 if (DBG) {
4938 log("Network " + newNetwork.name() + " stopped satisfying" +
4939 " request " + nri.request.requestId);
4940 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004941 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004942 if (currentNetwork == newNetwork) {
4943 mNetworkForRequestId.remove(nri.request.requestId);
4944 sendUpdatedScoreToFactories(nri.request, 0);
4945 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004946 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4947 newNetwork.name() +
4948 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004949 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004950 // TODO: Technically, sending CALLBACK_LOST here is
4951 // incorrect if there is a replacement network currently
4952 // connected that can satisfy nri, which is a request
4953 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004954 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4955 // so this code is only incorrect for a network that loses
4956 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004957 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004958 }
4959 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004960 if (isNewDefault) {
4961 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004962 makeDefault(newNetwork);
4963 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4964 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Hugo Benichi4c31b342017-03-30 23:18:10 +09004965 // Have a new default network, release the transition wakelock in
4966 scheduleReleaseNetworkTransitionWakelock();
Paul Jensencf4c2c62015-07-01 14:16:32 -04004967 }
4968
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004969 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4970 Slog.wtf(TAG, String.format(
4971 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
Andreas Gamped4f64c42017-07-11 15:14:41 -07004972 newNetwork.name(), nc, newNetwork.networkCapabilities));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004973 }
4974 if (newNetwork.getCurrentScore() != score) {
4975 Slog.wtf(TAG, String.format(
4976 "BUG: %s changed score during rematch: %d -> %d",
liangweikang@xiaomi.come9a7c262017-06-29 14:36:30 +08004977 newNetwork.name(), score, newNetwork.getCurrentScore()));
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004978 }
4979
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004980 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004981 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4982 // If the network went from background to foreground or vice versa, we need to update
4983 // its foreground state. It is safe to do this after rematching the requests because
4984 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4985 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004986 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004987 } else {
4988 processListenRequests(newNetwork, false);
4989 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004990
Paul Jensencf4c2c62015-07-01 14:16:32 -04004991 // do this after the default net is switched, but
4992 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09004993 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004994
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004995 // Linger any networks that are no longer needed. This should be done after sending the
4996 // available callback for newNetwork.
4997 for (NetworkAgentInfo nai : affectedNetworks) {
4998 updateLingerState(nai, now);
4999 }
5000 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
5001 // does not need to be done in any particular order.
5002 updateLingerState(newNetwork, now);
5003
Paul Jensencf4c2c62015-07-01 14:16:32 -04005004 if (isNewDefault) {
5005 // Maintain the illusion: since the legacy API only
5006 // understands one network at a time, we must pretend
5007 // that the current default network disconnected before
5008 // the new one connected.
5009 if (oldDefaultNetwork != null) {
5010 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
5011 oldDefaultNetwork, true);
5012 }
5013 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
5014 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
5015 notifyLockdownVpn(newNetwork);
5016 }
5017
Robert Greenwalt7b816022014-04-18 15:25:25 -07005018 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005019 // Notify battery stats service about this network, both the normal
5020 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04005021 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07005022 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07005023 final IBatteryStats bs = BatteryStatsService.getService();
5024 final int type = newNetwork.networkInfo.getType();
5025
5026 final String baseIface = newNetwork.linkProperties.getInterfaceName();
5027 bs.noteNetworkInterfaceType(baseIface, type);
5028 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
5029 final String stackedIface = stacked.getInterfaceName();
5030 bs.noteNetworkInterfaceType(stackedIface, type);
5031 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
5032 }
5033 } catch (RemoteException ignored) {
5034 }
5035
Robert Greenwalt152ed372014-12-17 17:19:53 -08005036 // This has to happen after the notifyNetworkCallbacks as that tickles each
5037 // ConnectivityManager instance so that legacy requests correctly bind dns
5038 // requests to this network. The legacy users are listening for this bcast
5039 // and will generally do a dns request so they can ensureRouteToHost and if
5040 // they do that before the callbacks happen they'll use the default network.
5041 //
5042 // TODO: Is there still a race here? We send the broadcast
5043 // after sending the callback, but if the app can receive the
5044 // broadcast before the callback, it might still break.
5045 //
5046 // This *does* introduce a race where if the user uses the new api
5047 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
5048 // they may get old info. Reverse this after the old startUsing api is removed.
5049 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005050 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
5051 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09005052 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08005053 // legacy type tracker filters out repeat adds
5054 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
5055 }
5056 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07005057
5058 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
5059 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
5060 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
5061 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
5062 if (newNetwork.isVPN()) {
5063 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
5064 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005065 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005066 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
5067 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09005068 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005069 if (nai.getLingerExpiry() > 0) {
5070 // This network has active linger timers and no requests, but is not
5071 // lingering. Linger it.
5072 //
5073 // One way (the only way?) this can happen if this network is unvalidated
5074 // and became unneeded due to another network improving its score to the
5075 // point where this network will no longer be able to satisfy any requests
5076 // even if it validates.
5077 updateLingerState(nai, now);
5078 } else {
5079 if (DBG) log("Reaping " + nai.name());
5080 teardownUnneededNetwork(nai);
5081 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05005082 }
5083 }
5084 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005085 }
5086
Paul Jensen1c7ba022015-06-16 14:27:36 -04005087 /**
5088 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
5089 * being disconnected.
5090 * @param changed If only one Network's score or capabilities have been modified since the last
5091 * time this function was called, pass this Network in this argument, otherwise pass
5092 * null.
5093 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5094 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5095 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5096 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5097 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005098 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005099 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005100 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5101 // to avoid the slowness. It is not simply enough to process just "changed", for
5102 // example in the case where "changed"'s score decreases and another network should begin
5103 // satifying a NetworkRequest that "changed" currently satisfies.
5104
5105 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5106 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5107 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005108 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005109 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005110 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005111 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005112 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5113 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5114 // Rematch higher scoring networks first to prevent requests first matching a lower
5115 // scoring network and then a higher scoring network, which could produce multiple
5116 // callbacks and inadvertently unlinger networks.
5117 Arrays.sort(nais);
5118 for (NetworkAgentInfo nai : nais) {
5119 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005120 // Only reap the last time through the loop. Reaping before all rematching
5121 // is complete could incorrectly teardown a network that hasn't yet been
5122 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005123 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005124 : ReapUnvalidatedNetworks.REAP,
5125 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005126 }
5127 }
5128 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005129
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005130 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005131 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005132 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005133 // For now only update icons for default connection.
5134 // TODO: Update WiFi and cellular icons separately. b/17237507
5135 if (!isDefaultNetwork(nai)) return;
5136
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005137 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005138 // Don't repeat publish.
5139 if (newInetCondition == mDefaultInetConditionPublished) return;
5140
5141 mDefaultInetConditionPublished = newInetCondition;
5142 sendInetConditionBroadcast(nai.networkInfo);
5143 }
5144
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005145 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5146 if (mLockdownTracker != null) {
5147 if (nai != null && nai.isVPN()) {
5148 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5149 } else {
5150 mLockdownTracker.onNetworkInfoChanged();
5151 }
5152 }
5153 }
5154
Robert Greenwalt7b816022014-04-18 15:25:25 -07005155 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005156 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005157 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005158 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005159 synchronized (networkAgent) {
5160 oldInfo = networkAgent.networkInfo;
5161 networkAgent.networkInfo = newInfo;
5162 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005163 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005164
5165 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005166 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5167 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5168 notifyIfacesChangedForNetworkStats();
5169 } else if (VDBG) log("ignoring duplicate network state non-change");
5170 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005171 return;
5172 }
5173 if (DBG) {
5174 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5175 (oldInfo == null ? "null" : oldInfo.getState()) +
5176 " to " + state);
5177 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005178
Robin Lee585e2482016-05-01 23:00:00 +01005179 if (!networkAgent.created
5180 && (state == NetworkInfo.State.CONNECTED
5181 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005182
5183 // A network that has just connected has zero requests and is thus a foreground network.
5184 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5185
Robert Greenwalt7b816022014-04-18 15:25:25 -07005186 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005187 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005188 if (networkAgent.isVPN()) {
5189 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005190 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5191 (networkAgent.networkMisc == null ||
5192 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005193 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005194 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005195 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005196 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005197 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005198 loge("Error creating network " + networkAgent.network.netId + ": "
5199 + e.getMessage());
5200 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005201 }
Paul Jenseneec75412014-08-04 12:21:19 -04005202 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005203 }
5204
5205 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5206 networkAgent.everConnected = true;
5207
Robert Greenwalt7b816022014-04-18 15:25:25 -07005208 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005209 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005210
Paul Jensenca8f16a2014-05-09 12:47:55 -04005211 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005212 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005213
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005214 if (networkAgent.isVPN()) {
5215 // Temporarily disable the default proxy (not global).
5216 synchronized (mProxyLock) {
5217 if (!mDefaultProxyDisabled) {
5218 mDefaultProxyDisabled = true;
5219 if (mGlobalProxy == null && mDefaultProxy != null) {
5220 sendProxyBroadcast(null);
5221 }
5222 }
5223 }
5224 // TODO: support proxy per network.
5225 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005226
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005227 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5228 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5229 // capabilities, so it only needs to be done once on initial connect, not every time the
5230 // network's capabilities change. Note that we do this before rematching the network,
5231 // so we could decide to tear it down immediately afterwards. That's fine though - on
5232 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5233 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005234 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005235
Paul Jensen2161a8e2014-09-11 11:00:39 -04005236 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005237 final long now = SystemClock.elapsedRealtime();
5238 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005239
5240 // This has to happen after matching the requests, because callbacks are just requests.
5241 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005242 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005243 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005244 if (networkAgent.isVPN()) {
5245 synchronized (mProxyLock) {
5246 if (mDefaultProxyDisabled) {
5247 mDefaultProxyDisabled = false;
5248 if (mGlobalProxy == null && mDefaultProxy != null) {
5249 sendProxyBroadcast(mDefaultProxy);
5250 }
5251 }
5252 }
5253 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005254 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5255 state == NetworkInfo.State.SUSPENDED) {
5256 // going into or coming out of SUSPEND: rescore and notify
5257 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005258 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005259 }
5260 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5261 ConnectivityManager.CALLBACK_SUSPENDED :
5262 ConnectivityManager.CALLBACK_RESUMED));
5263 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005264 }
5265 }
5266
Robert Greenwaltac96c522014-06-03 16:43:57 -07005267 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005268 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005269 if (score < 0) {
5270 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5271 "). Bumping score to min of 0");
5272 score = 0;
5273 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005274
Paul Jensen2161a8e2014-09-11 11:00:39 -04005275 final int oldScore = nai.getCurrentScore();
5276 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005277
Paul Jensen85cf78e2015-06-25 13:25:07 -04005278 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005279
Paul Jensenc8b9a742014-09-30 15:37:41 -04005280 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005281 }
5282
Erik Klinec75d4fa2017-02-15 19:59:17 +09005283 // Notify only this one new request of the current state. Transfer all the
5284 // current state by calling NetworkCapabilities and LinkProperties callbacks
5285 // so that callers can be guaranteed to have as close to atomicity in state
5286 // transfer as can be supported by this current API.
5287 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005288 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005289 if (nri.mPendingIntent != null) {
5290 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5291 // Attempt no subsequent state pushes where intents are involved.
5292 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005293 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005294
5295 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5296 // Whether a network is currently suspended is also an important
5297 // element of state to be transferred (it would not otherwise be
5298 // delivered by any currently available mechanism).
5299 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5300 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5301 }
5302 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5303 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005304 }
5305
Robert Greenwalt8d482522015-06-24 13:23:42 -07005306 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005307 // The NetworkInfo we actually send out has no bearing on the real
5308 // state of affairs. For example, if the default connection is mobile,
5309 // and a request for HIPRI has just gone away, we need to pretend that
5310 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5311 // the state to DISCONNECTED, even though the network is of type MOBILE
5312 // and is still connected.
5313 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5314 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005315 if (state != DetailedState.DISCONNECTED) {
5316 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005317 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005318 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005319 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005320 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5321 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5322 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5323 if (info.isFailover()) {
5324 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5325 nai.networkInfo.setFailover(false);
5326 }
5327 if (info.getReason() != null) {
5328 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5329 }
5330 if (info.getExtraInfo() != null) {
5331 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5332 }
5333 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005334 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005335 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005336 if (newDefaultAgent != null) {
5337 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5338 newDefaultAgent.networkInfo);
5339 } else {
5340 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5341 }
5342 }
5343 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5344 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005345 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005346 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005347 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005348 }
5349 }
5350 }
5351
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005352 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Hugo Benichia0385682017-03-22 17:07:57 +09005353 if (VDBG) {
5354 String notification = ConnectivityManager.getCallbackName(notifyType);
5355 log("notifyType " + notification + " for " + networkAgent.name());
5356 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005357 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5358 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005359 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5360 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005361 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5362 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005363 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005364 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005365 } else {
5366 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5367 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005368 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005369 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005370
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005371 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5372 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5373 }
5374
Jeff Sharkey69736342014-12-08 14:50:12 -08005375 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005376 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5377 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005378 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005379 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005380 try {
5381 mStatsService.forceUpdateIfaces();
5382 } catch (Exception ignored) {
5383 }
5384 }
5385
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005386 @Override
5387 public boolean addVpnAddress(String address, int prefixLength) {
5388 throwIfLockdownEnabled();
5389 int user = UserHandle.getUserId(Binder.getCallingUid());
5390 synchronized (mVpns) {
5391 return mVpns.get(user).addAddress(address, prefixLength);
5392 }
5393 }
5394
5395 @Override
5396 public boolean removeVpnAddress(String address, int prefixLength) {
5397 throwIfLockdownEnabled();
5398 int user = UserHandle.getUserId(Binder.getCallingUid());
5399 synchronized (mVpns) {
5400 return mVpns.get(user).removeAddress(address, prefixLength);
5401 }
5402 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005403
5404 @Override
5405 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5406 throwIfLockdownEnabled();
5407 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005408 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005409 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005410 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005411 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005412 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005413 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005414 }
5415 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005416 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005417
5418 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005419 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005420 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005421 }
5422
5423 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005424 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5425 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5426 enforceKeepalivePermission();
5427 mKeepaliveTracker.startNattKeepalive(
5428 getNetworkAgentInfoForNetwork(network),
5429 intervalSeconds, messenger, binder,
5430 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5431 }
5432
5433 @Override
5434 public void stopKeepalive(Network network, int slot) {
5435 mHandler.sendMessage(mHandler.obtainMessage(
5436 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5437 }
5438
5439 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005440 public void factoryReset() {
5441 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005442
5443 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5444 return;
5445 }
5446
Robin Lee3b3dd942015-05-12 18:14:58 +01005447 final int userId = UserHandle.getCallingUserId();
5448
Stuart Scottf1fb3972015-04-02 18:00:02 -07005449 // Turn airplane mode off
5450 setAirplaneMode(false);
5451
Stuart Scotte3e314d2015-04-20 14:07:45 -07005452 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5453 // Untether
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005454 String pkgName = mContext.getOpPackageName();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005455 for (String tether : getTetheredIfaces()) {
Tetsutoki Shiozawa335d2ed2016-03-16 23:30:57 +09005456 untether(tether, pkgName);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005457 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005458 }
5459
Stuart Scotte3e314d2015-04-20 14:07:45 -07005460 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005461 // Remove always-on package
5462 synchronized (mVpns) {
5463 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5464 if (alwaysOnPackage != null) {
5465 setAlwaysOnVpnPackage(userId, null, false);
5466 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5467 }
5468 }
5469
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005470 // Turn Always-on VPN off
5471 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5472 final long ident = Binder.clearCallingIdentity();
5473 try {
5474 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5475 mLockdownEnabled = false;
5476 setLockdownTracker(null);
5477 } finally {
5478 Binder.restoreCallingIdentity(ident);
5479 }
5480 }
5481
Stuart Scotte3e314d2015-04-20 14:07:45 -07005482 // Turn VPN off
5483 VpnConfig vpnConfig = getVpnConfig(userId);
5484 if (vpnConfig != null) {
5485 if (vpnConfig.legacy) {
5486 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5487 } else {
5488 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5489 // in the future without user intervention.
5490 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005491
Victor Changb04a5ea2016-05-30 20:36:30 +01005492 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005493 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005494 }
5495 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005496
5497 Settings.Global.putString(mContext.getContentResolver(),
5498 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005499 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005500
5501 @VisibleForTesting
5502 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5503 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5504 return new NetworkMonitor(context, handler, nai, defaultRequest);
5505 }
Erik Kline48f12f22016-04-14 17:30:59 +09005506
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005507 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005508 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5509 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005510 }
5511
5512 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005513 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5514 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5515 }
5516
Hugo Benichicfddd682016-05-31 16:28:06 +09005517 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005518 int newNetid = NETID_UNSET;
5519 int prevNetid = NETID_UNSET;
5520 int[] transports = new int[0];
5521 boolean hadIPv4 = false;
5522 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005523
Hugo Benichi5f16f762016-04-20 12:09:33 +09005524 if (newNai != null) {
5525 newNetid = newNai.network.netId;
5526 transports = newNai.networkCapabilities.getTransportTypes();
5527 }
5528 if (prevNai != null) {
5529 prevNetid = prevNai.network.netId;
5530 final LinkProperties lp = prevNai.linkProperties;
5531 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5532 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5533 }
5534
Hugo Benichicfddd682016-05-31 16:28:06 +09005535 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5536 }
5537
5538 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5539 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005540 }
Hugo Benichiab7d2e62017-04-21 15:07:12 +09005541
5542 private static boolean toBool(int encodedBoolean) {
5543 return encodedBoolean != 0; // Only 0 means false.
5544 }
5545
5546 private static int encodeBool(boolean b) {
5547 return b ? 1 : 0;
5548 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005549}