blob: 50c0a124fb8a3edf443a3983f29f9e9d7ea82892 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Paul Jensen3d194ea2015-06-16 14:27:36 -040026import static android.net.NetworkCapabilities.NET_CAPABILITY_CAPTIVE_PORTAL;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_FOREGROUND;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090028import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
31import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -060032
Wenchao Tongf5ea3402015-03-04 13:26:38 -080033import android.annotation.Nullable;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080034import android.app.BroadcastOptions;
Lorenzo Colitti0b599062016-08-22 22:36:19 +090035import android.app.NotificationManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070036import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070037import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080038import android.content.ContentResolver;
39import android.content.Context;
40import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070041import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070043import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090044import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070045import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090047import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070049import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070050import android.net.INetworkPolicyListener;
51import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070052import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080053import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070054import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070055import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070056import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070057import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070058import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080059import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070060import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070061import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070062import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070063import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070064import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070065import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070066import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040067import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070068import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040069import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040070import android.net.Uri;
Hugo Benichi5f16f762016-04-20 12:09:33 +090071import android.net.metrics.DefaultNetworkEvent;
Hugo Benichicfddd682016-05-31 16:28:06 +090072import android.net.metrics.IpConnectivityLog;
Hugo Benichicc92c6e2016-04-21 15:02:38 +090073import android.net.metrics.NetworkEvent;
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +090074import android.net.util.MultinetworkPolicyTracker;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080076import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070077import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040078import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070080import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070082import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Looper;
84import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070085import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070086import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070087import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070088import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.os.RemoteException;
Jeremy Klein36c7aa02016-01-22 14:11:45 -080090import android.os.ResultReceiver;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +090091import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070093import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040094import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070096import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070097import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070098import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070099import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700100import android.util.LocalLog;
101import android.util.LocalLog.ReadOnlyLocalLog;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600102import android.util.Log;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700103import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800104import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700105import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500106import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700107import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700108import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800109
Wink Savilleab9321d2013-06-29 21:10:57 -0700110import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400111import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400112import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700113import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700114import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700115import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700116import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800117import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700118import com.android.internal.net.VpnProfile;
Robert Greenwalte049c232014-04-11 15:53:27 -0700119import com.android.internal.util.AsyncChannel;
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -0600120import com.android.internal.util.DumpUtils;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700121import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900122import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900123import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700124import com.android.internal.util.XmlUtils;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900125import com.android.server.LocalServices;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700126import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400127import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900128import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700129import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900130import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900131import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700132import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600133import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400134import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900135import com.android.server.connectivity.NetworkNotificationManager;
136import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400137import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700138import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800139import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700140import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700141import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700142import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900143import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600144
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700145import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700146
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700147import org.xmlpull.v1.XmlPullParser;
148import org.xmlpull.v1.XmlPullParserException;
149
150import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700152import java.io.FileNotFoundException;
153import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700154import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700156import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700157import java.net.InetAddress;
158import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700159import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700160import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700161import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700162import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700163import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700164import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700165import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700166import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700167import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600168import java.util.SortedSet;
169import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
171/**
172 * @hide
173 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800174public class ConnectivityService extends IConnectivityManager.Stub
175 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900176 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800177
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900178 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700179 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800180
Jake Hamby786e71a2014-02-06 14:43:50 -0800181 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900182 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700183
Jeff Sharkey899223b2012-08-04 15:24:58 -0700184 // TODO: create better separation between radio types and network types
185
Robert Greenwalt42acef32009-08-12 16:08:25 -0700186 // how long to wait before switching back to a radio's default network
187 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
188 // system property that can override the above value
189 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
190 "android.telephony.apn-restore";
191
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900192 // How long to wait before putting up a "This network doesn't have an Internet connection,
193 // connect anyway?" dialog after the user selects a network that doesn't validate.
194 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
195
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900196 // Default to 30s linger time-out. Modifiable only for testing.
197 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
198 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
199 @VisibleForTesting
200 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
201
Jeremy Joslin79294842014-12-03 17:15:28 -0800202 // How long to delay to removal of a pending intent based request.
203 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
204 private final int mReleasePendingIntentDelayMs;
205
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800206 private Tethering mTethering;
207
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700208 private final PermissionMonitor mPermissionMonitor;
209
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700210 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700211
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700212 @GuardedBy("mVpns")
213 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700214
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700215 private boolean mLockdownEnabled;
216 private LockdownVpnTracker mLockdownTracker;
217
Erik Klineda4bfa82015-04-30 12:58:40 +0900218 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700220 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700221 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800222
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800223 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800224
225 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700226 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800227
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700228 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800229 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700230 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900231 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700232
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700233 private String mCurrentTcpBufferSizes;
234
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700235 private static final int ENABLED = 1;
236 private static final int DISABLED = 0;
237
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900238 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900239 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
240 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900241
Paul Jensenb10e37f2014-11-25 12:33:08 -0500242 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400243 // Tear down networks that have no chance (e.g. even if validated) of becoming
244 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500245 // all networks have been rematched against all NetworkRequests.
246 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400247 // Don't reap networks. This should be passed when some networks have not yet been
248 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500249 DONT_REAP
250 };
251
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900252 private enum UnneededFor {
253 LINGER, // Determine whether this network is unneeded and should be lingered.
254 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
255 }
256
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700257 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700258 * used internally to change our mobile data enabled flag
259 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700260 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700261
262 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700263 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700264 * from one net to another. Clear happens when we get a new
265 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
266 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700267 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700268 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700269
Robert Greenwalt434203a2010-10-11 16:00:27 -0700270 /**
271 * used internally to reload global proxy settings
272 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700273 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700274
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700275 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400276 * PAC manager has received new port.
277 */
278 private static final int EVENT_PROXY_HAS_CHANGED = 16;
279
Robert Greenwalte049c232014-04-11 15:53:27 -0700280 /**
281 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700282 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700283 */
284 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
285
Robert Greenwalt7b816022014-04-18 15:25:25 -0700286 /**
287 * used internally when registering NetworkAgents
288 * obj = Messenger
289 */
290 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
291
Robert Greenwalt9258c642014-03-26 16:47:06 -0700292 /**
293 * used to add a network request
294 * includes a NetworkRequestInfo
295 */
296 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
297
298 /**
299 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900300 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 * cancel it.
302 * includes a NetworkRequestInfo
303 */
304 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
305
306 /**
307 * used to add a network listener - no request
308 * includes a NetworkRequestInfo
309 */
310 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
311
312 /**
313 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400314 * arg1 = UID of caller
315 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700316 */
317 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
318
Robert Greenwalta67be032014-05-16 15:49:14 -0700319 /**
320 * used internally when registering NetworkFactories
321 * obj = Messenger
322 */
323 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
324
Robert Greenwalt27711812014-06-25 16:45:57 -0700325 /**
326 * used internally to expire a wakelock when transitioning
327 * from one net to another. Expire happens when we fail to find
328 * a new network (typically after 1 minute) -
329 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
330 * a replacement network.
331 */
332 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
333
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700334 /**
335 * Used internally to indicate the system is ready.
336 */
337 private static final int EVENT_SYSTEM_READY = 25;
338
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800339 /**
340 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400341 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800342 */
343 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
344
345 /**
346 * used to remove a pending intent and its associated network request.
347 * arg1 = UID of caller
348 * obj = PendingIntent
349 */
350 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
351
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900352 /**
353 * used to specify whether a network should be used even if unvalidated.
354 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
355 * arg2 = whether to remember this choice in the future (1 or 0)
356 * obj = network
357 */
358 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
359
360 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900361 * used to specify whether a network should not be penalized when it becomes unvalidated.
362 */
363 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
364
365 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900366 * used to ask the user to confirm a connection to an unvalidated network.
367 * obj = network
368 */
369 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700370
Erik Klineda4bfa82015-04-30 12:58:40 +0900371 /**
372 * used internally to (re)configure mobile data always-on settings.
373 */
374 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
375
Paul Jensen694f2b82015-06-17 14:15:39 -0400376 /**
377 * used to add a network listener with a pending intent
378 * obj = NetworkRequestInfo
379 */
380 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
381
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900382 /** Handler thread used for both of the handlers below. */
383 @VisibleForTesting
384 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700385 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700386 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700387 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700388 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700389
Mike Lockwood0f79b542009-08-14 14:18:49 -0400390 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800391 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400392
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700393 private PowerManager.WakeLock mNetTransitionWakeLock;
394 private String mNetTransitionWakeLockCausedBy = "";
395 private int mNetTransitionWakeLockSerialNumber;
396 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800397 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700398
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700399 // used in DBG mode to track inet condition reports
400 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
401 private ArrayList mInetLog;
402
Robert Greenwalt434203a2010-10-11 16:00:27 -0700403 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400404 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700405 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700406 private boolean mDefaultProxyDisabled = false;
407
Robert Greenwalt434203a2010-10-11 16:00:27 -0700408 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400409 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700410
Jason Monk602b2322013-07-03 17:04:33 -0400411 private PacManager mPacManager = null;
412
Erik Klineda4bfa82015-04-30 12:58:40 +0900413 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700414
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400415 private UserManager mUserManager;
416
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700417 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700418 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700419
Robert Greenwalt50393202011-06-21 17:26:14 -0700420 // the set of network types that can only be enabled by system/sig apps
421 List mProtectedNetworks;
422
John Spurlockbf991a82013-06-24 14:20:23 -0400423 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700424
Wink Savilleab9321d2013-06-29 21:10:57 -0700425 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400426
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900427 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900428 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900429 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900430
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700431 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
432 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700433 private final static int MAX_NET_ID = 65535;
434 private int mNextNetId = MIN_NET_ID;
435
Robert Greenwalt34524f02014-05-18 16:22:10 -0700436 // sequence number of NetworkRequests
437 private int mNextNetworkRequestId = 1;
438
Erik Kline7523eb32015-07-09 18:24:03 +0900439 // NetworkRequest activity String log entries.
440 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
441 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
442
Hugo Benichic2ae2872016-07-11 11:05:12 +0900443 // NetworkInfo blocked and unblocked String log entries
444 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
445 private static final int MAX_NETWORK_INFO_LOGS = 100;
446 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
447
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700448 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
449 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400450 private static class ValidationLog {
451 final Network mNetwork;
452 final String mNetworkExtraInfo;
453 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700454
Paul Jensen0808eb82016-06-03 13:51:21 -0400455 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
456 mNetwork = network;
457 mNetworkExtraInfo = networkExtraInfo;
458 mLog = log;
459 }
460 }
461 private final ArrayDeque<ValidationLog> mValidationLogs =
462 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
463
464 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700465 synchronized(mValidationLogs) {
466 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
467 mValidationLogs.removeLast();
468 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400469 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700470 }
471 }
472
Hugo Benichif9fdf872016-07-28 17:53:06 +0900473 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900474
Erik Kline065ab6e2016-10-02 18:02:14 +0900475 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900476 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900477
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700478 /**
479 * Implements support for the legacy "one network per network type" model.
480 *
481 * We used to have a static array of NetworkStateTrackers, one for each
482 * network type, but that doesn't work any more now that we can have,
483 * for example, more that one wifi network. This class stores all the
484 * NetworkAgentInfo objects that support a given type, but the legacy
485 * API will only see the first one.
486 *
487 * It serves two main purposes:
488 *
489 * 1. Provide information about "the network for a given type" (since this
490 * API only supports one).
491 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
492 * the first network for a given type changes, or if the default network
493 * changes.
494 */
495 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900496
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900497 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900499
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700500 /**
501 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
502 * Each list holds references to all NetworkAgentInfos that are used to
503 * satisfy requests for that network type.
504 *
505 * This array is built out at startup such that an unsupported network
506 * doesn't get an ArrayList instance, making this a tristate:
507 * unsupported, supported but not active and active.
508 *
509 * The actual lists are populated when we scan the network types that
510 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900511 *
512 * Threading model:
513 * - addSupportedType() is only called in the constructor
514 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
515 * They are therefore not thread-safe with respect to each other.
516 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
517 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
518 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700519 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900520 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700521
522 public LegacyTypeTracker() {
523 mTypeLists = (ArrayList<NetworkAgentInfo>[])
524 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
525 }
526
527 public void addSupportedType(int type) {
528 if (mTypeLists[type] != null) {
529 throw new IllegalStateException(
530 "legacy list for type " + type + "already initialized");
531 }
532 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
533 }
534
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700535 public boolean isTypeSupported(int type) {
536 return isNetworkTypeValid(type) && mTypeLists[type] != null;
537 }
538
539 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900540 synchronized (mTypeLists) {
541 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
542 return mTypeLists[type].get(0);
543 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700544 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900545 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700546 }
547
Robert Greenwalt8d482522015-06-24 13:23:42 -0700548 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900549 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900550 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700551 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900553 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900554 }
555 }
556
557 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700558 public void add(int type, NetworkAgentInfo nai) {
559 if (!isTypeSupported(type)) {
560 return; // Invalid network type.
561 }
562 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
563
564 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
565 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700566 return;
567 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900568 synchronized (mTypeLists) {
569 list.add(nai);
570 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900571
572 // 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 +0900573 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900574 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700575 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
576 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700577 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700578 }
579
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900581 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900582 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
583 if (list == null || list.isEmpty()) {
584 return;
585 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900586 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900587
Hugo Benichi78caa2582016-06-21 09:48:07 +0900588 synchronized (mTypeLists) {
589 if (!list.remove(nai)) {
590 return;
591 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592 }
593
Robert Greenwalt8d482522015-06-24 13:23:42 -0700594 final DetailedState state = DetailedState.DISCONNECTED;
595
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900596 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700597 maybeLogBroadcast(nai, state, type, wasDefault);
598 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900599 }
600
601 if (!list.isEmpty() && wasFirstNetwork) {
602 if (DBG) log("Other network available for type " + type +
603 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900604 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700605 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
606 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900607 }
608 }
609
610 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900611 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
612 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700613 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900614 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700615 }
616 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700617
Robert Greenwalt8d482522015-06-24 13:23:42 -0700618 // send out another legacy broadcast - currently only used for suspend/unsuspend
619 // toggle
620 public void update(NetworkAgentInfo nai) {
621 final boolean isDefault = isDefaultNetwork(nai);
622 final DetailedState state = nai.networkInfo.getDetailedState();
623 for (int type = 0; type < mTypeLists.length; type++) {
624 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700625 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900626 final boolean isFirst = contains && (nai == list.get(0));
627 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700628 maybeLogBroadcast(nai, state, type, isDefault);
629 sendLegacyNetworkBroadcast(nai, state, type);
630 }
631 }
632 }
633
Lorenzo Colittia793a672014-07-31 23:20:17 +0900634 private String naiToString(NetworkAgentInfo nai) {
635 String name = (nai != null) ? nai.name() : "null";
636 String state = (nai.networkInfo != null) ?
637 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
638 "???/???";
639 return name + " " + state;
640 }
641
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700642 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900643 pw.println("mLegacyTypeTracker:");
644 pw.increaseIndent();
645 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700646 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900647 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700648 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900649 pw.println();
650 pw.println("Current state:");
651 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900652 synchronized (mTypeLists) {
653 for (int type = 0; type < mTypeLists.length; type++) {
654 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
655 for (NetworkAgentInfo nai : mTypeLists[type]) {
656 pw.println(type + " " + naiToString(nai));
657 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900658 }
659 }
660 pw.decreaseIndent();
661 pw.decreaseIndent();
662 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700663 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700664 }
665 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
666
Jeff Sharkey899223b2012-08-04 15:24:58 -0700667 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700668 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900669 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
670 }
671
672 @VisibleForTesting
673 protected ConnectivityService(Context context, INetworkManagementService netManager,
674 INetworkStatsService statsService, INetworkPolicyManager policyManager,
675 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800676 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800677
Hugo Benichif9fdf872016-07-28 17:53:06 +0900678 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900679 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900680 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900681 mNetworkRequests.put(mDefaultRequest, defaultNRI);
682 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900683
684 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900685 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700686
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900687 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900688 mHandlerThread.start();
689 mHandler = new InternalHandler(mHandlerThread.getLooper());
690 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700691
Jeremy Joslin79294842014-12-03 17:15:28 -0800692 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
693 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
694
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900695 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
696
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700697 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700698 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800699 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700700 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900701 mPolicyManagerInternal = checkNotNull(
702 LocalServices.getService(NetworkPolicyManagerInternal.class),
703 "missing NetworkPolicyManagerInternal");
704
Jeff Sharkey82f85212012-08-24 11:17:25 -0700705 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700706 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700707
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700708 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900709 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700710 } catch (RemoteException e) {
711 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700712 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700713 }
714
715 final PowerManager powerManager = (PowerManager) context.getSystemService(
716 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700717 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
718 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
719 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800720 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700721
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700722 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700723
Wink Saville51f456f2013-04-23 14:26:51 -0700724 // TODO: What is the "correct" way to do determine if this is a wifi only device?
725 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
726 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700727 String[] naStrings = context.getResources().getStringArray(
728 com.android.internal.R.array.networkAttributes);
729 for (String naString : naStrings) {
730 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700731 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700732 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700733 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800734 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700735 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700736 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700737 }
Wink Saville51f456f2013-04-23 14:26:51 -0700738 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
739 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
740 n.type);
741 continue;
742 }
Wink Saville975c8482011-04-07 14:23:45 -0700743 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800744 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700745 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700746 continue;
747 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700748 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700749
Wink Saville975c8482011-04-07 14:23:45 -0700750 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700751 mNetworksDefined++;
752 } catch(Exception e) {
753 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700754 }
755 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700756
757 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
758 if (mNetConfigs[TYPE_VPN] == null) {
759 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
760 // don't need to add TYPE_VPN to mNetConfigs.
761 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
762 mNetworksDefined++; // used only in the log() statement below.
763 }
764
Wink Saville5e56bc52013-07-29 15:00:57 -0700765 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700766
Robert Greenwalt50393202011-06-21 17:26:14 -0700767 mProtectedNetworks = new ArrayList<Integer>();
768 int[] protectedNetworks = context.getResources().getIntArray(
769 com.android.internal.R.array.config_protectedNetworks);
770 for (int p : protectedNetworks) {
771 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
772 mProtectedNetworks.add(p);
773 } else {
774 if (DBG) loge("Ignoring protectedNetwork " + p);
775 }
776 }
777
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700778 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
779 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700780
Christopher Wiley497c1472016-10-11 13:26:03 -0700781 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
782 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800783
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700784 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
785
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700786 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700787 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100788 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700789 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700790 intentFilter.addAction(Intent.ACTION_USER_ADDED);
791 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000792 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700793 mContext.registerReceiverAsUser(
794 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000795 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
796 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900797
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700798 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700799 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700800 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700801 } catch (RemoteException e) {
802 loge("Error registering observer :" + e);
803 }
804
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700805 if (DBG) {
806 mInetLog = new ArrayList();
807 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700808
Erik Klineda4bfa82015-04-30 12:58:40 +0900809 mSettingsObserver = new SettingsObserver(mContext, mHandler);
810 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800811
John Spurlockbf991a82013-06-24 14:20:23 -0400812 mDataConnectionStats = new DataConnectionStats(mContext);
813 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400814
Jason Monkdecd2952013-10-10 14:02:51 -0400815 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700816
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400817 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900818
819 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900820 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
821 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900822
823 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
824 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
825 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
826 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
827 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
828 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
829 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900830
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900831 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900832 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900833 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800834 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700835
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900836 private NetworkRequest createInternetRequestForTransport(
837 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900838 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900839 netCap.addCapability(NET_CAPABILITY_INTERNET);
840 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900841 if (transportType > -1) {
842 netCap.addTransportType(transportType);
843 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900844 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900845 }
846
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900847 // Used only for testing.
848 // TODO: Delete this and either:
849 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
850 // changing ContentResolver to make registerContentObserver non-final).
851 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
852 // by subclassing SettingsObserver.
853 @VisibleForTesting
854 void updateMobileDataAlwaysOn() {
855 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
856 }
857
Erik Klineda4bfa82015-04-30 12:58:40 +0900858 private void handleMobileDataAlwaysOn() {
859 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900860 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900861 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
862 if (enable == isEnabled) {
863 return; // Nothing to do.
864 }
865
866 if (enable) {
867 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900868 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900869 } else {
870 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
871 }
872 }
873
874 private void registerSettingsCallbacks() {
875 // Watch for global HTTP proxy changes.
876 mSettingsObserver.observe(
877 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
878 EVENT_APPLY_GLOBAL_HTTP_PROXY);
879
880 // Watch for whether or not to keep mobile data always on.
881 mSettingsObserver.observe(
882 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
883 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
884 }
885
Robert Greenwalt34524f02014-05-18 16:22:10 -0700886 private synchronized int nextNetworkRequestId() {
887 return mNextNetworkRequestId++;
888 }
889
Paul Jensen67b0b072015-06-10 11:22:17 -0400890 @VisibleForTesting
891 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400892 synchronized (mNetworkForNetId) {
893 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
894 int netId = mNextNetId;
895 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
896 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500897 if (!mNetIdInUse.get(netId)) {
898 mNetIdInUse.put(netId, true);
899 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400900 }
901 }
902 }
903 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700904 }
905
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600906 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800907 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600908 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
909 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800910 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600911 state = nai.getNetworkState();
912 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800913 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600914 final NetworkInfo info = new NetworkInfo(networkType, 0,
915 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800916 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
917 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600918 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
919 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800920 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600921 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600922 return state;
923 } else {
924 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800925 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400926 }
927
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800928 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
929 if (network == null) {
930 return null;
931 }
932 synchronized (mNetworkForNetId) {
933 return mNetworkForNetId.get(network.netId);
934 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600935 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900937 private Network[] getVpnUnderlyingNetworks(int uid) {
938 if (!mLockdownEnabled) {
939 int user = UserHandle.getUserId(uid);
940 synchronized (mVpns) {
941 Vpn vpn = mVpns.get(user);
942 if (vpn != null && vpn.appliesToUid(uid)) {
943 return vpn.getUnderlyingNetworks();
944 }
945 }
946 }
947 return null;
948 }
949
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800950 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400951 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800952
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900953 final Network[] networks = getVpnUnderlyingNetworks(uid);
954 if (networks != null) {
955 // getUnderlyingNetworks() returns:
956 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
957 // empty array => the VPN explicitly said "no default network".
958 // non-empty array => the VPN specified one or more default networks; we use the
959 // first one.
960 if (networks.length > 0) {
961 nai = getNetworkAgentInfoForNetwork(networks[0]);
962 } else {
963 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800964 }
965 }
966
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600968 return nai.getNetworkState();
969 } else {
970 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800971 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400972 }
973
974 /**
975 * Check if UID should be blocked from using the network with the given LinkProperties.
976 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600977 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
978 boolean ignoreBlocked) {
979 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900980 if (ignoreBlocked) {
981 return false;
982 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600983 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900984 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
985 if (isSystem(uid)) {
986 return false;
987 }
Robin Lee17e61832016-05-09 13:46:28 +0100988 synchronized (mVpns) {
989 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
990 if (vpn != null && vpn.isBlockingUid(uid)) {
991 return true;
992 }
993 }
Robert Greenwalt12e67352014-05-13 21:41:06 -0700994 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900995 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700996 }
997
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900998 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +0900999 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
1000 return;
1001 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001002 boolean removed = false;
1003 boolean added = false;
1004 synchronized (mBlockedAppUids) {
1005 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1006 added = true;
1007 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1008 removed = true;
1009 }
1010 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001011 if (added) {
1012 log("Returning blocked NetworkInfo to uid=" + uid);
1013 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1014 } else if (removed) {
1015 log("Returning unblocked NetworkInfo to uid=" + uid);
1016 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1017 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001018 }
1019
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001020 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001021 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1022 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1023 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1024 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001025 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001026 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001027 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1028
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001029 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001030 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001031 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001032 if (mLockdownTracker != null) {
1033 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001034 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001035
1036 // TODO: apply metered state closer to NetworkAgentInfo
1037 final long token = Binder.clearCallingIdentity();
1038 try {
1039 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1040 } catch (RemoteException e) {
1041 } finally {
1042 Binder.restoreCallingIdentity(token);
1043 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001044 }
1045
1046 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 * Return NetworkInfo for the active (i.e., connected) network interface.
1048 * It is assumed that at most one network is active at a time. If more
1049 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001050 * @return the info for the active network, or {@code null} if none is
1051 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001052 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001053 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001055 enforceAccessPermission();
1056 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001057 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001058 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001059 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1060 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001061 }
1062
Paul Jensen31a94f42015-02-13 14:18:39 -05001063 @Override
1064 public Network getActiveNetwork() {
1065 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001066 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001067 }
1068
1069 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001070 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001071 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001072 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001073 }
1074
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001075 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001076 final int user = UserHandle.getUserId(uid);
1077 int vpnNetId = NETID_UNSET;
1078 synchronized (mVpns) {
1079 final Vpn vpn = mVpns.get(user);
1080 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1081 }
1082 NetworkAgentInfo nai;
1083 if (vpnNetId != NETID_UNSET) {
1084 synchronized (mNetworkForNetId) {
1085 nai = mNetworkForNetId.get(vpnNetId);
1086 }
1087 if (nai != null) return nai.network;
1088 }
1089 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001090 if (nai != null
1091 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1092 nai = null;
1093 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001094 return nai != null ? nai.network : null;
1095 }
1096
Lorenzo Colitti18660282016-07-04 12:55:44 +09001097 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001098 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1099 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001100 final int uid = Binder.getCallingUid();
1101 NetworkState state = getUnfilteredActiveNetworkState(uid);
1102 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001103 }
1104
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001105 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001106 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001107 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001108 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001109 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001110 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 }
1112
1113 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001114 public NetworkInfo getNetworkInfo(int networkType) {
1115 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001116 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001117 if (getVpnUnderlyingNetworks(uid) != null) {
1118 // A VPN is active, so we may need to return one of its underlying networks. This
1119 // information is not available in LegacyTypeTracker, so we have to get it from
1120 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001121 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001122 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001123 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001124 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001125 }
1126 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001127 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001128 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001129 }
1130
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001131 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001132 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001133 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001134 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001135 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001136 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001137 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001138 return state.networkInfo;
1139 } else {
1140 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001141 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001142 }
1143
1144 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001145 public NetworkInfo[] getAllNetworkInfo() {
1146 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001147 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001148 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1149 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001150 NetworkInfo info = getNetworkInfo(networkType);
1151 if (info != null) {
1152 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001153 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001154 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001155 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001156 }
1157
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001158 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001159 public Network getNetworkForType(int networkType) {
1160 enforceAccessPermission();
1161 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001162 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1163 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001164 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001165 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001166 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001167 }
1168
1169 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001170 public Network[] getAllNetworks() {
1171 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001172 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001173 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001174 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001175 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001176 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001177 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001178 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001179 }
1180
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001181 @Override
1182 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1183 // The basic principle is: if an app's traffic could possibly go over a
1184 // network, without the app doing anything multinetwork-specific,
1185 // (hence, by "default"), then include that network's capabilities in
1186 // the array.
1187 //
1188 // In the normal case, app traffic only goes over the system's default
1189 // network connection, so that's the only network returned.
1190 //
1191 // With a VPN in force, some app traffic may go into the VPN, and thus
1192 // over whatever underlying networks the VPN specifies, while other app
1193 // traffic may go over the system default network (e.g.: a split-tunnel
1194 // VPN, or an app disallowed by the VPN), so the set of networks
1195 // returned includes the VPN's underlying networks and the system
1196 // default.
1197 enforceAccessPermission();
1198
1199 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1200
1201 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001202 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001203 if (nc != null) {
1204 result.put(nai.network, nc);
1205 }
1206
1207 if (!mLockdownEnabled) {
1208 synchronized (mVpns) {
1209 Vpn vpn = mVpns.get(userId);
1210 if (vpn != null) {
1211 Network[] networks = vpn.getUnderlyingNetworks();
1212 if (networks != null) {
1213 for (Network network : networks) {
1214 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001215 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001216 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001217 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001218 }
1219 }
1220 }
1221 }
1222 }
1223 }
1224
1225 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1226 out = result.values().toArray(out);
1227 return out;
1228 }
1229
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001230 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001231 public boolean isNetworkSupported(int networkType) {
1232 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001233 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001234 }
1235
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001236 /**
1237 * Return LinkProperties for the active (i.e., connected) default
1238 * network interface. It is assumed that at most one default network
1239 * is active at a time. If more than one is active, it is indeterminate
1240 * which will be returned.
1241 * @return the ip properties for the active network, or {@code null} if
1242 * none is active
1243 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001244 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001245 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001246 enforceAccessPermission();
1247 final int uid = Binder.getCallingUid();
1248 NetworkState state = getUnfilteredActiveNetworkState(uid);
1249 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001250 }
1251
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001252 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001253 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001254 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001255 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1256 if (nai != null) {
1257 synchronized (nai) {
1258 return new LinkProperties(nai.linkProperties);
1259 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001260 }
1261 return null;
1262 }
1263
Robert Greenwalt12e67352014-05-13 21:41:06 -07001264 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001265 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001266 public LinkProperties getLinkProperties(Network network) {
1267 enforceAccessPermission();
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001268 return getLinkProperties(getNetworkAgentInfoForNetwork(network));
1269 }
1270
1271 private LinkProperties getLinkProperties(NetworkAgentInfo nai) {
1272 if (nai == null) {
1273 return null;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001274 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09001275 synchronized (nai) {
1276 return new LinkProperties(nai.linkProperties);
1277 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001278 }
1279
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001280 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001281 if (nai != null) {
1282 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001283 if (nai.networkCapabilities != null) {
1284 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001285 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001286 }
1287 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001288 return null;
1289 }
1290
1291 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001292 public NetworkCapabilities getNetworkCapabilities(Network network) {
1293 enforceAccessPermission();
1294 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1295 }
1296
1297 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001298 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001299 // Require internal since we're handing out IMSI details
1300 enforceConnectivityInternalPermission();
1301
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001302 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001303 for (Network network : getAllNetworks()) {
1304 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1305 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001306 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001307 }
1308 }
1309 return result.toArray(new NetworkState[result.size()]);
1310 }
1311
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001312 @Override
1313 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1314 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001315 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001316 final long token = Binder.clearCallingIdentity();
1317 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001318 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1319 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001320 try {
1321 return mPolicyManager.getNetworkQuotaInfo(state);
1322 } catch (RemoteException e) {
1323 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001324 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001325 return null;
1326 } finally {
1327 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001328 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001329 }
1330
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001331 @Override
1332 public boolean isActiveNetworkMetered() {
1333 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001334
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001335 final NetworkInfo info = getActiveNetworkInfo();
1336 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001337 }
1338
Jeff Sharkey216c1812012-08-05 14:29:23 -07001339 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1340 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001341 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001342 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001343 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001344 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001345 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001346
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001347 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 * Ensure that a network route exists to deliver traffic to the specified
1349 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001350 * @param networkType the type of the network over which traffic to the
1351 * specified host is to be routed
1352 * @param hostAddress the IP address of the host to which the route is
1353 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 * @return {@code true} on success, {@code false} on failure
1355 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001356 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001357 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001359 if (mProtectedNetworks.contains(networkType)) {
1360 enforceConnectivityInternalPermission();
1361 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001362
Chad Brubakerc0234532014-02-14 13:24:29 -08001363 InetAddress addr;
1364 try {
1365 addr = InetAddress.getByAddress(hostAddress);
1366 } catch (UnknownHostException e) {
1367 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1368 return false;
1369 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001370
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001371 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001372 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 return false;
1374 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001375
1376 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1377 if (nai == null) {
1378 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1379 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1380 } else {
1381 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1382 }
1383 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001384 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001385
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001386 DetailedState netState;
1387 synchronized (nai) {
1388 netState = nai.networkInfo.getDetailedState();
1389 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001390
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001391 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001392 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001393 log("requestRouteToHostAddress on down network "
1394 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001395 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001396 }
1397 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001398 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001399
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001400 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001401 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001402 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001403 LinkProperties lp;
1404 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001405 synchronized (nai) {
1406 lp = nai.linkProperties;
1407 netId = nai.network.netId;
1408 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001409 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001410 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1411 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001412 } finally {
1413 Binder.restoreCallingIdentity(token);
1414 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001415 }
1416
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001417 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001418 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001419 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001420 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001421 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001422 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001423 if (bestRoute.getGateway().equals(addr)) {
1424 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001425 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001426 } else {
1427 // if we will connect to this through another route, add a direct route
1428 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001429 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001430 }
1431 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001432 if (DBG) log("Adding legacy route " + bestRoute +
1433 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001434 try {
1435 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1436 } catch (Exception e) {
1437 // never crash - catch them all
1438 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001439 return false;
1440 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001441 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
1443
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001444 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001445 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001446 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001447 // TODO: notify UID when it has requested targeted updates
1448 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001449 @Override
1450 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001451 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001452 @Override
1453 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001454 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001455 if (restrictBackground) {
1456 log("onRestrictBackgroundChanged(true): disabling tethering");
1457 mTethering.untetherAll();
1458 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001459 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001460 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001461 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001462 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001463 };
1464
Robin Lee3b3dd942015-05-12 18:14:58 +01001465 /**
1466 * Require that the caller is either in the same user or has appropriate permission to interact
1467 * across users.
1468 *
1469 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1470 */
1471 private void enforceCrossUserPermission(int userId) {
1472 if (userId == UserHandle.getCallingUserId()) {
1473 // Not a cross-user call.
1474 return;
1475 }
1476 mContext.enforceCallingOrSelfPermission(
1477 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1478 "ConnectivityService");
1479 }
1480
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001481 private void enforceInternetPermission() {
1482 mContext.enforceCallingOrSelfPermission(
1483 android.Manifest.permission.INTERNET,
1484 "ConnectivityService");
1485 }
1486
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001488 mContext.enforceCallingOrSelfPermission(
1489 android.Manifest.permission.ACCESS_NETWORK_STATE,
1490 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492
1493 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001494 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001495 }
1496
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001497 private void enforceTetherAccessPermission() {
1498 mContext.enforceCallingOrSelfPermission(
1499 android.Manifest.permission.ACCESS_NETWORK_STATE,
1500 "ConnectivityService");
1501 }
1502
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001503 private void enforceConnectivityInternalPermission() {
1504 mContext.enforceCallingOrSelfPermission(
1505 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1506 "ConnectivityService");
1507 }
1508
Hugo Benichi514da602016-07-19 15:59:27 +09001509 private void enforceConnectivityRestrictedNetworksPermission() {
1510 try {
1511 mContext.enforceCallingOrSelfPermission(
1512 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1513 "ConnectivityService");
1514 return;
1515 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1516 enforceConnectivityInternalPermission();
1517 }
1518
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001519 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001520 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001521 }
1522
Lorenzo Colitti18660282016-07-04 12:55:44 +09001523 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001524 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001525 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001526 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001527 }
1528
1529 private void sendInetConditionBroadcast(NetworkInfo info) {
1530 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1531 }
1532
Wink Saville628b0852011-08-04 15:01:58 -07001533 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001534 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001535 info = new NetworkInfo(info);
1536 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001537 }
1538
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001539 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001540 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001541 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001542 if (info.isFailover()) {
1543 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1544 info.setFailover(false);
1545 }
1546 if (info.getReason() != null) {
1547 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1548 }
1549 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001550 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1551 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001552 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001553 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001554 return intent;
1555 }
1556
1557 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1558 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1559 }
1560
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001561 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001562 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1563 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1564 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001565 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001566 final long ident = Binder.clearCallingIdentity();
1567 try {
1568 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1569 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1570 } finally {
1571 Binder.restoreCallingIdentity(ident);
1572 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001573 }
1574
Mike Lockwood0f79b542009-08-14 14:18:49 -04001575 private void sendStickyBroadcast(Intent intent) {
1576 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001577 if (!mSystemReady) {
1578 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001579 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001580 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001581 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001582 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001583 }
1584
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001585 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001586 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001587 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001588 final NetworkInfo ni = intent.getParcelableExtra(
1589 ConnectivityManager.EXTRA_NETWORK_INFO);
1590 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1591 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1592 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001593 } else {
1594 BroadcastOptions opts = BroadcastOptions.makeBasic();
1595 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1596 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001597 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001598 final IBatteryStats bs = BatteryStatsService.getService();
1599 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001600 bs.noteConnectivityChanged(intent.getIntExtra(
1601 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1602 ni != null ? ni.getState().toString() : "?");
1603 } catch (RemoteException e) {
1604 }
1605 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001606 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001607 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001608 } finally {
1609 Binder.restoreCallingIdentity(ident);
1610 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001611 }
1612 }
1613
1614 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001615 loadGlobalProxy();
1616
Mike Lockwood0f79b542009-08-14 14:18:49 -04001617 synchronized(this) {
1618 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001619 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001620 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001621 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001622 }
1623 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001624 // load the global proxy at startup
1625 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001626
Robin Lee244ce8e2016-01-05 18:03:46 +00001627 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1628 // for user to unlock device too.
1629 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001630
Erik Klineda4bfa82015-04-30 12:58:40 +09001631 // Configure whether mobile data is always on.
1632 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1633
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001634 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001635
1636 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001637 }
1638
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001639 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001640 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001641 *
1642 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001643 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001644 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1646 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001647
1648 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001649 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001650
Robert Greenwalt7b816022014-04-18 15:25:25 -07001651 if (networkAgent.networkCapabilities.hasTransport(
1652 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001653 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1654 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001655 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001656 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001657 } else if (networkAgent.networkCapabilities.hasTransport(
1658 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001659 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1660 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001661 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001662 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001663 } else {
1664 // do not track any other networks
1665 timeout = 0;
1666 }
1667
Robert Greenwalt7b816022014-04-18 15:25:25 -07001668 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001669 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001670 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001671 } catch (Exception e) {
1672 // You shall not crash!
1673 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001674 }
1675 }
1676 }
1677
1678 /**
1679 * Remove data activity tracking when network disconnects.
1680 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001681 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1682 final String iface = networkAgent.linkProperties.getInterfaceName();
1683 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001684
Robert Greenwalt7b816022014-04-18 15:25:25 -07001685 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1686 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001687 try {
1688 // the call fails silently if no idletimer setup for this interface
1689 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001690 } catch (Exception e) {
1691 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001692 }
1693 }
1694 }
1695
1696 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001697 * Reads the network specific MTU size from reources.
1698 * and set it on it's iface.
1699 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001700 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1701 final String iface = newLp.getInterfaceName();
1702 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001703 if (oldLp == null && mtu == 0) {
1704 // Silently ignore unset MTU value.
1705 return;
1706 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001707 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1708 if (VDBG) log("identical MTU - not setting");
1709 return;
1710 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001711 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001712 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001713 return;
1714 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001715
w1997615afd812014-08-05 15:18:11 -07001716 // Cannot set MTU without interface name
1717 if (TextUtils.isEmpty(iface)) {
1718 loge("Setting MTU size with null iface.");
1719 return;
1720 }
1721
Robert Greenwalt7b816022014-04-18 15:25:25 -07001722 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001723 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001724 mNetd.setMtu(iface, mtu);
1725 } catch (Exception e) {
1726 Slog.e(TAG, "exception in setMtu()" + e);
1727 }
1728 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001729
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001730 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001731 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1732
1733 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001734 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001735 protected int getDefaultTcpRwnd() {
1736 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1737 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001738
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001739 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1740 if (isDefaultNetwork(nai) == false) {
1741 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001742 }
1743
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001744 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1745 String[] values = null;
1746 if (tcpBufferSizes != null) {
1747 values = tcpBufferSizes.split(",");
1748 }
1749
1750 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001751 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001752 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1753 values = tcpBufferSizes.split(",");
1754 }
1755
1756 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1757
1758 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001759 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001760
1761 final String prefix = "/sys/kernel/ipv4/tcp_";
1762 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1763 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1764 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1765 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1766 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1767 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1768 mCurrentTcpBufferSizes = tcpBufferSizes;
1769 } catch (IOException e) {
1770 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001771 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001772
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001773 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001774 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001775 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1776 if (rwndValue != 0) {
1777 SystemProperties.set(sysctlKey, rwndValue.toString());
1778 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001779 }
1780
Mattias Falk8b47b362011-08-23 14:15:13 +02001781 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001782 /*
1783 * Tell the VMs to toss their DNS caches
1784 */
1785 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1786 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001787 /*
1788 * Connectivity events can happen before boot has completed ...
1789 */
1790 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001791 final long ident = Binder.clearCallingIdentity();
1792 try {
1793 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1794 } finally {
1795 Binder.restoreCallingIdentity(ident);
1796 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001797 }
1798
Robert Greenwalt562cc542014-05-15 18:07:26 -07001799 @Override
1800 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001801 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1802 NETWORK_RESTORE_DELAY_PROP_NAME);
1803 if(restoreDefaultNetworkDelayStr != null &&
1804 restoreDefaultNetworkDelayStr.length() != 0) {
1805 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001806 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001807 } catch (NumberFormatException e) {
1808 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001809 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001810 // if the system property isn't set, use the value for the apn type
1811 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1812
1813 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1814 (mNetConfigs[networkType] != null)) {
1815 ret = mNetConfigs[networkType].restoreTime;
1816 }
1817 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001818 }
1819
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001820 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001821 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001822 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001823 }
1824 return false;
1825 }
1826
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001827 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1828 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1829 final long DIAG_TIME_MS = 5000;
1830 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1831 // Start gathering diagnostic information.
1832 netDiags.add(new NetworkDiagnostics(
1833 nai.network,
1834 new LinkProperties(nai.linkProperties), // Must be a copy.
1835 DIAG_TIME_MS));
1836 }
1837
1838 for (NetworkDiagnostics netDiag : netDiags) {
1839 pw.println();
1840 netDiag.waitForMeasurements();
1841 netDiag.dump(pw);
1842 }
1843 }
1844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001846 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1847 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Jeff Sharkeyfe9a53b2017-03-31 14:08:23 -06001848 if (!DumpUtils.checkDumpPermission(mContext, TAG, pw)) return;
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001849
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001850 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001851 dumpNetworkDiagnostics(pw);
1852 return;
1853 }
Erik Kline379747a2015-06-05 17:47:34 +09001854
Lorenzo Colittie3805462015-06-03 11:18:24 +09001855 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001856 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001857 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001858 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001859 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001860 pw.println();
1861
Paul Jensen85cf78e2015-06-25 13:25:07 -04001862 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001863 pw.print("Active default network: ");
1864 if (defaultNai == null) {
1865 pw.println("none");
1866 } else {
1867 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001868 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001869 pw.println();
1870
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001871 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001872 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001873 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1874 pw.println(nai.toString());
1875 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001876 pw.println(String.format(
1877 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1878 nai.numForegroundNetworkRequests(),
1879 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1880 nai.numBackgroundNetworkRequests(),
1881 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001882 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001883 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1884 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001885 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001886 pw.decreaseIndent();
1887 pw.println("Lingered:");
1888 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001889 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001890 pw.decreaseIndent();
1891 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001892 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001893 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001894 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001895
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001896 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001897 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001898 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1899 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001900 }
1901 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001902 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001903
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001904 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001905
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001906 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001907 pw.print("mNetTransitionWakeLock: currently " +
1908 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1909 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1910 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1911 } else {
1912 pw.println(", last requested never");
1913 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001914 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001915
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001916 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001917 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001918
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001919 pw.println();
1920 mKeepaliveTracker.dump(pw);
1921
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001922 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001923 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001924
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001925 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09001926 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001927 pw.println();
1928 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001929 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001930 for(int i = 0; i < mInetLog.size(); i++) {
1931 pw.println(mInetLog.get(i));
1932 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001933 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001934 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001935
1936 if (argsContain(args, "--short") == false) {
1937 pw.println();
1938 synchronized (mValidationLogs) {
1939 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001940 for (ValidationLog p : mValidationLogs) {
1941 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001942 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001943 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001944 pw.decreaseIndent();
1945 }
1946 }
Erik Kline7523eb32015-07-09 18:24:03 +09001947
1948 pw.println();
1949 pw.println("mNetworkRequestInfoLogs (most recent first):");
1950 pw.increaseIndent();
1951 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1952 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001953
1954 pw.println();
1955 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1956 pw.increaseIndent();
1957 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1958 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001959 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001960 }
1961
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001962 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001963 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001964 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001965 if (officialNai != null && officialNai.equals(nai)) return true;
1966 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001967 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001968 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001969 " - " + nai);
1970 }
1971 return false;
1972 }
1973
Robert Greenwalt42acef32009-08-12 16:08:25 -07001974 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001975 private class NetworkStateTrackerHandler extends Handler {
1976 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001977 super(looper);
1978 }
1979
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001980 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001981 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001982 default:
1983 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001984 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001985 handleAsyncChannelHalfConnect(msg);
1986 break;
1987 }
1988 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1989 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1990 if (nai != null) nai.asyncChannel.disconnect();
1991 break;
1992 }
1993 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1994 handleAsyncChannelDisconnected(msg);
1995 break;
1996 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001997 }
1998 return true;
1999 }
2000
2001 private void maybeHandleNetworkAgentMessage(Message msg) {
2002 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2003 if (nai == null) {
2004 if (VDBG) {
2005 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2006 log(String.format("%s from unknown NetworkAgent", what));
2007 }
2008 return;
2009 }
2010
2011 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002012 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002013 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2014 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002015 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2016 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002017 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002018 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002019 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002020 break;
2021 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002022 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002023 if (VDBG) {
2024 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002025 "; created=" + nai.created +
2026 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002027 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002028 LinkProperties oldLp = nai.linkProperties;
2029 synchronized (nai) {
2030 nai.linkProperties = (LinkProperties)msg.obj;
2031 }
Robin Lee585e2482016-05-01 23:00:00 +01002032 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002033 break;
2034 }
2035 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002036 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002037 updateNetworkInfo(nai, info);
2038 break;
2039 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002040 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002041 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002042 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002043 break;
2044 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002045 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002046 try {
2047 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002048 } catch (Exception e) {
2049 // Never crash!
2050 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002051 }
2052 break;
2053 }
2054 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002055 try {
2056 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002057 } catch (Exception e) {
2058 // Never crash!
2059 loge("Exception in removeVpnUidRanges: " + e);
2060 }
2061 break;
2062 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002063 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002064 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2065 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002066 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002067 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002068 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002069 break;
2070 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002071 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002072 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2073 break;
2074 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002075 }
2076 }
2077
2078 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2079 switch (msg.what) {
2080 default:
2081 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002082 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002083 final NetworkAgentInfo nai;
2084 synchronized (mNetworkForNetId) {
2085 nai = mNetworkForNetId.get(msg.arg2);
2086 }
2087 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002088 final boolean valid =
2089 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002090 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002091 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2092 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002093 if (valid != nai.lastValidated) {
2094 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002095 nai.lastValidated = valid;
2096 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002097 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002098 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2099 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002100 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002101 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002102 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002103 Bundle redirectUrlBundle = new Bundle();
2104 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002105 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002106 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002107 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002108 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002109 if (wasValidated && !nai.lastValidated) {
2110 handleNetworkUnvalidated(nai);
2111 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002112 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 break;
2114 }
Paul Jensen869868be2014-05-15 10:33:05 -04002115 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002116 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002117 final boolean visible = (msg.arg1 != 0);
2118 final NetworkAgentInfo nai;
2119 synchronized (mNetworkForNetId) {
2120 nai = mNetworkForNetId.get(netId);
2121 }
Calvin Onbe96da12016-10-11 15:10:46 -07002122 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002123 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002124 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002125 nai.lastCaptivePortalDetected = visible;
2126 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002127 if (nai.lastCaptivePortalDetected &&
2128 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2129 if (DBG) log("Avoiding captive portal network: " + nai.name());
2130 nai.asyncChannel.sendMessage(
2131 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2132 teardownUnneededNetwork(nai);
2133 break;
2134 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002135 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002136 }
2137 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002138 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002139 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002140 if (nai == null) {
2141 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2142 break;
2143 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002144 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002145 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002146 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002147 }
Paul Jensen869868be2014-05-15 10:33:05 -04002148 }
Paul Jensen869868be2014-05-15 10:33:05 -04002149 break;
2150 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002151 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002152 return true;
2153 }
2154
Calvin Onbe96da12016-10-11 15:10:46 -07002155 private int getCaptivePortalMode() {
2156 return Settings.Global.getInt(mContext.getContentResolver(),
2157 Settings.Global.CAPTIVE_PORTAL_MODE,
2158 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2159 }
2160
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002161 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2162 switch (msg.what) {
2163 default:
2164 return false;
2165 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2166 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2167 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2168 handleLingerComplete(nai);
2169 }
2170 break;
2171 }
2172 }
2173 return true;
2174 }
2175
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002176 @Override
2177 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002178 if (!maybeHandleAsyncChannelMessage(msg) &&
2179 !maybeHandleNetworkMonitorMessage(msg) &&
2180 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002181 maybeHandleNetworkAgentMessage(msg);
2182 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002183 }
2184 }
2185
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002186 private void updateLingerState(NetworkAgentInfo nai, long now) {
2187 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2188 // 2. If the network was lingering and there are now requests, unlinger it.
2189 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2190 // one lingered request, start lingering.
2191 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002192 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002193 if (DBG) log("Unlingering " + nai.name());
2194 nai.unlinger();
2195 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002196 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002197 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002198 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002199 nai.linger();
2200 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2201 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2202 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002203 }
2204
Robert Greenwalt7b816022014-04-18 15:25:25 -07002205 private void handleAsyncChannelHalfConnect(Message msg) {
2206 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002207 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002208 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2209 if (VDBG) log("NetworkFactory connected");
2210 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002211 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002212 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002213 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002214 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002215 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002216 }
2217 } else {
2218 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002219 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002220 }
2221 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2222 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2223 if (VDBG) log("NetworkAgent connected");
2224 // A network agent has requested a connection. Establish the connection.
2225 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2226 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2227 } else {
2228 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002229 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002230 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002231 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002232 synchronized (mNetworkForNetId) {
2233 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002234 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002235 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002236 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002237 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002238 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002239 }
2240 }
2241 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002242
Robert Greenwalt7b816022014-04-18 15:25:25 -07002243 private void handleAsyncChannelDisconnected(Message msg) {
2244 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2245 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002246 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002247 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002248 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002249 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002250 // TODO - if we move the logic to the network agent (have them disconnect
2251 // because they lost all their requests or because their score isn't good)
2252 // then they would disconnect organically, report their new state and then
2253 // disconnect the channel.
2254 if (nai.networkInfo.isConnected()) {
2255 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2256 null, null);
2257 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002258 final boolean wasDefault = isDefaultNetwork(nai);
2259 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002260 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002261 // Log default network disconnection before required book-keeping.
2262 // Let rematchAllNetworksAndRequests() below record a new default network event
2263 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2264 // whose timestamps tell how long it takes to recover a default network.
2265 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002266 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002267 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002268 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2269 // by other networks that are already connected. Perhaps that can be done by
2270 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2271 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002272 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002273 mKeepaliveTracker.handleStopAllKeepalives(nai,
2274 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002275 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002276 mNetworkAgentInfos.remove(msg.replyTo);
2277 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002278 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002279 // Remove the NetworkAgent, but don't mark the netId as
2280 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002281 mNetworkForNetId.remove(nai.network.netId);
2282 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002283 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002284 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2285 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002286 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2287 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2288 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002289 sendUpdatedScoreToFactories(request, 0);
2290 }
2291 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002292 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002293 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002294 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002295 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002296 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002297 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002298 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002299 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002300 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002301 if (nai.created) {
2302 // Tell netd to clean up the configuration for this network
2303 // (routing rules, DNS, etc).
2304 // This may be slow as it requires a lot of netd shelling out to ip and
2305 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2306 // after we've rematched networks with requests which should make a potential
2307 // fallback network the default or requested a new network from the
2308 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2309 // long time.
2310 try {
2311 mNetd.removeNetwork(nai.network.netId);
2312 } catch (Exception e) {
2313 loge("Exception removing network: " + e);
2314 }
2315 }
2316 synchronized (mNetworkForNetId) {
2317 mNetIdInUse.delete(nai.network.netId);
2318 }
2319 } else {
2320 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2321 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002322 }
2323 }
2324
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002325 // If this method proves to be too slow then we can maintain a separate
2326 // pendingIntent => NetworkRequestInfo map.
2327 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2328 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2329 Intent intent = pendingIntent.getIntent();
2330 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2331 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2332 if (existingPendingIntent != null &&
2333 existingPendingIntent.getIntent().filterEquals(intent)) {
2334 return entry.getValue();
2335 }
2336 }
2337 return null;
2338 }
2339
2340 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2341 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2342
2343 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2344 if (existingRequest != null) { // remove the existing request.
2345 if (DBG) log("Replacing " + existingRequest.request + " with "
2346 + nri.request + " because their intents matched.");
2347 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2348 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002349 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002350 }
2351
Erik Klineda4bfa82015-04-30 12:58:40 +09002352 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002353 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002354 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002355 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002356 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002357 if (nri.request.networkCapabilities.hasSignalStrength() &&
2358 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2359 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002360 }
2361 }
2362 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002363 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002364 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002365 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002366 }
2367 }
2368
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002369 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2370 int callingUid) {
2371 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2372 if (nri != null) {
2373 handleReleaseNetworkRequest(nri.request, callingUid);
2374 }
2375 }
2376
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002377 // Determines whether the network is the best (or could become the best, if it validated), for
2378 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2379 // on the value of reason:
2380 //
2381 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2382 // then it should be torn down.
2383 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2384 // then it should be lingered.
2385 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2386 final int numRequests;
2387 switch (reason) {
2388 case TEARDOWN:
2389 numRequests = nai.numRequestNetworkRequests();
2390 break;
2391 case LINGER:
2392 numRequests = nai.numForegroundNetworkRequests();
2393 break;
2394 default:
2395 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2396 return true;
2397 }
2398
2399 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002400 return false;
2401 }
Paul Jensene0988542015-06-25 15:30:08 -04002402 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002403 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2404 // Background requests don't affect lingering.
2405 continue;
2406 }
2407
Paul Jensene0988542015-06-25 15:30:08 -04002408 // If this Network is already the highest scoring Network for a request, or if
2409 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002410 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002411 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002412 // Note that this catches two important cases:
2413 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2414 // is currently satisfying the request. This is desirable when
2415 // cellular ends up validating but WiFi does not.
2416 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002417 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002418 // WiFi ends up validating and out scoring cellular.
2419 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2420 nai.getCurrentScoreAsValidated())) {
2421 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002422 }
2423 }
Paul Jensene0988542015-06-25 15:30:08 -04002424 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002425 }
2426
Erik Klineacdd6392016-07-07 16:50:58 +09002427 private NetworkRequestInfo getNriForAppRequest(
2428 NetworkRequest request, int callingUid, String requestedOperation) {
2429 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2430
Robert Greenwalt9258c642014-03-26 16:47:06 -07002431 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002432 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002433 log(String.format("UID %d attempted to %s for unowned request %s",
2434 callingUid, requestedOperation, nri));
2435 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002436 }
Erik Klineacdd6392016-07-07 16:50:58 +09002437 }
2438
2439 return nri;
2440 }
2441
Erik Kline57faba92015-11-25 12:49:38 +09002442 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2443 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2444 nri.request.requestId) == null) {
2445 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2446 }
2447 }
2448
Erik Klineacdd6392016-07-07 16:50:58 +09002449 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2450 final NetworkRequestInfo nri = getNriForAppRequest(
2451 request, callingUid, "release NetworkRequest");
Erik Kline57faba92015-11-25 12:49:38 +09002452 if (nri != null) {
2453 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2454 }
2455 }
Erik Klineacdd6392016-07-07 16:50:58 +09002456
Erik Kline57faba92015-11-25 12:49:38 +09002457 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2458 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2459 if (VDBG || (DBG && nri.request.isRequest())) {
2460 log("releasing " + nri.request + " (" + logCallbackType + ")");
2461 }
Erik Klineacdd6392016-07-07 16:50:58 +09002462 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002463 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002464 synchronized (mUidToNetworkRequestCount) {
2465 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2466 if (requests < 1) {
2467 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2468 nri.mUid);
2469 } else if (requests == 1) {
2470 mUidToNetworkRequestCount.removeAt(
2471 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2472 } else {
2473 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2474 }
2475 }
2476 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2477 if (nri.request.isRequest()) {
2478 boolean wasKept = false;
2479 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2480 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002481 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002482 nai.removeRequest(nri.request.requestId);
2483 if (VDBG) {
2484 log(" Removing from current network " + nai.name() +
2485 ", leaving " + nai.numNetworkRequests() + " requests.");
2486 }
2487 // If there are still lingered requests on this network, don't tear it down,
2488 // but resume lingering instead.
2489 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002490 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002491 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2492 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002493 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002494 wasKept = true;
2495 }
2496 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002497 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2498 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002499 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002500 }
Erik Klineacdd6392016-07-07 16:50:58 +09002501 }
2502
2503 // TODO: remove this code once we know that the Slog.wtf is never hit.
2504 //
2505 // Find all networks that are satisfying this request and remove the request
2506 // from their request lists.
2507 // TODO - it's my understanding that for a request there is only a single
2508 // network satisfying it, so this loop is wasteful
2509 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2510 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2511 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2512 otherNai.name() + ", but mNetworkAgentInfos says " +
2513 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002514 }
2515 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002516
Erik Klineacdd6392016-07-07 16:50:58 +09002517 // Maintain the illusion. When this request arrived, we might have pretended
2518 // that a network connected to serve it, even though the network was already
2519 // connected. Now that this request has gone away, we might have to pretend
2520 // that the network disconnected. LegacyTypeTracker will generate that
2521 // phantom disconnect for this type.
2522 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2523 boolean doRemove = true;
2524 if (wasKept) {
2525 // check if any of the remaining requests for this network are for the
2526 // same legacy type - if so, don't remove the nai
2527 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2528 NetworkRequest otherRequest = nai.requestAt(i);
2529 if (otherRequest.legacyType == nri.request.legacyType &&
2530 otherRequest.isRequest()) {
2531 if (DBG) log(" still have other legacy request - leaving");
2532 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002533 }
2534 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002535 }
2536
Erik Klineacdd6392016-07-07 16:50:58 +09002537 if (doRemove) {
2538 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002539 }
2540 }
Erik Klineacdd6392016-07-07 16:50:58 +09002541
2542 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2543 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2544 nri.request);
2545 }
2546 } else {
2547 // listens don't have a singular affectedNetwork. Check all networks to see
2548 // if this listen request applies and remove it.
2549 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2550 nai.removeRequest(nri.request.requestId);
2551 if (nri.request.networkCapabilities.hasSignalStrength() &&
2552 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2553 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2554 }
2555 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002556 }
Erik Kline57faba92015-11-25 12:49:38 +09002557 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002558 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002559
Lorenzo Colitti18660282016-07-04 12:55:44 +09002560 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002561 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2562 enforceConnectivityInternalPermission();
2563 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2564 accept ? 1 : 0, always ? 1: 0, network));
2565 }
2566
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002567 @Override
2568 public void setAvoidUnvalidated(Network network) {
2569 enforceConnectivityInternalPermission();
2570 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2571 }
2572
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002573 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2574 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2575 " accept=" + accept + " always=" + always);
2576
2577 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2578 if (nai == null) {
2579 // Nothing to do.
2580 return;
2581 }
2582
2583 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002584 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002585 return;
2586 }
2587
2588 if (!nai.networkMisc.explicitlySelected) {
2589 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2590 }
2591
2592 if (accept != nai.networkMisc.acceptUnvalidated) {
2593 int oldScore = nai.getCurrentScore();
2594 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002595 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002596 sendUpdatedScoreToFactories(nai);
2597 }
2598
2599 if (always) {
2600 nai.asyncChannel.sendMessage(
2601 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2602 }
2603
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002604 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002605 // Tell the NetworkAgent to not automatically reconnect to the network.
2606 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2607 // Teardown the nework.
2608 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002609 }
2610
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002611 }
2612
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002613 private void handleSetAvoidUnvalidated(Network network) {
2614 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2615 if (nai == null || nai.lastValidated) {
2616 // Nothing to do. The network either disconnected or revalidated.
2617 return;
2618 }
2619 if (!nai.avoidUnvalidated) {
2620 int oldScore = nai.getCurrentScore();
2621 nai.avoidUnvalidated = true;
2622 rematchAllNetworksAndRequests(nai, oldScore);
2623 sendUpdatedScoreToFactories(nai);
2624 }
2625 }
2626
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002627 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002628 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002629 mHandler.sendMessageDelayed(
2630 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2631 PROMPT_UNVALIDATED_DELAY_MS);
2632 }
2633
Hugo Benichic8e9e122016-09-14 23:23:08 +00002634 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002635 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002636 }
2637
Erik Kline065ab6e2016-10-02 18:02:14 +09002638 private void rematchForAvoidBadWifiUpdate() {
2639 rematchAllNetworksAndRequests(null, 0);
2640 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2641 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2642 sendUpdatedScoreToFactories(nai);
2643 }
2644 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002645 }
2646
Erik Kline065ab6e2016-10-02 18:02:14 +09002647 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002648 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002649 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002650 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002651 if (!configRestrict) {
2652 pw.println("Bad Wi-Fi avoidance: unrestricted");
2653 return;
2654 }
2655
2656 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2657 pw.increaseIndent();
2658 pw.println("Config restrict: " + configRestrict);
2659
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002660 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002661 String description;
2662 // Can't use a switch statement because strings are legal case labels, but null is not.
2663 if ("0".equals(value)) {
2664 description = "get stuck";
2665 } else if (value == null) {
2666 description = "prompt";
2667 } else if ("1".equals(value)) {
2668 description = "avoid";
2669 } else {
2670 description = value + " (?)";
2671 }
2672 pw.println("User setting: " + description);
2673 pw.println("Network overrides:");
2674 pw.increaseIndent();
2675 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2676 if (nai.avoidUnvalidated) {
2677 pw.println(nai.name());
2678 }
2679 }
2680 pw.decreaseIndent();
2681 pw.decreaseIndent();
2682 }
2683
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002684 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2685 final String action;
2686 switch (type) {
2687 case NO_INTERNET:
2688 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2689 break;
2690 case LOST_INTERNET:
2691 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2692 break;
2693 default:
2694 Slog.wtf(TAG, "Unknown notification type " + type);
2695 return;
2696 }
2697
2698 Intent intent = new Intent(action);
2699 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2700 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2701 intent.setClassName("com.android.settings",
2702 "com.android.settings.wifi.WifiNoInternetDialog");
2703
2704 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2705 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2706 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2707 }
2708
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002709 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002710 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002711 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2712
2713 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2714 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002715 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002716 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002717 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2718 return;
2719 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002720 showValidationNotification(nai, NotificationType.NO_INTERNET);
2721 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002722
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002723 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2724 NetworkCapabilities nc = nai.networkCapabilities;
2725 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002726
Erik Kline065ab6e2016-10-02 18:02:14 +09002727 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002728 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002729 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2730 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002731 }
2732
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002733 @Override
2734 public int getMultipathPreference(Network network) {
2735 enforceAccessPermission();
2736
2737 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2738 if (nai != null && !nai.networkInfo.isMetered()) {
2739 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2740 }
2741
2742 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2743 }
2744
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002745 private class InternalHandler extends Handler {
2746 public InternalHandler(Looper looper) {
2747 super(looper);
2748 }
2749
2750 @Override
2751 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002752 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002753 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002754 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002755 String causedBy = null;
2756 synchronized (ConnectivityService.this) {
2757 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2758 mNetTransitionWakeLock.isHeld()) {
2759 mNetTransitionWakeLock.release();
2760 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002761 } else {
2762 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002763 }
2764 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002765 if (VDBG) {
2766 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2767 log("Failed to find a new network - expiring NetTransition Wakelock");
2768 } else {
2769 log("NetTransition Wakelock (" +
2770 (causedBy == null ? "unknown" : causedBy) +
2771 " cleared because we found a replacement network");
2772 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002773 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002774 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002775 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002776 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002777 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002778 break;
2779 }
Jason Monkdecd2952013-10-10 14:02:51 -04002780 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002781 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002782 break;
2783 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002784 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002785 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2786 break;
2787 }
2788 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2789 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002790 break;
2791 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002792 case EVENT_REGISTER_NETWORK_AGENT: {
2793 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2794 break;
2795 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002796 case EVENT_REGISTER_NETWORK_REQUEST:
2797 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002798 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002799 break;
2800 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002801 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2802 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002803 handleRegisterNetworkRequestWithIntent(msg);
2804 break;
2805 }
Erik Kline57faba92015-11-25 12:49:38 +09002806 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2807 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2808 handleTimedOutNetworkRequest(nri);
2809 break;
2810 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002811 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2812 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2813 break;
2814 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002815 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002816 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002817 break;
2818 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002819 case EVENT_SET_ACCEPT_UNVALIDATED: {
2820 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2821 break;
2822 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002823 case EVENT_SET_AVOID_UNVALIDATED: {
2824 handleSetAvoidUnvalidated((Network) msg.obj);
2825 break;
2826 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002827 case EVENT_PROMPT_UNVALIDATED: {
2828 handlePromptUnvalidated((Network) msg.obj);
2829 break;
2830 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002831 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2832 handleMobileDataAlwaysOn();
2833 break;
2834 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002835 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2836 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2837 mKeepaliveTracker.handleStartKeepalive(msg);
2838 break;
2839 }
2840 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2841 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2842 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2843 int slot = msg.arg1;
2844 int reason = msg.arg2;
2845 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2846 break;
2847 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002848 case EVENT_SYSTEM_READY: {
2849 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2850 nai.networkMonitor.systemReady = true;
2851 }
2852 break;
2853 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002854 }
2855 }
2856 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002857
2858 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002859 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002860 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002861 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002862 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002863 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002864 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002865 } else {
2866 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2867 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002868 }
2869
2870 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002871 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002872 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002873 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002874
2875 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002876 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002877 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002878 } else {
2879 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2880 }
2881 }
2882
2883 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002884 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002885 public int getLastTetherError(String iface) {
2886 enforceTetherAccessPermission();
2887
2888 if (isTetheringSupported()) {
2889 return mTethering.getLastTetherError(iface);
2890 } else {
2891 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2892 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002893 }
2894
2895 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002896 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002897 public String[] getTetherableUsbRegexs() {
2898 enforceTetherAccessPermission();
2899 if (isTetheringSupported()) {
2900 return mTethering.getTetherableUsbRegexs();
2901 } else {
2902 return new String[0];
2903 }
2904 }
2905
Lorenzo Colitti18660282016-07-04 12:55:44 +09002906 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002907 public String[] getTetherableWifiRegexs() {
2908 enforceTetherAccessPermission();
2909 if (isTetheringSupported()) {
2910 return mTethering.getTetherableWifiRegexs();
2911 } else {
2912 return new String[0];
2913 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002914 }
2915
Lorenzo Colitti18660282016-07-04 12:55:44 +09002916 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002917 public String[] getTetherableBluetoothRegexs() {
2918 enforceTetherAccessPermission();
2919 if (isTetheringSupported()) {
2920 return mTethering.getTetherableBluetoothRegexs();
2921 } else {
2922 return new String[0];
2923 }
2924 }
2925
Lorenzo Colitti18660282016-07-04 12:55:44 +09002926 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002927 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002928 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002929 if (isTetheringSupported()) {
2930 return mTethering.setUsbTethering(enable);
2931 } else {
2932 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2933 }
2934 }
2935
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002936 // TODO - move iface listing, queries, etc to new module
2937 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002938 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002939 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002940 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002941 return mTethering.getTetherableIfaces();
2942 }
2943
Lorenzo Colitti18660282016-07-04 12:55:44 +09002944 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002945 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002946 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002947 return mTethering.getTetheredIfaces();
2948 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002949
Lorenzo Colitti18660282016-07-04 12:55:44 +09002950 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002951 public String[] getTetheringErroredIfaces() {
2952 enforceTetherAccessPermission();
2953 return mTethering.getErroredIfaces();
2954 }
2955
Lorenzo Colitti18660282016-07-04 12:55:44 +09002956 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002957 public String[] getTetheredDhcpRanges() {
2958 enforceConnectivityInternalPermission();
2959 return mTethering.getTetheredDhcpRanges();
2960 }
2961
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002962 // if ro.tether.denied = true we default to no tethering
2963 // gservices could set the secure setting to 1 though to enable it on a build where it
2964 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002965 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002966 public boolean isTetheringSupported() {
2967 enforceTetherAccessPermission();
2968 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002969 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002970 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2971 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07002972
2973 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
2974 boolean adminUser = false;
2975 final long token = Binder.clearCallingIdentity();
2976 try {
2977 adminUser = mUserManager.isAdminUser();
2978 } finally {
2979 Binder.restoreCallingIdentity(token);
2980 }
2981
2982 return tetherEnabledInSettings && adminUser &&
Erik Klined781fba2017-01-23 13:01:58 +09002983 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002984 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002985
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002986 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09002987 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002988 ConnectivityManager.enforceTetherChangePermission(mContext);
2989 if (!isTetheringSupported()) {
2990 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2991 return;
2992 }
2993 mTethering.startTethering(type, receiver, showProvisioningUi);
2994 }
2995
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002996 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002997 public void stopTethering(int type) {
2998 ConnectivityManager.enforceTetherChangePermission(mContext);
2999 mTethering.stopTethering(type);
3000 }
3001
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003002 // Called when we lose the default network and have no replacement yet.
3003 // This will automatically be cleared after X seconds or a new default network
3004 // becomes CONNECTED, whichever happens first. The timer is started by the
3005 // first caller and not restarted by subsequent callers.
3006 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003007 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003008 synchronized (this) {
3009 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003010 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003011 mNetTransitionWakeLock.acquire();
3012 mNetTransitionWakeLockCausedBy = forWhom;
3013 }
3014 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003015 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003016 mNetTransitionWakeLockTimeout);
3017 return;
3018 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003019
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003020 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003021 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003022 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003023 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003024 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003025 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003026 }
3027
Lorenzo Colitti18660282016-07-04 12:55:44 +09003028 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003029 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003030 enforceAccessPermission();
3031 enforceInternetPermission();
3032
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003033 // TODO: execute this logic on ConnectivityService handler.
3034 final NetworkAgentInfo nai;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003035 if (network == null) {
3036 nai = getDefaultNetwork();
3037 } else {
3038 nai = getNetworkAgentInfoForNetwork(network);
3039 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003040 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3041 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3042 return;
3043 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003044 // Revalidate if the app report does not match our current validated state.
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003045 if (hasConnectivity == nai.lastValidated) {
3046 return;
3047 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003048 final int uid = Binder.getCallingUid();
3049 if (DBG) {
3050 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3051 ") by " + uid);
3052 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003053 // Validating a network that has not yet connected could result in a call to
3054 // rematchNetworkAndRequests() which is not meant to work on such networks.
3055 if (!nai.everConnected) {
3056 return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003057 }
Hugo Benichi0fd4af92017-04-06 16:01:44 +09003058 LinkProperties lp = getLinkProperties(nai);
3059 if (isNetworkWithLinkPropertiesBlocked(lp, uid, false)) {
3060 return;
3061 }
3062 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003063 }
3064
Paul Jensencee9b512015-05-06 07:32:40 -04003065 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003066 // this information is already available as a world read/writable jvm property
3067 // so this API change wouldn't have a benifit. It also breaks the passing
3068 // of proxy info to all the JVMs.
3069 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003070 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003071 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003072 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3073 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003074 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003075 }
3076
Lorenzo Colitti18660282016-07-04 12:55:44 +09003077 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003078 public ProxyInfo getProxyForNetwork(Network network) {
3079 if (network == null) return getDefaultProxy();
3080 final ProxyInfo globalProxy = getGlobalProxy();
3081 if (globalProxy != null) return globalProxy;
3082 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3083 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3084 // caller may not have.
3085 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3086 if (nai == null) return null;
3087 synchronized (nai) {
3088 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3089 if (proxyInfo == null) return null;
3090 return new ProxyInfo(proxyInfo);
3091 }
3092 }
3093
Paul Jensene0bef712014-12-10 15:12:18 -05003094 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3095 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3096 // proxy is null then there is no proxy in place).
3097 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3098 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3099 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3100 proxy = null;
3101 }
3102 return proxy;
3103 }
3104
3105 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3106 // better for determining if a new proxy broadcast is necessary:
3107 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3108 // avoid unnecessary broadcasts.
3109 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3110 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3111 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3112 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3113 // all set.
3114 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3115 a = canonicalizeProxyInfo(a);
3116 b = canonicalizeProxyInfo(b);
3117 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3118 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3119 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3120 }
3121
Jason Monk207900c2014-04-25 15:00:09 -04003122 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003123 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003124
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003125 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003126 if (proxyProperties == mGlobalProxy) return;
3127 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3128 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3129
3130 String host = "";
3131 int port = 0;
3132 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003133 String pacFileUrl = "";
3134 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003135 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003136 if (!proxyProperties.isValid()) {
3137 if (DBG)
3138 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3139 return;
3140 }
Jason Monk207900c2014-04-25 15:00:09 -04003141 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003142 host = mGlobalProxy.getHost();
3143 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003144 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003145 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003146 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003147 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003148 } else {
3149 mGlobalProxy = null;
3150 }
3151 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003152 final long token = Binder.clearCallingIdentity();
3153 try {
3154 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3155 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3156 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3157 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003158 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003159 } finally {
3160 Binder.restoreCallingIdentity(token);
3161 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003162
Jason Monkcf0f97a2014-10-02 15:39:38 -04003163 if (mGlobalProxy == null) {
3164 proxyProperties = mDefaultProxy;
3165 }
3166 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003167 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003168 }
3169
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003170 private void loadGlobalProxy() {
3171 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003172 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3173 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3174 String exclList = Settings.Global.getString(res,
3175 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003176 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3177 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003178 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003179 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003180 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003181 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003182 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003183 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003184 if (!proxyProperties.isValid()) {
3185 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3186 return;
3187 }
3188
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003189 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003190 mGlobalProxy = proxyProperties;
3191 }
3192 }
3193 }
3194
Jason Monk207900c2014-04-25 15:00:09 -04003195 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003196 // this information is already available as a world read/writable jvm property
3197 // so this API change wouldn't have a benifit. It also breaks the passing
3198 // of proxy info to all the JVMs.
3199 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003200 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003201 return mGlobalProxy;
3202 }
3203 }
3204
Jason Monk207900c2014-04-25 15:00:09 -04003205 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003206 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003207 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003208 proxy = null;
3209 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003210 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003211 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003212 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003213 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003214 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3215 return;
3216 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003217
3218 // This call could be coming from the PacManager, containing the port of the local
3219 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3220 // global (to get the correct local port), and send a broadcast.
3221 // TODO: Switch PacManager to have its own message to send back rather than
3222 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003223 if ((mGlobalProxy != null) && (proxy != null)
3224 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003225 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3226 mGlobalProxy = proxy;
3227 sendProxyBroadcast(mGlobalProxy);
3228 return;
3229 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003230 mDefaultProxy = proxy;
3231
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003232 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003233 if (!mDefaultProxyDisabled) {
3234 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003235 }
3236 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003237 }
3238
Paul Jensene0bef712014-12-10 15:12:18 -05003239 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3240 // This method gets called when any network changes proxy, but the broadcast only ever contains
3241 // the default proxy (even if it hasn't changed).
3242 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3243 // world where an app might be bound to a non-default network.
3244 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3245 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3246 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3247
3248 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3249 sendProxyBroadcast(getDefaultProxy());
3250 }
3251 }
3252
Robert Greenwalt434203a2010-10-11 16:00:27 -07003253 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003254 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3255 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003256 if (!TextUtils.isEmpty(proxy)) {
3257 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003258 if (data.length == 0) {
3259 return;
3260 }
3261
Robert Greenwalt434203a2010-10-11 16:00:27 -07003262 String proxyHost = data[0];
3263 int proxyPort = 8080;
3264 if (data.length > 1) {
3265 try {
3266 proxyPort = Integer.parseInt(data[1]);
3267 } catch (NumberFormatException e) {
3268 return;
3269 }
3270 }
Jason Monk207900c2014-04-25 15:00:09 -04003271 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003272 setGlobalProxy(p);
3273 }
3274 }
3275
Jason Monk207900c2014-04-25 15:00:09 -04003276 private void sendProxyBroadcast(ProxyInfo proxy) {
3277 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003278 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003279 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003280 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003281 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3282 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003283 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003284 final long ident = Binder.clearCallingIdentity();
3285 try {
3286 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3287 } finally {
3288 Binder.restoreCallingIdentity(ident);
3289 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003290 }
3291
3292 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003293 final private HashMap<Uri, Integer> mUriEventMap;
3294 final private Context mContext;
3295 final private Handler mHandler;
3296
3297 SettingsObserver(Context context, Handler handler) {
3298 super(null);
3299 mUriEventMap = new HashMap<Uri, Integer>();
3300 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003301 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003302 }
3303
Erik Klineda4bfa82015-04-30 12:58:40 +09003304 void observe(Uri uri, int what) {
3305 mUriEventMap.put(uri, what);
3306 final ContentResolver resolver = mContext.getContentResolver();
3307 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003308 }
3309
3310 @Override
3311 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003312 Slog.wtf(TAG, "Should never be reached.");
3313 }
3314
3315 @Override
3316 public void onChange(boolean selfChange, Uri uri) {
3317 final Integer what = mUriEventMap.get(uri);
3318 if (what != null) {
3319 mHandler.obtainMessage(what.intValue()).sendToTarget();
3320 } else {
3321 loge("No matching event to send for URI=" + uri);
3322 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003323 }
3324 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003325
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003326 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003327 Slog.d(TAG, s);
3328 }
3329
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003330 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003331 Slog.e(TAG, s);
3332 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003333
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003334 private static void loge(String s, Throwable t) {
3335 Slog.e(TAG, s, t);
3336 }
3337
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003338 private static <T> T checkNotNull(T value, String message) {
3339 if (value == null) {
3340 throw new NullPointerException(message);
3341 }
3342 return value;
3343 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003344
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003345 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003346 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003347 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3348 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3349 *
3350 * @param oldPackage Package name of the application which currently controls VPN, which will
3351 * be replaced. If there is no such application, this should should either be
3352 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3353 * @param newPackage Package name of the application which should gain control of VPN, or
3354 * {@code null} to disable.
3355 * @param userId User for whom to prepare the new VPN.
3356 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003357 * @hide
3358 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003359 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003360 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3361 int userId) {
3362 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003363 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003364
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003365 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003366 Vpn vpn = mVpns.get(userId);
3367 if (vpn != null) {
3368 return vpn.prepare(oldPackage, newPackage);
3369 } else {
3370 return false;
3371 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003372 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003373 }
3374
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003375 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003376 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3377 * This method is used by system-privileged apps.
3378 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3379 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3380 *
3381 * @param packageName The package for which authorization state should change.
3382 * @param userId User for whom {@code packageName} is installed.
3383 * @param authorized {@code true} if this app should be able to start a VPN connection without
3384 * explicit user approval, {@code false} if not.
3385 *
Jeff Davidson05542602014-08-11 14:07:27 -07003386 * @hide
3387 */
3388 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003389 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3390 enforceCrossUserPermission(userId);
3391
Jeff Davidson05542602014-08-11 14:07:27 -07003392 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003393 Vpn vpn = mVpns.get(userId);
3394 if (vpn != null) {
3395 vpn.setPackageAuthorization(packageName, authorized);
3396 }
Jeff Davidson05542602014-08-11 14:07:27 -07003397 }
3398 }
3399
3400 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003401 * Configure a TUN interface and return its file descriptor. Parameters
3402 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003403 * and not available in ConnectivityManager. Permissions are checked in
3404 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003405 * @hide
3406 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003407 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003408 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003409 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003410 int user = UserHandle.getUserId(Binder.getCallingUid());
3411 synchronized(mVpns) {
3412 return mVpns.get(user).establish(config);
3413 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003414 }
3415
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003416 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003417 * Start legacy VPN, controlling native daemons as needed. Creates a
3418 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003419 */
3420 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003421 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003422 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003423 final LinkProperties egress = getActiveLinkProperties();
3424 if (egress == null) {
3425 throw new IllegalStateException("Missing active network connection");
3426 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003427 int user = UserHandle.getUserId(Binder.getCallingUid());
3428 synchronized(mVpns) {
3429 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3430 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003431 }
3432
3433 /**
3434 * Return the information of the ongoing legacy VPN. This method is used
3435 * by VpnSettings and not available in ConnectivityManager. Permissions
3436 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003437 */
3438 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003439 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3440 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003441
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003442 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003443 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003444 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003445 }
3446
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003447 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003448 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3449 * and not available in ConnectivityManager.
3450 */
3451 @Override
3452 public VpnInfo[] getAllVpnInfo() {
3453 enforceConnectivityInternalPermission();
3454 if (mLockdownEnabled) {
3455 return new VpnInfo[0];
3456 }
3457
3458 synchronized(mVpns) {
3459 List<VpnInfo> infoList = new ArrayList<>();
3460 for (int i = 0; i < mVpns.size(); i++) {
3461 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3462 if (info != null) {
3463 infoList.add(info);
3464 }
3465 }
3466 return infoList.toArray(new VpnInfo[infoList.size()]);
3467 }
3468 }
3469
3470 /**
3471 * @return VPN information for accounting, or null if we can't retrieve all required
3472 * information, e.g primary underlying iface.
3473 */
3474 @Nullable
3475 private VpnInfo createVpnInfo(Vpn vpn) {
3476 VpnInfo info = vpn.getVpnInfo();
3477 if (info == null) {
3478 return null;
3479 }
3480 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3481 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3482 // the underlyingNetworks list.
3483 if (underlyingNetworks == null) {
3484 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3485 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3486 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3487 }
3488 } else if (underlyingNetworks.length > 0) {
3489 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3490 if (linkProperties != null) {
3491 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3492 }
3493 }
3494 return info.primaryUnderlyingIface == null ? null : info;
3495 }
3496
3497 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003498 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3499 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003500 * Permissions are checked in Vpn class.
3501 * @hide
3502 */
3503 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003504 public VpnConfig getVpnConfig(int userId) {
3505 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003506 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003507 Vpn vpn = mVpns.get(userId);
3508 if (vpn != null) {
3509 return vpn.getVpnConfig();
3510 } else {
3511 return null;
3512 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003513 }
3514 }
3515
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003516 @Override
3517 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003518 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3519 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3520 return false;
3521 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003522
3523 // Tear down existing lockdown if profile was removed
3524 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3525 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003526 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3527 if (profileTag == null) {
3528 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3529 return false;
3530 }
3531 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003532 final VpnProfile profile = VpnProfile.decode(
3533 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003534 if (profile == null) {
3535 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3536 setLockdownTracker(null);
3537 return true;
3538 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003539 int user = UserHandle.getUserId(Binder.getCallingUid());
3540 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003541 Vpn vpn = mVpns.get(user);
3542 if (vpn == null) {
3543 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3544 return false;
3545 }
3546 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003547 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003548 } else {
3549 setLockdownTracker(null);
3550 }
3551
3552 return true;
3553 }
3554
3555 /**
3556 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3557 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3558 */
3559 private void setLockdownTracker(LockdownVpnTracker tracker) {
3560 // Shutdown any existing tracker
3561 final LockdownVpnTracker existing = mLockdownTracker;
3562 mLockdownTracker = null;
3563 if (existing != null) {
3564 existing.shutdown();
3565 }
3566
3567 try {
3568 if (tracker != null) {
3569 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003570 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003571 mLockdownTracker = tracker;
3572 mLockdownTracker.init();
3573 } else {
3574 mNetd.setFirewallEnabled(false);
3575 }
3576 } catch (RemoteException e) {
3577 // ignored; NMS lives inside system_server
3578 }
3579 }
3580
3581 private void throwIfLockdownEnabled() {
3582 if (mLockdownEnabled) {
3583 throw new IllegalStateException("Unavailable in lockdown mode");
3584 }
3585 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003586
Robin Lee244ce8e2016-01-05 18:03:46 +00003587 /**
Robin Lee17e61832016-05-09 13:46:28 +01003588 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3589 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003590 *
Robin Lee17e61832016-05-09 13:46:28 +01003591 * @return {@code true} if the service was started, the service was already connected, or there
3592 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003593 */
Robin Lee17e61832016-05-09 13:46:28 +01003594 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003595 synchronized (mVpns) {
3596 Vpn vpn = mVpns.get(userId);
3597 if (vpn == null) {
3598 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3599 // exists already.
3600 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3601 return false;
3602 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003603
Robin Lee812800c2016-05-13 15:38:08 +01003604 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003605 }
3606 }
3607
3608 @Override
Robin Leedc679712016-05-03 13:23:03 +01003609 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003610 enforceConnectivityInternalPermission();
3611 enforceCrossUserPermission(userId);
3612
3613 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3614 if (LockdownVpnTracker.isEnabled()) {
3615 return false;
3616 }
3617
Robin Lee244ce8e2016-01-05 18:03:46 +00003618 synchronized (mVpns) {
3619 Vpn vpn = mVpns.get(userId);
3620 if (vpn == null) {
3621 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3622 return false;
3623 }
Robin Lee17e61832016-05-09 13:46:28 +01003624 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003625 return false;
3626 }
Robin Lee17e61832016-05-09 13:46:28 +01003627 if (!startAlwaysOnVpn(userId)) {
3628 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003629 return false;
3630 }
Robin Lee17e61832016-05-09 13:46:28 +01003631
Robin Lee812800c2016-05-13 15:38:08 +01003632 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003633 }
3634 return true;
3635 }
3636
3637 @Override
3638 public String getAlwaysOnVpnPackage(int userId) {
3639 enforceConnectivityInternalPermission();
3640 enforceCrossUserPermission(userId);
3641
3642 synchronized (mVpns) {
3643 Vpn vpn = mVpns.get(userId);
3644 if (vpn == null) {
3645 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3646 return null;
3647 }
3648 return vpn.getAlwaysOnPackage();
3649 }
3650 }
3651
Wink Savilleab9321d2013-06-29 21:10:57 -07003652 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003653 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003654 // TODO: Remove? Any reason to trigger a provisioning check?
3655 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003656 }
3657
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003658 /** Location to an updatable file listing carrier provisioning urls.
3659 * An example:
3660 *
3661 * <?xml version="1.0" encoding="utf-8"?>
3662 * <provisioningUrls>
3663 * <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 -07003664 * </provisioningUrls>
3665 */
3666 private static final String PROVISIONING_URL_PATH =
3667 "/data/misc/radio/provisioning_urls.xml";
3668 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003669
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003670 /** XML tag for root element. */
3671 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3672 /** XML tag for individual url */
3673 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003674 /** XML attribute for mcc */
3675 private static final String ATTR_MCC = "mcc";
3676 /** XML attribute for mnc */
3677 private static final String ATTR_MNC = "mnc";
3678
Paul Jensen434dde82015-06-11 09:43:30 -04003679 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003680 FileReader fileReader = null;
3681 XmlPullParser parser = null;
3682 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003683
3684 try {
3685 fileReader = new FileReader(mProvisioningUrlFile);
3686 parser = Xml.newPullParser();
3687 parser.setInput(fileReader);
3688 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3689
3690 while (true) {
3691 XmlUtils.nextElement(parser);
3692
3693 String element = parser.getName();
3694 if (element == null) break;
3695
Paul Jensen434dde82015-06-11 09:43:30 -04003696 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003697 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3698 try {
3699 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3700 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3701 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3702 parser.next();
3703 if (parser.getEventType() == XmlPullParser.TEXT) {
3704 return parser.getText();
3705 }
3706 }
3707 }
3708 } catch (NumberFormatException e) {
3709 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3710 }
3711 }
3712 }
3713 return null;
3714 } catch (FileNotFoundException e) {
3715 loge("Carrier Provisioning Urls file not found");
3716 } catch (XmlPullParserException e) {
3717 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3718 } catch (IOException e) {
3719 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3720 } finally {
3721 if (fileReader != null) {
3722 try {
3723 fileReader.close();
3724 } catch (IOException e) {}
3725 }
3726 }
3727 return null;
3728 }
3729
Wink Saville42d4f082013-07-20 20:31:59 -07003730 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003731 public String getMobileProvisioningUrl() {
3732 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003733 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003734 if (TextUtils.isEmpty(url)) {
3735 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003736 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003737 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003738 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003739 }
Wink Saville8cf35602013-07-10 23:00:07 -07003740 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003741 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003742 String phoneNumber = mTelephonyManager.getLine1Number();
3743 if (TextUtils.isEmpty(phoneNumber)) {
3744 phoneNumber = "0000000000";
3745 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003746 url = String.format(url,
3747 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3748 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003749 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003750 }
3751
Wink Savilleab9321d2013-06-29 21:10:57 -07003752 return url;
3753 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003754
Wink Saville948282b2013-08-29 08:55:16 -07003755 @Override
3756 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003757 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003758 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003759 final long ident = Binder.clearCallingIdentity();
3760 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003761 // Concatenate the range of types onto the range of NetIDs.
3762 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3763 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003764 } finally {
3765 Binder.restoreCallingIdentity(ident);
3766 }
Wink Saville948282b2013-08-29 08:55:16 -07003767 }
Wink Saville7788c612013-08-29 14:57:08 -07003768
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003769 @Override
3770 public void setAirplaneMode(boolean enable) {
3771 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003772 final long ident = Binder.clearCallingIdentity();
3773 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003774 final ContentResolver cr = mContext.getContentResolver();
3775 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3776 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3777 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003778 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003779 } finally {
3780 Binder.restoreCallingIdentity(ident);
3781 }
3782 }
3783
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003784 private void onUserStart(int userId) {
3785 synchronized(mVpns) {
3786 Vpn userVpn = mVpns.get(userId);
3787 if (userVpn != null) {
3788 loge("Starting user already has a VPN");
3789 return;
3790 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003791 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003792 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003793
3794 final ContentResolver cr = mContext.getContentResolver();
3795 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3796 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3797 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3798 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3799 if (alwaysOnPackage != null) {
3800 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3801 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003802 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003803 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3804 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003805 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003806 }
3807
3808 private void onUserStop(int userId) {
3809 synchronized(mVpns) {
3810 Vpn userVpn = mVpns.get(userId);
3811 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003812 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003813 return;
3814 }
Robin Lee17e61832016-05-09 13:46:28 +01003815 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003816 mVpns.delete(userId);
3817 }
3818 }
3819
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003820 private void onUserAdded(int userId) {
3821 synchronized(mVpns) {
3822 final int vpnsSize = mVpns.size();
3823 for (int i = 0; i < vpnsSize; i++) {
3824 Vpn vpn = mVpns.valueAt(i);
3825 vpn.onUserAdded(userId);
3826 }
3827 }
3828 }
3829
3830 private void onUserRemoved(int userId) {
3831 synchronized(mVpns) {
3832 final int vpnsSize = mVpns.size();
3833 for (int i = 0; i < vpnsSize; i++) {
3834 Vpn vpn = mVpns.valueAt(i);
3835 vpn.onUserRemoved(userId);
3836 }
3837 }
3838 }
3839
Robin Lee89e7a692016-02-29 14:38:17 +00003840 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003841 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3842 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3843 updateLockdownVpn();
3844 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003845 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003846 }
3847 }
3848
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003849 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3850 @Override
3851 public void onReceive(Context context, Intent intent) {
3852 final String action = intent.getAction();
3853 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3854 if (userId == UserHandle.USER_NULL) return;
3855
Robin Lee323f29d2016-05-04 16:38:06 +01003856 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003857 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003858 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003859 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003860 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3861 onUserAdded(userId);
3862 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3863 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003864 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3865 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003866 }
3867 }
3868 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003869
Robin Lee95204e02017-01-27 11:59:22 +00003870 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3871 @Override
3872 public void onReceive(Context context, Intent intent) {
3873 // Try creating lockdown tracker, since user present usually means
3874 // unlocked keystore.
3875 updateLockdownVpn();
3876 mContext.unregisterReceiver(this);
3877 }
3878 };
3879
Robert Greenwalta67be032014-05-16 15:49:14 -07003880 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3881 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003882 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3883 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003884
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003885 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3886 // Map from UID to number of NetworkRequests that UID has filed.
3887 @GuardedBy("mUidToNetworkRequestCount")
3888 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3889
Robert Greenwalta67be032014-05-16 15:49:14 -07003890 private static class NetworkFactoryInfo {
3891 public final String name;
3892 public final Messenger messenger;
3893 public final AsyncChannel asyncChannel;
3894
3895 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3896 this.name = name;
3897 this.messenger = messenger;
3898 this.asyncChannel = asyncChannel;
3899 }
3900 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003901
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003902 private void ensureNetworkRequestHasType(NetworkRequest request) {
3903 if (request.type == NetworkRequest.Type.NONE) {
3904 throw new IllegalArgumentException(
3905 "All NetworkRequests in ConnectivityService must have a type");
3906 }
3907 }
3908
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003909 /**
3910 * Tracks info about the requester.
3911 * Also used to notice when the calling process dies so we can self-expire
3912 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003913 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003914 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003915 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003916 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003917 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003918 final int mPid;
3919 final int mUid;
3920 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003921
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003922 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003923 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003924 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003925 mPendingIntent = pi;
3926 messenger = null;
3927 mBinder = null;
3928 mPid = getCallingPid();
3929 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003930 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003931 }
3932
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003933 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003934 super();
3935 messenger = m;
3936 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003937 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003938 mBinder = binder;
3939 mPid = getCallingPid();
3940 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003941 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003942 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003943
3944 try {
3945 mBinder.linkToDeath(this, 0);
3946 } catch (RemoteException e) {
3947 binderDied();
3948 }
3949 }
3950
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003951 private void enforceRequestCountLimit() {
3952 synchronized (mUidToNetworkRequestCount) {
3953 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3954 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3955 throw new IllegalArgumentException("Too many NetworkRequests filed");
3956 }
3957 mUidToNetworkRequestCount.put(mUid, networkRequests);
3958 }
3959 }
3960
Robert Greenwalt9258c642014-03-26 16:47:06 -07003961 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003962 if (mBinder != null) {
3963 mBinder.unlinkToDeath(this, 0);
3964 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003965 }
3966
3967 public void binderDied() {
3968 log("ConnectivityService NetworkRequestInfo binderDied(" +
3969 request + ", " + mBinder + ")");
3970 releaseNetworkRequest(request);
3971 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003972
3973 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003974 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003975 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003976 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003977 }
3978
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003979 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3980 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3981 if (badCapability != null) {
3982 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003983 }
3984 }
3985
Erik Kline9d598e12015-07-13 16:37:51 +09003986 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003987 final SortedSet<Integer> thresholds = new TreeSet();
3988 synchronized (nai) {
3989 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3990 if (nri.request.networkCapabilities.hasSignalStrength() &&
3991 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3992 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3993 }
3994 }
3995 }
Erik Kline9d598e12015-07-13 16:37:51 +09003996 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003997 }
3998
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003999 private void updateSignalStrengthThresholds(
4000 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4001 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004002 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004003 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4004
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004005 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004006 String detail;
4007 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4008 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4009 } else {
4010 detail = reason;
4011 }
4012 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4013 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4014 }
4015
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004016 nai.asyncChannel.sendMessage(
4017 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004018 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004019 }
4020
Robert Greenwalt9258c642014-03-26 16:47:06 -07004021 @Override
4022 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004023 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004024 final NetworkRequest.Type type = (networkCapabilities == null)
4025 ? NetworkRequest.Type.TRACK_DEFAULT
4026 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004027 // If the requested networkCapabilities is null, take them instead from
4028 // the default network request. This allows callers to keep track of
4029 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004030 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004031 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4032 enforceAccessPermission();
4033 } else {
4034 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4035 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004036 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4037 // of the app when the request is filed, but we never change the request if the app
4038 // changes network state. http://b/29964605
4039 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004040 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004041 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004042
Etan Cohenba07c8c2017-02-05 10:42:27 -08004043 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004044 throw new IllegalArgumentException("Bad timeout specified");
4045 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004046
Etan Cohenddb9ef02015-11-18 10:56:15 -08004047 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4048 .equals(networkCapabilities.getNetworkSpecifier())) {
4049 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4050 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4051 }
4052
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004053 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004054 nextNetworkRequestId(), type);
4055 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004056 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004057
4058 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004059 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004061 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004062 }
4063 return networkRequest;
4064 }
4065
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004066 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004067 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004068 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004069 } else {
4070 enforceChangePermission();
4071 }
4072 }
4073
fenglub15e72b2015-03-20 11:29:56 -07004074 @Override
fengludb571472015-04-21 17:12:05 -07004075 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004076 enforceAccessPermission();
4077 NetworkAgentInfo nai = null;
4078 if (network == null) {
4079 return false;
4080 }
4081 synchronized (mNetworkForNetId) {
4082 nai = mNetworkForNetId.get(network.netId);
4083 }
4084 if (nai != null) {
4085 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4086 return true;
4087 }
4088 return false;
4089 }
4090
Felipe Lemeee27cab2016-06-20 16:36:29 -07004091 private boolean isSystem(int uid) {
4092 return uid < Process.FIRST_APPLICATION_UID;
4093 }
fenglub15e72b2015-03-20 11:29:56 -07004094
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004095 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004096 final int uid = Binder.getCallingUid();
4097 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004098 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004099 return;
4100 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004101 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4102 // Policy already enforced.
4103 return;
4104 }
4105 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4106 // If UID is restricted, don't allow them to bring up metered APNs.
4107 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004108 }
4109 }
4110
Robert Greenwalt9258c642014-03-26 16:47:06 -07004111 @Override
4112 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4113 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004114 checkNotNull(operation, "PendingIntent cannot be null.");
4115 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4116 enforceNetworkRequestPermissions(networkCapabilities);
4117 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004118 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004119
4120 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004121 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4122 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004123 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004124 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4125 nri));
4126 return networkRequest;
4127 }
4128
Jeremy Joslin79294842014-12-03 17:15:28 -08004129 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4130 mHandler.sendMessageDelayed(
4131 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4132 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4133 }
4134
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004135 @Override
4136 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004137 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004138 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4139 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004140 }
4141
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004142 // In order to implement the compatibility measure for pre-M apps that call
4143 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4144 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4145 // This ensures it has permission to do so.
4146 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4147 if (nc == null) {
4148 return false;
4149 }
4150 int[] transportTypes = nc.getTransportTypes();
4151 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4152 return false;
4153 }
4154 try {
4155 mContext.enforceCallingOrSelfPermission(
4156 android.Manifest.permission.ACCESS_WIFI_STATE,
4157 "ConnectivityService");
4158 } catch (SecurityException e) {
4159 return false;
4160 }
4161 return true;
4162 }
4163
Robert Greenwalt9258c642014-03-26 16:47:06 -07004164 @Override
4165 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4166 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004167 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4168 enforceAccessPermission();
4169 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004170
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004171 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4172 if (!ConnectivityManager.checkChangePermission(mContext)) {
4173 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4174 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4175 // onLost and onAvailable callbacks when networks move in and out of the background.
4176 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4177 // can't request networks.
4178 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4179 }
4180
4181 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004182 NetworkRequest.Type.LISTEN);
4183 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004184 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004185
4186 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4187 return networkRequest;
4188 }
4189
4190 @Override
4191 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4192 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004193 checkNotNull(operation, "PendingIntent cannot be null.");
4194 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4195 enforceAccessPermission();
4196 }
4197
Erik Kline7523eb32015-07-09 18:24:03 +09004198 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004199 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4200 NetworkRequest.Type.LISTEN);
4201 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004202 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004203
4204 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004205 }
4206
Erik Klineacdd6392016-07-07 16:50:58 +09004207 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004208 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004209 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004210 mHandler.sendMessage(mHandler.obtainMessage(
4211 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004212 }
4213
4214 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004215 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004216 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004217 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4218 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004219 }
4220
Robert Greenwalta67be032014-05-16 15:49:14 -07004221 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004222 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004223 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4224 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4225 }
4226
4227 @Override
4228 public void unregisterNetworkFactory(Messenger messenger) {
4229 enforceConnectivityInternalPermission();
4230 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4231 }
4232
4233 private void handleUnregisterNetworkFactory(Messenger messenger) {
4234 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4235 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004236 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004237 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004238 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004239 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004240 }
4241
Robert Greenwalt7b816022014-04-18 15:25:25 -07004242 /**
4243 * NetworkAgentInfo supporting a request by requestId.
4244 * These have already been vetted (their Capabilities satisfy the request)
4245 * and the are the highest scored network available.
4246 * the are keyed off the Requests requestId.
4247 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004248 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004249 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4250 new SparseArray<NetworkAgentInfo>();
4251
Paul Jensen31a94f42015-02-13 14:18:39 -05004252 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4253 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004254 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4255 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004256 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4257 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4258 // there may not be a strict 1:1 correlation between the two.
4259 @GuardedBy("mNetworkForNetId")
4260 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004261
Robert Greenwalt7b816022014-04-18 15:25:25 -07004262 // NetworkAgentInfo keyed off its connecting messenger
4263 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004264 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004265 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4266 new HashMap<Messenger, NetworkAgentInfo>();
4267
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004268 @GuardedBy("mBlockedAppUids")
4269 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4270
Paul Jensen2c311d62014-11-17 12:34:51 -05004271 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004272 private final NetworkRequest mDefaultRequest;
4273
Erik Klineda4bfa82015-04-30 12:58:40 +09004274 // Request used to optionally keep mobile data active even when higher
4275 // priority networks like Wi-Fi are active.
4276 private final NetworkRequest mDefaultMobileDataRequest;
4277
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004278 private NetworkAgentInfo getDefaultNetwork() {
4279 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4280 }
4281
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004282 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004283 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004284 }
4285
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004286 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4287 return nri.request.requestId == mDefaultRequest.requestId;
4288 }
4289
Paul Jensen31a94f42015-02-13 14:18:39 -05004290 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004291 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004292 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004293 enforceConnectivityInternalPermission();
4294
Paul Jensen2c311d62014-11-17 12:34:51 -05004295 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4296 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004297 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004298 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4299 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004300 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004301 synchronized (this) {
4302 nai.networkMonitor.systemReady = mSystemReady;
4303 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004304 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4305 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004306 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004307 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004308 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004309 }
4310
4311 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4312 if (VDBG) log("Got NetworkAgent Messenger");
4313 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004314 synchronized (mNetworkForNetId) {
4315 mNetworkForNetId.put(na.network.netId, na);
4316 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004317 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4318 NetworkInfo networkInfo = na.networkInfo;
4319 na.networkInfo = null;
4320 updateNetworkInfo(na, networkInfo);
4321 }
4322
4323 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4324 LinkProperties newLp = networkAgent.linkProperties;
4325 int netId = networkAgent.network.netId;
4326
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004327 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4328 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004329 if (networkAgent.clatd != null) {
4330 networkAgent.clatd.fixupLinkProperties(oldLp);
4331 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004332
Paul Jensen992f2522014-04-28 10:33:11 -04004333 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004334 updateMtu(newLp, oldLp);
4335 // TODO - figure out what to do for clat
4336// for (LinkProperties lp : newLp.getStackedLinks()) {
4337// updateMtu(lp, null);
4338// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004339 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004340
Erik Kline94887872016-04-05 13:30:49 +09004341 updateRoutes(newLp, oldLp, netId);
4342 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004343
Paul Jensen3b759822014-05-13 11:44:01 -04004344 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004345 if (isDefaultNetwork(networkAgent)) {
4346 handleApplyDefaultProxy(newLp.getHttpProxy());
4347 } else {
4348 updateProxy(newLp, oldLp, networkAgent);
4349 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004350 // TODO - move this check to cover the whole function
4351 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004352 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004353 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4354 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004355
4356 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004357 }
4358
Lorenzo Colitti95439462014-10-09 13:44:48 +09004359 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4360 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4361 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004362
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004363 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004364 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4365 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004366 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004367 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004368 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004369 }
Paul Jensen992f2522014-04-28 10:33:11 -04004370
4371 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4372 CompareResult<String> interfaceDiff = new CompareResult<String>();
4373 if (oldLp != null) {
4374 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4375 } else if (newLp != null) {
4376 interfaceDiff.added = newLp.getAllInterfaceNames();
4377 }
4378 for (String iface : interfaceDiff.added) {
4379 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004380 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004381 mNetd.addInterfaceToNetwork(iface, netId);
4382 } catch (Exception e) {
4383 loge("Exception adding interface: " + e);
4384 }
4385 }
4386 for (String iface : interfaceDiff.removed) {
4387 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004388 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004389 mNetd.removeInterfaceFromNetwork(iface, netId);
4390 } catch (Exception e) {
4391 loge("Exception removing interface: " + e);
4392 }
4393 }
4394 }
4395
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004396 /**
4397 * Have netd update routes from oldLp to newLp.
4398 * @return true if routes changed between oldLp and newLp
4399 */
4400 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004401 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4402 if (oldLp != null) {
4403 routeDiff = oldLp.compareAllRoutes(newLp);
4404 } else if (newLp != null) {
4405 routeDiff.added = newLp.getAllRoutes();
4406 }
4407
4408 // add routes before removing old in case it helps with continuous connectivity
4409
4410 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4411 for (RouteInfo route : routeDiff.added) {
4412 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004413 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004414 try {
4415 mNetd.addRoute(netId, route);
4416 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004417 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4418 loge("Exception in addRoute for non-gateway: " + e);
4419 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004420 }
4421 }
4422 for (RouteInfo route : routeDiff.added) {
4423 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004424 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004425 try {
4426 mNetd.addRoute(netId, route);
4427 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004428 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4429 loge("Exception in addRoute for gateway: " + e);
4430 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004431 }
4432 }
4433
4434 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004435 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004436 try {
4437 mNetd.removeRoute(netId, route);
4438 } catch (Exception e) {
4439 loge("Exception in removeRoute: " + e);
4440 }
4441 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004442 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004443 }
Erik Kline41368502015-06-17 13:19:54 +09004444
Erik Kline94887872016-04-05 13:30:49 +09004445 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4446 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4447 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004448 }
Erik Kline94887872016-04-05 13:30:49 +09004449
4450 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004451 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004452 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004453 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004454 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4455 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004456 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004457 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004458 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4459 if (defaultNai != null && defaultNai.network.netId == netId) {
4460 setDefaultDnsSystemProperties(dnses);
4461 }
Erik Kline94887872016-04-05 13:30:49 +09004462 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004463 }
4464
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004465 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4466 int last = 0;
4467 for (InetAddress dns : dnses) {
4468 ++last;
4469 String key = "net.dns" + last;
4470 String value = dns.getHostAddress();
4471 SystemProperties.set(key, value);
4472 }
4473 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4474 String key = "net.dns" + i;
4475 SystemProperties.set(key, "");
4476 }
4477 mNumDnsEntries = last;
4478 }
4479
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004480 private String getNetworkPermission(NetworkCapabilities nc) {
4481 // TODO: make these permission strings AIDL constants instead.
4482 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4483 return NetworkManagementService.PERMISSION_SYSTEM;
4484 }
4485 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4486 return NetworkManagementService.PERMISSION_NETWORK;
4487 }
4488 return null;
4489 }
4490
Paul Jensen3d194ea2015-06-16 14:27:36 -04004491 /**
4492 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4493 * augmented with any stateful capabilities implied from {@code networkAgent}
4494 * (e.g., validated status and captive portal status).
4495 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004496 * @param oldScore score of the network before any of the changes that prompted us
4497 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004498 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004499 * @param networkCapabilities the new network capabilities.
4500 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004501 private void updateCapabilities(
4502 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004503 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4504 networkCapabilities)) {
4505 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4506 + nai.networkCapabilities + " -> " + networkCapabilities);
4507 }
4508
Paul Jensen3d194ea2015-06-16 14:27:36 -04004509 // Don't modify caller's NetworkCapabilities.
4510 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004511 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004512 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4513 } else {
4514 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4515 }
Paul Jensene0988542015-06-25 15:30:08 -04004516 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004517 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4518 } else {
4519 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4520 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004521 if (nai.isBackgroundNetwork()) {
4522 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4523 } else {
4524 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4525 }
4526
4527 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4528
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004529 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4530 final String newPermission = getNetworkPermission(networkCapabilities);
4531 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004532 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004533 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004534 } catch (RemoteException e) {
4535 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004536 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004537 }
4538
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004539 final NetworkCapabilities prevNc = nai.networkCapabilities;
4540 synchronized (nai) {
4541 nai.networkCapabilities = networkCapabilities;
4542 }
4543 if (nai.getCurrentScore() == oldScore &&
4544 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4545 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4546 // the change we're processing can't affect any requests, it can only affect the listens
4547 // on this network. We might have been called by rematchNetworkAndRequests when a
4548 // network changed foreground state.
4549 processListenRequests(nai, true);
4550 } else {
4551 // If the requestable capabilities have changed or the score changed, we can't have been
4552 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004553 rematchAllNetworksAndRequests(nai, oldScore);
4554 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004555 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004556 }
4557
Paul Jensenc8b9a742014-09-30 15:37:41 -04004558 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004559 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4560 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004561 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004562 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004563 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4564 }
4565 }
4566
Robert Greenwalt7b816022014-04-18 15:25:25 -07004567 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4568 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004569 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004570 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4571 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004572 }
4573 }
4574
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004575 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4576 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004577 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004578 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004579 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4580 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004581 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004582 sendIntent(nri.mPendingIntent, intent);
4583 }
4584 // else not handled
4585 }
4586
4587 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4588 mPendingIntentWakeLock.acquire();
4589 try {
4590 if (DBG) log("Sending " + pendingIntent);
4591 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4592 } catch (PendingIntent.CanceledException e) {
4593 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4594 mPendingIntentWakeLock.release();
4595 releasePendingNetworkRequest(pendingIntent);
4596 }
4597 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4598 }
4599
4600 @Override
4601 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4602 String resultData, Bundle resultExtras) {
4603 if (DBG) log("Finished sending " + pendingIntent);
4604 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004605 // Release with a delay so the receiving client has an opportunity to put in its
4606 // own request.
4607 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004608 }
4609
Robert Greenwalt9258c642014-03-26 16:47:06 -07004610 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004611 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004612 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004613 Bundle bundle = new Bundle();
4614 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4615 new NetworkRequest(nri.request));
4616 Message msg = Message.obtain();
4617 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4618 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4619 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4620 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004621 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004622 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004623 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004624 break;
4625 }
4626 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4627 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4628 new NetworkCapabilities(networkAgent.networkCapabilities));
4629 break;
4630 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004631 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004632 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4633 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004634 break;
4635 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004636 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004637 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004638 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004639 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004640 if (VDBG) {
4641 log("sending notification " + notifyTypeToName(notificationType) +
4642 " for " + nri.request);
4643 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004644 nri.messenger.send(msg);
4645 } catch (RemoteException e) {
4646 // may occur naturally in the race of binder death.
4647 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4648 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004649 }
4650
Paul Jensenc8b9a742014-09-30 15:37:41 -04004651 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004652 if (nai.numRequestNetworkRequests() != 0) {
4653 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4654 NetworkRequest nr = nai.requestAt(i);
4655 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004656 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004657 loge("Dead network still had at least " + nr);
4658 break;
4659 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004660 }
4661 nai.asyncChannel.disconnect();
4662 }
4663
Robert Greenwalt7b816022014-04-18 15:25:25 -07004664 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4665 if (oldNetwork == null) {
4666 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4667 return;
4668 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004669 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004670
4671 // If we get here it means that the last linger timeout for this network expired. So there
4672 // must be no other active linger timers, and we must stop lingering.
4673 oldNetwork.clearLingerState();
4674
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004675 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004676 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004677 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004678 } else {
4679 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004680 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4681 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004682 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004683 }
4684
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004685 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004686 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004687 setupDataActivityTracking(newNetwork);
4688 try {
4689 mNetd.setDefaultNetId(newNetwork.network.netId);
4690 } catch (Exception e) {
4691 loge("Exception setting default network :" + e);
4692 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004693 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004694 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004695 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004696 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004697 }
4698
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004699 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004700 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4701 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4702 NetworkRequest nr = nri.request;
4703 if (!nr.isListen()) continue;
4704 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4705 nai.removeRequest(nri.request.requestId);
4706 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4707 }
4708 }
4709
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004710 if (capabilitiesChanged) {
4711 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4712 }
4713
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004714 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4715 NetworkRequest nr = nri.request;
4716 if (!nr.isListen()) continue;
4717 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4718 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004719 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004720 }
4721 }
4722 }
4723
Paul Jensen2161a8e2014-09-11 11:00:39 -04004724 // Handles a network appearing or improving its score.
4725 //
4726 // - Evaluates all current NetworkRequests that can be
4727 // satisfied by newNetwork, and reassigns to newNetwork
4728 // any such requests for which newNetwork is the best.
4729 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004730 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004731 // needed. A network is needed if it is the best network for
4732 // one or more NetworkRequests, or if it is a VPN.
4733 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004734 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004735 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004736 //
4737 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4738 // networks that have no chance (i.e. even if validated)
4739 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004740 //
4741 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4742 // it does not remove NetworkRequests that other Networks could better satisfy.
4743 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4744 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4745 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004746 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004747 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004748 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4749 // performed to tear down unvalidated networks that have no chance (i.e. even if
4750 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004751 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004752 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004753 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004754 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004755 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004756 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004757
4758 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4759 final int score = newNetwork.getCurrentScore();
4760
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004761 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004762
Paul Jensen2161a8e2014-09-11 11:00:39 -04004763 // Find and migrate to this Network any NetworkRequests for
4764 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004765 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004766 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004767 NetworkCapabilities nc = newNetwork.networkCapabilities;
4768 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004769 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004770 // Process requests in the first pass and listens in the second pass. This allows us to
4771 // change a network's capabilities depending on which requests it has. This is only
4772 // correct if the change in capabilities doesn't affect whether the network satisfies
4773 // requests or not, and doesn't affect the network's score.
4774 if (nri.request.isListen()) continue;
4775
Paul Jensencf4c2c62015-07-01 14:16:32 -04004776 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4777 final boolean satisfies = newNetwork.satisfies(nri.request);
4778 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004779 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004780 log("Network " + newNetwork.name() + " was already satisfying" +
4781 " request " + nri.request.requestId + ". No change.");
4782 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004783 keep = true;
4784 continue;
4785 }
4786
4787 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004788 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004789 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004790 // next check if it's better than any current network we're using for
4791 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004792 if (VDBG) {
4793 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004794 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004795 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004796 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004797 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004798 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004799 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004800 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004801 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004802 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004803 affectedNetworks.add(currentNetwork);
4804 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004805 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004806 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004807 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004808 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004809 if (!newNetwork.addRequest(nri.request)) {
4810 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4811 }
4812 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004813 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004814 // Tell NetworkFactories about the new score, so they can stop
4815 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004816 // TODO - this could get expensive if we have alot of requests for this
4817 // network. Think about if there is a way to reduce this. Push
4818 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004819 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004820 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004821 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004822 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004823 if (currentNetwork != null) {
4824 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4825 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004826 }
4827 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004828 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004829 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4830 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004831 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004832 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4833 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4834 // This means this code doesn't have to handle the case where "currentNetwork" no
4835 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4836 if (DBG) {
4837 log("Network " + newNetwork.name() + " stopped satisfying" +
4838 " request " + nri.request.requestId);
4839 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004840 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004841 if (currentNetwork == newNetwork) {
4842 mNetworkForRequestId.remove(nri.request.requestId);
4843 sendUpdatedScoreToFactories(nri.request, 0);
4844 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004845 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4846 newNetwork.name() +
4847 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004848 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004849 // TODO: Technically, sending CALLBACK_LOST here is
4850 // incorrect if there is a replacement network currently
4851 // connected that can satisfy nri, which is a request
4852 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004853 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4854 // so this code is only incorrect for a network that loses
4855 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004856 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004857 }
4858 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004859 if (isNewDefault) {
4860 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004861 makeDefault(newNetwork);
4862 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4863 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004864 synchronized (ConnectivityService.this) {
4865 // have a new default network, release the transition wakelock in
4866 // a second if it's held. The second pause is to allow apps
4867 // to reconnect over the new network
4868 if (mNetTransitionWakeLock.isHeld()) {
4869 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4870 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4871 mNetTransitionWakeLockSerialNumber, 0),
4872 1000);
4873 }
4874 }
4875 }
4876
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004877 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4878 Slog.wtf(TAG, String.format(
4879 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4880 nc, newNetwork.networkCapabilities));
4881 }
4882 if (newNetwork.getCurrentScore() != score) {
4883 Slog.wtf(TAG, String.format(
4884 "BUG: %s changed score during rematch: %d -> %d",
4885 score, newNetwork.getCurrentScore()));
4886 }
4887
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004888 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004889 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4890 // If the network went from background to foreground or vice versa, we need to update
4891 // its foreground state. It is safe to do this after rematching the requests because
4892 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4893 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004894 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004895 } else {
4896 processListenRequests(newNetwork, false);
4897 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004898
Paul Jensencf4c2c62015-07-01 14:16:32 -04004899 // do this after the default net is switched, but
4900 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09004901 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004902
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004903 // Linger any networks that are no longer needed. This should be done after sending the
4904 // available callback for newNetwork.
4905 for (NetworkAgentInfo nai : affectedNetworks) {
4906 updateLingerState(nai, now);
4907 }
4908 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4909 // does not need to be done in any particular order.
4910 updateLingerState(newNetwork, now);
4911
Paul Jensencf4c2c62015-07-01 14:16:32 -04004912 if (isNewDefault) {
4913 // Maintain the illusion: since the legacy API only
4914 // understands one network at a time, we must pretend
4915 // that the current default network disconnected before
4916 // the new one connected.
4917 if (oldDefaultNetwork != null) {
4918 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4919 oldDefaultNetwork, true);
4920 }
4921 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4922 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4923 notifyLockdownVpn(newNetwork);
4924 }
4925
Robert Greenwalt7b816022014-04-18 15:25:25 -07004926 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004927 // Notify battery stats service about this network, both the normal
4928 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004929 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004930 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004931 final IBatteryStats bs = BatteryStatsService.getService();
4932 final int type = newNetwork.networkInfo.getType();
4933
4934 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4935 bs.noteNetworkInterfaceType(baseIface, type);
4936 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4937 final String stackedIface = stacked.getInterfaceName();
4938 bs.noteNetworkInterfaceType(stackedIface, type);
4939 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4940 }
4941 } catch (RemoteException ignored) {
4942 }
4943
Robert Greenwalt152ed372014-12-17 17:19:53 -08004944 // This has to happen after the notifyNetworkCallbacks as that tickles each
4945 // ConnectivityManager instance so that legacy requests correctly bind dns
4946 // requests to this network. The legacy users are listening for this bcast
4947 // and will generally do a dns request so they can ensureRouteToHost and if
4948 // they do that before the callbacks happen they'll use the default network.
4949 //
4950 // TODO: Is there still a race here? We send the broadcast
4951 // after sending the callback, but if the app can receive the
4952 // broadcast before the callback, it might still break.
4953 //
4954 // This *does* introduce a race where if the user uses the new api
4955 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4956 // they may get old info. Reverse this after the old startUsing api is removed.
4957 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004958 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4959 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004960 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004961 // legacy type tracker filters out repeat adds
4962 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4963 }
4964 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004965
4966 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4967 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4968 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4969 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4970 if (newNetwork.isVPN()) {
4971 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4972 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004973 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004974 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4975 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004976 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004977 if (nai.getLingerExpiry() > 0) {
4978 // This network has active linger timers and no requests, but is not
4979 // lingering. Linger it.
4980 //
4981 // One way (the only way?) this can happen if this network is unvalidated
4982 // and became unneeded due to another network improving its score to the
4983 // point where this network will no longer be able to satisfy any requests
4984 // even if it validates.
4985 updateLingerState(nai, now);
4986 } else {
4987 if (DBG) log("Reaping " + nai.name());
4988 teardownUnneededNetwork(nai);
4989 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004990 }
4991 }
4992 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004993 }
4994
Paul Jensen1c7ba022015-06-16 14:27:36 -04004995 /**
4996 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4997 * being disconnected.
4998 * @param changed If only one Network's score or capabilities have been modified since the last
4999 * time this function was called, pass this Network in this argument, otherwise pass
5000 * null.
5001 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5002 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5003 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5004 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5005 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005006 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005007 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005008 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5009 // to avoid the slowness. It is not simply enough to process just "changed", for
5010 // example in the case where "changed"'s score decreases and another network should begin
5011 // satifying a NetworkRequest that "changed" currently satisfies.
5012
5013 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5014 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5015 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005016 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005017 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005018 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005019 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005020 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5021 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5022 // Rematch higher scoring networks first to prevent requests first matching a lower
5023 // scoring network and then a higher scoring network, which could produce multiple
5024 // callbacks and inadvertently unlinger networks.
5025 Arrays.sort(nais);
5026 for (NetworkAgentInfo nai : nais) {
5027 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005028 // Only reap the last time through the loop. Reaping before all rematching
5029 // is complete could incorrectly teardown a network that hasn't yet been
5030 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005031 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005032 : ReapUnvalidatedNetworks.REAP,
5033 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005034 }
5035 }
5036 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005037
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005038 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005039 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005040 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005041 // For now only update icons for default connection.
5042 // TODO: Update WiFi and cellular icons separately. b/17237507
5043 if (!isDefaultNetwork(nai)) return;
5044
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005045 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005046 // Don't repeat publish.
5047 if (newInetCondition == mDefaultInetConditionPublished) return;
5048
5049 mDefaultInetConditionPublished = newInetCondition;
5050 sendInetConditionBroadcast(nai.networkInfo);
5051 }
5052
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005053 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5054 if (mLockdownTracker != null) {
5055 if (nai != null && nai.isVPN()) {
5056 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5057 } else {
5058 mLockdownTracker.onNetworkInfoChanged();
5059 }
5060 }
5061 }
5062
Robert Greenwalt7b816022014-04-18 15:25:25 -07005063 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005064 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005065 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005066 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005067 synchronized (networkAgent) {
5068 oldInfo = networkAgent.networkInfo;
5069 networkAgent.networkInfo = newInfo;
5070 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005071 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005072
5073 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005074 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5075 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5076 notifyIfacesChangedForNetworkStats();
5077 } else if (VDBG) log("ignoring duplicate network state non-change");
5078 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005079 return;
5080 }
5081 if (DBG) {
5082 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5083 (oldInfo == null ? "null" : oldInfo.getState()) +
5084 " to " + state);
5085 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005086
Robin Lee585e2482016-05-01 23:00:00 +01005087 if (!networkAgent.created
5088 && (state == NetworkInfo.State.CONNECTED
5089 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005090
5091 // A network that has just connected has zero requests and is thus a foreground network.
5092 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5093
Robert Greenwalt7b816022014-04-18 15:25:25 -07005094 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005095 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005096 if (networkAgent.isVPN()) {
5097 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005098 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5099 (networkAgent.networkMisc == null ||
5100 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005101 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005102 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005103 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005104 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005105 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005106 loge("Error creating network " + networkAgent.network.netId + ": "
5107 + e.getMessage());
5108 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005109 }
Paul Jenseneec75412014-08-04 12:21:19 -04005110 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005111 }
5112
5113 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5114 networkAgent.everConnected = true;
5115
Robert Greenwalt7b816022014-04-18 15:25:25 -07005116 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005117 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005118
Paul Jensenca8f16a2014-05-09 12:47:55 -04005119 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005120 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005121
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005122 if (networkAgent.isVPN()) {
5123 // Temporarily disable the default proxy (not global).
5124 synchronized (mProxyLock) {
5125 if (!mDefaultProxyDisabled) {
5126 mDefaultProxyDisabled = true;
5127 if (mGlobalProxy == null && mDefaultProxy != null) {
5128 sendProxyBroadcast(null);
5129 }
5130 }
5131 }
5132 // TODO: support proxy per network.
5133 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005134
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005135 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5136 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5137 // capabilities, so it only needs to be done once on initial connect, not every time the
5138 // network's capabilities change. Note that we do this before rematching the network,
5139 // so we could decide to tear it down immediately afterwards. That's fine though - on
5140 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5141 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005142 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005143
Paul Jensen2161a8e2014-09-11 11:00:39 -04005144 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005145 final long now = SystemClock.elapsedRealtime();
5146 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005147
5148 // This has to happen after matching the requests, because callbacks are just requests.
5149 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005150 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005151 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005152 if (networkAgent.isVPN()) {
5153 synchronized (mProxyLock) {
5154 if (mDefaultProxyDisabled) {
5155 mDefaultProxyDisabled = false;
5156 if (mGlobalProxy == null && mDefaultProxy != null) {
5157 sendProxyBroadcast(mDefaultProxy);
5158 }
5159 }
5160 }
5161 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005162 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5163 state == NetworkInfo.State.SUSPENDED) {
5164 // going into or coming out of SUSPEND: rescore and notify
5165 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005166 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005167 }
5168 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5169 ConnectivityManager.CALLBACK_SUSPENDED :
5170 ConnectivityManager.CALLBACK_RESUMED));
5171 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005172 }
5173 }
5174
Robert Greenwaltac96c522014-06-03 16:43:57 -07005175 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005176 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005177 if (score < 0) {
5178 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5179 "). Bumping score to min of 0");
5180 score = 0;
5181 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005182
Paul Jensen2161a8e2014-09-11 11:00:39 -04005183 final int oldScore = nai.getCurrentScore();
5184 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005185
Paul Jensen85cf78e2015-06-25 13:25:07 -04005186 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005187
Paul Jensenc8b9a742014-09-30 15:37:41 -04005188 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005189 }
5190
Erik Klinec75d4fa2017-02-15 19:59:17 +09005191 // Notify only this one new request of the current state. Transfer all the
5192 // current state by calling NetworkCapabilities and LinkProperties callbacks
5193 // so that callers can be guaranteed to have as close to atomicity in state
5194 // transfer as can be supported by this current API.
5195 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005196 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005197 if (nri.mPendingIntent != null) {
5198 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5199 // Attempt no subsequent state pushes where intents are involved.
5200 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005201 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005202
5203 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5204 // Whether a network is currently suspended is also an important
5205 // element of state to be transferred (it would not otherwise be
5206 // delivered by any currently available mechanism).
5207 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5208 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5209 }
5210 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5211 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005212 }
5213
Robert Greenwalt8d482522015-06-24 13:23:42 -07005214 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005215 // The NetworkInfo we actually send out has no bearing on the real
5216 // state of affairs. For example, if the default connection is mobile,
5217 // and a request for HIPRI has just gone away, we need to pretend that
5218 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5219 // the state to DISCONNECTED, even though the network is of type MOBILE
5220 // and is still connected.
5221 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5222 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005223 if (state != DetailedState.DISCONNECTED) {
5224 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005225 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005226 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005227 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005228 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5229 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5230 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5231 if (info.isFailover()) {
5232 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5233 nai.networkInfo.setFailover(false);
5234 }
5235 if (info.getReason() != null) {
5236 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5237 }
5238 if (info.getExtraInfo() != null) {
5239 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5240 }
5241 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005242 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005243 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005244 if (newDefaultAgent != null) {
5245 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5246 newDefaultAgent.networkInfo);
5247 } else {
5248 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5249 }
5250 }
5251 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5252 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005253 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005254 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005255 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005256 }
5257 }
5258 }
5259
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005260 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005261 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005262 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5263 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005264 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5265 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005266 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5267 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005268 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005269 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005270 } else {
5271 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5272 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005273 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005274 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005275
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005276 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5277 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5278 }
5279
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005280 private String notifyTypeToName(int notifyType) {
5281 switch (notifyType) {
5282 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5283 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5284 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5285 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5286 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5287 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5288 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5289 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5290 }
5291 return "UNKNOWN";
5292 }
5293
Jeff Sharkey69736342014-12-08 14:50:12 -08005294 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005295 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5296 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005297 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005298 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005299 try {
5300 mStatsService.forceUpdateIfaces();
5301 } catch (Exception ignored) {
5302 }
5303 }
5304
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005305 @Override
5306 public boolean addVpnAddress(String address, int prefixLength) {
5307 throwIfLockdownEnabled();
5308 int user = UserHandle.getUserId(Binder.getCallingUid());
5309 synchronized (mVpns) {
5310 return mVpns.get(user).addAddress(address, prefixLength);
5311 }
5312 }
5313
5314 @Override
5315 public boolean removeVpnAddress(String address, int prefixLength) {
5316 throwIfLockdownEnabled();
5317 int user = UserHandle.getUserId(Binder.getCallingUid());
5318 synchronized (mVpns) {
5319 return mVpns.get(user).removeAddress(address, prefixLength);
5320 }
5321 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005322
5323 @Override
5324 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5325 throwIfLockdownEnabled();
5326 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005327 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005328 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005329 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005330 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005331 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005332 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005333 }
5334 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005335 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005336
5337 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005338 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005339 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005340 }
5341
5342 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005343 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5344 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5345 enforceKeepalivePermission();
5346 mKeepaliveTracker.startNattKeepalive(
5347 getNetworkAgentInfoForNetwork(network),
5348 intervalSeconds, messenger, binder,
5349 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5350 }
5351
5352 @Override
5353 public void stopKeepalive(Network network, int slot) {
5354 mHandler.sendMessage(mHandler.obtainMessage(
5355 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5356 }
5357
5358 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005359 public void factoryReset() {
5360 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005361
5362 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5363 return;
5364 }
5365
Robin Lee3b3dd942015-05-12 18:14:58 +01005366 final int userId = UserHandle.getCallingUserId();
5367
Stuart Scottf1fb3972015-04-02 18:00:02 -07005368 // Turn airplane mode off
5369 setAirplaneMode(false);
5370
Stuart Scotte3e314d2015-04-20 14:07:45 -07005371 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5372 // Untether
5373 for (String tether : getTetheredIfaces()) {
5374 untether(tether);
5375 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005376 }
5377
Stuart Scotte3e314d2015-04-20 14:07:45 -07005378 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005379 // Remove always-on package
5380 synchronized (mVpns) {
5381 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5382 if (alwaysOnPackage != null) {
5383 setAlwaysOnVpnPackage(userId, null, false);
5384 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5385 }
5386 }
5387
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005388 // Turn Always-on VPN off
5389 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5390 final long ident = Binder.clearCallingIdentity();
5391 try {
5392 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5393 mLockdownEnabled = false;
5394 setLockdownTracker(null);
5395 } finally {
5396 Binder.restoreCallingIdentity(ident);
5397 }
5398 }
5399
Stuart Scotte3e314d2015-04-20 14:07:45 -07005400 // Turn VPN off
5401 VpnConfig vpnConfig = getVpnConfig(userId);
5402 if (vpnConfig != null) {
5403 if (vpnConfig.legacy) {
5404 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5405 } else {
5406 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5407 // in the future without user intervention.
5408 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005409
Victor Changb04a5ea2016-05-30 20:36:30 +01005410 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005411 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005412 }
5413 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005414
5415 Settings.Global.putString(mContext.getContentResolver(),
5416 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005417 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005418
5419 @VisibleForTesting
5420 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5421 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5422 return new NetworkMonitor(context, handler, nai, defaultRequest);
5423 }
Erik Kline48f12f22016-04-14 17:30:59 +09005424
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005425 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005426 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5427 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005428 }
5429
5430 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005431 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5432 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5433 }
5434
Hugo Benichicfddd682016-05-31 16:28:06 +09005435 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005436 int newNetid = NETID_UNSET;
5437 int prevNetid = NETID_UNSET;
5438 int[] transports = new int[0];
5439 boolean hadIPv4 = false;
5440 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005441
Hugo Benichi5f16f762016-04-20 12:09:33 +09005442 if (newNai != null) {
5443 newNetid = newNai.network.netId;
5444 transports = newNai.networkCapabilities.getTransportTypes();
5445 }
5446 if (prevNai != null) {
5447 prevNetid = prevNai.network.netId;
5448 final LinkProperties lp = prevNai.linkProperties;
5449 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5450 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5451 }
5452
Hugo Benichicfddd682016-05-31 16:28:06 +09005453 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5454 }
5455
5456 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5457 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005458 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005459}