blob: 0e06682f1547cf3ef61e75614291ceaee24ae01c [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 Sharkeye6e61972012-09-14 13:47:51 -0700120import com.android.internal.util.IndentingPrintWriter;
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900121import com.android.internal.util.MessageUtils;
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900122import com.android.internal.util.WakeupMessage;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700123import com.android.internal.util.XmlUtils;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900124import com.android.server.LocalServices;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700125import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400126import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900127import com.android.server.connectivity.KeepaliveTracker;
Christopher Wiley497c1472016-10-11 13:26:03 -0700128import com.android.server.connectivity.MockableSystemProperties;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900129import com.android.server.connectivity.Nat464Xlat;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900130import com.android.server.connectivity.LingerMonitor;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700131import com.android.server.connectivity.NetworkAgentInfo;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600132import com.android.server.connectivity.NetworkDiagnostics;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400133import com.android.server.connectivity.NetworkMonitor;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900134import com.android.server.connectivity.NetworkNotificationManager;
135import com.android.server.connectivity.NetworkNotificationManager.NotificationType;
Jason Monk602b2322013-07-03 17:04:33 -0400136import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700137import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800138import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700139import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700140import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700141import com.android.server.net.LockdownVpnTracker;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900142import com.android.server.net.NetworkPolicyManagerInternal;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600143
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700144import com.google.android.collect.Lists;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700145
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700146import org.xmlpull.v1.XmlPullParser;
147import org.xmlpull.v1.XmlPullParserException;
148
149import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700151import java.io.FileNotFoundException;
152import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700153import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700155import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700156import java.net.InetAddress;
157import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700158import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700159import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700160import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700161import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700162import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700163import java.util.HashSet;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700164import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700165import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700166import java.util.Objects;
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600167import java.util.SortedSet;
168import java.util.TreeSet;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
170/**
171 * @hide
172 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800173public class ConnectivityService extends IConnectivityManager.Stub
174 implements PendingIntent.OnFinished {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900175 private static final String TAG = ConnectivityService.class.getSimpleName();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800176
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900177 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700178 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800179
Jake Hamby786e71a2014-02-06 14:43:50 -0800180 private static final boolean LOGD_RULES = false;
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900181 private static final boolean LOGD_BLOCKED_NETWORKINFO = true;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700182
Jeff Sharkey899223b2012-08-04 15:24:58 -0700183 // TODO: create better separation between radio types and network types
184
Robert Greenwalt42acef32009-08-12 16:08:25 -0700185 // how long to wait before switching back to a radio's default network
186 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
187 // system property that can override the above value
188 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
189 "android.telephony.apn-restore";
190
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900191 // How long to wait before putting up a "This network doesn't have an Internet connection,
192 // connect anyway?" dialog after the user selects a network that doesn't validate.
193 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
194
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900195 // Default to 30s linger time-out. Modifiable only for testing.
196 private static final String LINGER_DELAY_PROPERTY = "persist.netmon.linger";
197 private static final int DEFAULT_LINGER_DELAY_MS = 30_000;
198 @VisibleForTesting
199 protected int mLingerDelayMs; // Can't be final, or test subclass constructors can't change it.
200
Jeremy Joslin79294842014-12-03 17:15:28 -0800201 // How long to delay to removal of a pending intent based request.
202 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
203 private final int mReleasePendingIntentDelayMs;
204
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800205 private Tethering mTethering;
206
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700207 private final PermissionMonitor mPermissionMonitor;
208
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700209 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700210
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700211 @GuardedBy("mVpns")
212 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700213
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700214 private boolean mLockdownEnabled;
215 private LockdownVpnTracker mLockdownTracker;
216
Erik Klineda4bfa82015-04-30 12:58:40 +0900217 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800218 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700219 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700220 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800221
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800222 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800223
224 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700225 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800226
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700227 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800228 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700229 private INetworkPolicyManager mPolicyManager;
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900230 private NetworkPolicyManagerInternal mPolicyManagerInternal;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700231
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700232 private String mCurrentTcpBufferSizes;
233
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700234 private static final int ENABLED = 1;
235 private static final int DISABLED = 0;
236
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900237 private static final SparseArray<String> sMagicDecoderRing = MessageUtils.findMessageNames(
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900238 new Class[] { AsyncChannel.class, ConnectivityService.class, NetworkAgent.class,
239 NetworkAgentInfo.class });
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +0900240
Paul Jensenb10e37f2014-11-25 12:33:08 -0500241 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400242 // Tear down networks that have no chance (e.g. even if validated) of becoming
243 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500244 // all networks have been rematched against all NetworkRequests.
245 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400246 // Don't reap networks. This should be passed when some networks have not yet been
247 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500248 DONT_REAP
249 };
250
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900251 private enum UnneededFor {
252 LINGER, // Determine whether this network is unneeded and should be lingered.
253 TEARDOWN, // Determine whether this network is unneeded and should be torn down.
254 }
255
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700256 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700257 * used internally to change our mobile data enabled flag
258 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700259 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700260
261 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700262 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700263 * from one net to another. Clear happens when we get a new
264 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
265 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700266 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700267 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700268
Robert Greenwalt434203a2010-10-11 16:00:27 -0700269 /**
270 * used internally to reload global proxy settings
271 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700272 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700273
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700274 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400275 * PAC manager has received new port.
276 */
277 private static final int EVENT_PROXY_HAS_CHANGED = 16;
278
Robert Greenwalte049c232014-04-11 15:53:27 -0700279 /**
280 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700281 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700282 */
283 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
284
Robert Greenwalt7b816022014-04-18 15:25:25 -0700285 /**
286 * used internally when registering NetworkAgents
287 * obj = Messenger
288 */
289 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
290
Robert Greenwalt9258c642014-03-26 16:47:06 -0700291 /**
292 * used to add a network request
293 * includes a NetworkRequestInfo
294 */
295 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
296
297 /**
298 * indicates a timeout period is over - check if we had a network yet or not
Erik Klineacdd6392016-07-07 16:50:58 +0900299 * and if not, call the timeout callback (but leave the request live until they
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 * cancel it.
301 * includes a NetworkRequestInfo
302 */
303 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
304
305 /**
306 * used to add a network listener - no request
307 * includes a NetworkRequestInfo
308 */
309 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
310
311 /**
312 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400313 * arg1 = UID of caller
314 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700315 */
316 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
317
Robert Greenwalta67be032014-05-16 15:49:14 -0700318 /**
319 * used internally when registering NetworkFactories
320 * obj = Messenger
321 */
322 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
323
Robert Greenwalt27711812014-06-25 16:45:57 -0700324 /**
325 * used internally to expire a wakelock when transitioning
326 * from one net to another. Expire happens when we fail to find
327 * a new network (typically after 1 minute) -
328 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
329 * a replacement network.
330 */
331 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
332
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700333 /**
334 * Used internally to indicate the system is ready.
335 */
336 private static final int EVENT_SYSTEM_READY = 25;
337
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800338 /**
339 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400340 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800341 */
342 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
343
344 /**
345 * used to remove a pending intent and its associated network request.
346 * arg1 = UID of caller
347 * obj = PendingIntent
348 */
349 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
350
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900351 /**
352 * used to specify whether a network should be used even if unvalidated.
353 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
354 * arg2 = whether to remember this choice in the future (1 or 0)
355 * obj = network
356 */
357 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
358
359 /**
Lorenzo Colitti165c51c2016-09-19 01:00:19 +0900360 * used to specify whether a network should not be penalized when it becomes unvalidated.
361 */
362 private static final int EVENT_SET_AVOID_UNVALIDATED = 35;
363
364 /**
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900365 * used to ask the user to confirm a connection to an unvalidated network.
366 * obj = network
367 */
368 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700369
Erik Klineda4bfa82015-04-30 12:58:40 +0900370 /**
371 * used internally to (re)configure mobile data always-on settings.
372 */
373 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
374
Paul Jensen694f2b82015-06-17 14:15:39 -0400375 /**
376 * used to add a network listener with a pending intent
377 * obj = NetworkRequestInfo
378 */
379 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
380
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900381 /** Handler thread used for both of the handlers below. */
382 @VisibleForTesting
383 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700384 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700385 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700386 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700387 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700388
Mike Lockwood0f79b542009-08-14 14:18:49 -0400389 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800390 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400391
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700392 private PowerManager.WakeLock mNetTransitionWakeLock;
393 private String mNetTransitionWakeLockCausedBy = "";
394 private int mNetTransitionWakeLockSerialNumber;
395 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800396 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700397
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700398 // used in DBG mode to track inet condition reports
399 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
400 private ArrayList mInetLog;
401
Robert Greenwalt434203a2010-10-11 16:00:27 -0700402 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400403 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700404 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700405 private boolean mDefaultProxyDisabled = false;
406
Robert Greenwalt434203a2010-10-11 16:00:27 -0700407 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400408 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700409
Jason Monk602b2322013-07-03 17:04:33 -0400410 private PacManager mPacManager = null;
411
Erik Klineda4bfa82015-04-30 12:58:40 +0900412 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700413
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400414 private UserManager mUserManager;
415
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700416 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700417 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700418
Robert Greenwalt50393202011-06-21 17:26:14 -0700419 // the set of network types that can only be enabled by system/sig apps
420 List mProtectedNetworks;
421
John Spurlockbf991a82013-06-24 14:20:23 -0400422 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700423
Wink Savilleab9321d2013-06-29 21:10:57 -0700424 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400425
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900426 private KeepaliveTracker mKeepaliveTracker;
Lorenzo Colittif3ae2ee2016-08-22 16:30:00 +0900427 private NetworkNotificationManager mNotifier;
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +0900428 private LingerMonitor mLingerMonitor;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900429
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700430 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
431 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700432 private final static int MAX_NET_ID = 65535;
433 private int mNextNetId = MIN_NET_ID;
434
Robert Greenwalt34524f02014-05-18 16:22:10 -0700435 // sequence number of NetworkRequests
436 private int mNextNetworkRequestId = 1;
437
Erik Kline7523eb32015-07-09 18:24:03 +0900438 // NetworkRequest activity String log entries.
439 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
440 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
441
Hugo Benichic2ae2872016-07-11 11:05:12 +0900442 // NetworkInfo blocked and unblocked String log entries
443 // TODO: consider reducing memory usage. Each log line is ~40 2B chars, for a total of ~8kB.
444 private static final int MAX_NETWORK_INFO_LOGS = 100;
445 private final LocalLog mNetworkInfoBlockingLogs = new LocalLog(MAX_NETWORK_INFO_LOGS);
446
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700447 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
448 private static final int MAX_VALIDATION_LOGS = 10;
Paul Jensen0808eb82016-06-03 13:51:21 -0400449 private static class ValidationLog {
450 final Network mNetwork;
451 final String mNetworkExtraInfo;
452 final ReadOnlyLocalLog mLog;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700453
Paul Jensen0808eb82016-06-03 13:51:21 -0400454 ValidationLog(Network network, String networkExtraInfo, ReadOnlyLocalLog log) {
455 mNetwork = network;
456 mNetworkExtraInfo = networkExtraInfo;
457 mLog = log;
458 }
459 }
460 private final ArrayDeque<ValidationLog> mValidationLogs =
461 new ArrayDeque<ValidationLog>(MAX_VALIDATION_LOGS);
462
463 private void addValidationLogs(ReadOnlyLocalLog log, Network network, String networkExtraInfo) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700464 synchronized(mValidationLogs) {
465 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
466 mValidationLogs.removeLast();
467 }
Paul Jensen0808eb82016-06-03 13:51:21 -0400468 mValidationLogs.addFirst(new ValidationLog(network, networkExtraInfo, log));
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700469 }
470 }
471
Hugo Benichif9fdf872016-07-28 17:53:06 +0900472 private final IpConnectivityLog mMetricsLog;
Hugo Benichicfddd682016-05-31 16:28:06 +0900473
Erik Kline065ab6e2016-10-02 18:02:14 +0900474 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900475 final MultinetworkPolicyTracker mMultinetworkPolicyTracker;
Erik Kline065ab6e2016-10-02 18:02:14 +0900476
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700477 /**
478 * Implements support for the legacy "one network per network type" model.
479 *
480 * We used to have a static array of NetworkStateTrackers, one for each
481 * network type, but that doesn't work any more now that we can have,
482 * for example, more that one wifi network. This class stores all the
483 * NetworkAgentInfo objects that support a given type, but the legacy
484 * API will only see the first one.
485 *
486 * It serves two main purposes:
487 *
488 * 1. Provide information about "the network for a given type" (since this
489 * API only supports one).
490 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
491 * the first network for a given type changes, or if the default network
492 * changes.
493 */
494 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900495
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +0900496 private static final boolean DBG = true;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900497 private static final boolean VDBG = false;
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700499 /**
500 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
501 * Each list holds references to all NetworkAgentInfos that are used to
502 * satisfy requests for that network type.
503 *
504 * This array is built out at startup such that an unsupported network
505 * doesn't get an ArrayList instance, making this a tristate:
506 * unsupported, supported but not active and active.
507 *
508 * The actual lists are populated when we scan the network types that
509 * are supported on this device.
Hugo Benichi78caa2582016-06-21 09:48:07 +0900510 *
511 * Threading model:
512 * - addSupportedType() is only called in the constructor
513 * - add(), update(), remove() are only called from the ConnectivityService handler thread.
514 * They are therefore not thread-safe with respect to each other.
515 * - getNetworkForType() can be called at any time on binder threads. It is synchronized
516 * on mTypeLists to be thread-safe with respect to a concurrent remove call.
517 * - dump is thread-safe with respect to concurrent add and remove calls.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700518 */
Hugo Benichi78caa2582016-06-21 09:48:07 +0900519 private final ArrayList<NetworkAgentInfo> mTypeLists[];
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700520
521 public LegacyTypeTracker() {
522 mTypeLists = (ArrayList<NetworkAgentInfo>[])
523 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
524 }
525
526 public void addSupportedType(int type) {
527 if (mTypeLists[type] != null) {
528 throw new IllegalStateException(
529 "legacy list for type " + type + "already initialized");
530 }
531 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
532 }
533
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700534 public boolean isTypeSupported(int type) {
535 return isNetworkTypeValid(type) && mTypeLists[type] != null;
536 }
537
538 public NetworkAgentInfo getNetworkForType(int type) {
Hugo Benichi78caa2582016-06-21 09:48:07 +0900539 synchronized (mTypeLists) {
540 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
541 return mTypeLists[type].get(0);
542 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700543 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900544 return null;
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700545 }
546
Robert Greenwalt8d482522015-06-24 13:23:42 -0700547 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900548 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900549 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700550 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900551 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900552 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553 }
554 }
555
556 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700557 public void add(int type, NetworkAgentInfo nai) {
558 if (!isTypeSupported(type)) {
559 return; // Invalid network type.
560 }
561 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
562
563 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
564 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700565 return;
566 }
Hugo Benichi78caa2582016-06-21 09:48:07 +0900567 synchronized (mTypeLists) {
568 list.add(nai);
569 }
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900570
571 // 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 +0900572 final boolean isDefaultNetwork = isDefaultNetwork(nai);
Hugo Benichi78caa2582016-06-21 09:48:07 +0900573 if ((list.size() == 1) || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
575 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700576 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700577 }
578
Lorenzo Colittia793a672014-07-31 23:20:17 +0900579 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900580 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900581 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
582 if (list == null || list.isEmpty()) {
583 return;
584 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900585 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900586
Hugo Benichi78caa2582016-06-21 09:48:07 +0900587 synchronized (mTypeLists) {
588 if (!list.remove(nai)) {
589 return;
590 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900591 }
592
Robert Greenwalt8d482522015-06-24 13:23:42 -0700593 final DetailedState state = DetailedState.DISCONNECTED;
594
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900595 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700596 maybeLogBroadcast(nai, state, type, wasDefault);
597 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900598 }
599
600 if (!list.isEmpty() && wasFirstNetwork) {
601 if (DBG) log("Other network available for type " + type +
602 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900603 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700604 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
605 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900606 }
607 }
608
609 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900610 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
611 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700612 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900613 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700614 }
615 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700616
Robert Greenwalt8d482522015-06-24 13:23:42 -0700617 // send out another legacy broadcast - currently only used for suspend/unsuspend
618 // toggle
619 public void update(NetworkAgentInfo nai) {
620 final boolean isDefault = isDefaultNetwork(nai);
621 final DetailedState state = nai.networkInfo.getDetailedState();
622 for (int type = 0; type < mTypeLists.length; type++) {
623 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700624 final boolean contains = (list != null && list.contains(nai));
Hugo Benichi78caa2582016-06-21 09:48:07 +0900625 final boolean isFirst = contains && (nai == list.get(0));
626 if (isFirst || contains && isDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700627 maybeLogBroadcast(nai, state, type, isDefault);
628 sendLegacyNetworkBroadcast(nai, state, type);
629 }
630 }
631 }
632
Lorenzo Colittia793a672014-07-31 23:20:17 +0900633 private String naiToString(NetworkAgentInfo nai) {
634 String name = (nai != null) ? nai.name() : "null";
635 String state = (nai.networkInfo != null) ?
636 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
637 "???/???";
638 return name + " " + state;
639 }
640
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700641 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900642 pw.println("mLegacyTypeTracker:");
643 pw.increaseIndent();
644 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700645 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900646 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700647 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900648 pw.println();
649 pw.println("Current state:");
650 pw.increaseIndent();
Hugo Benichi78caa2582016-06-21 09:48:07 +0900651 synchronized (mTypeLists) {
652 for (int type = 0; type < mTypeLists.length; type++) {
653 if (mTypeLists[type] == null || mTypeLists[type].isEmpty()) continue;
654 for (NetworkAgentInfo nai : mTypeLists[type]) {
655 pw.println(type + " " + naiToString(nai));
656 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900657 }
658 }
659 pw.decreaseIndent();
660 pw.decreaseIndent();
661 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700662 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700663 }
664 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
665
Jeff Sharkey899223b2012-08-04 15:24:58 -0700666 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700667 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Hugo Benichif9fdf872016-07-28 17:53:06 +0900668 this(context, netManager, statsService, policyManager, new IpConnectivityLog());
669 }
670
671 @VisibleForTesting
672 protected ConnectivityService(Context context, INetworkManagementService netManager,
673 INetworkStatsService statsService, INetworkPolicyManager policyManager,
674 IpConnectivityLog logger) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800675 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800676
Hugo Benichif9fdf872016-07-28 17:53:06 +0900677 mMetricsLog = logger;
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900678 mDefaultRequest = createInternetRequestForTransport(-1, NetworkRequest.Type.REQUEST);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900679 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest, new Binder());
Erik Kline7523eb32015-07-09 18:24:03 +0900680 mNetworkRequests.put(mDefaultRequest, defaultNRI);
681 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900682
683 mDefaultMobileDataRequest = createInternetRequestForTransport(
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900684 NetworkCapabilities.TRANSPORT_CELLULAR, NetworkRequest.Type.BACKGROUND_REQUEST);
Robert Greenwalte049c232014-04-11 15:53:27 -0700685
Hugo Benichiad4db4e2016-10-17 15:54:51 +0900686 mHandlerThread = new HandlerThread("ConnectivityServiceThread");
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900687 mHandlerThread.start();
688 mHandler = new InternalHandler(mHandlerThread.getLooper());
689 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700690
Jeremy Joslin79294842014-12-03 17:15:28 -0800691 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
692 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
693
Lorenzo Colittib57578ca2016-07-01 01:53:25 +0900694 mLingerDelayMs = SystemProperties.getInt(LINGER_DELAY_PROPERTY, DEFAULT_LINGER_DELAY_MS);
695
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700696 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700697 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800698 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700699 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900700 mPolicyManagerInternal = checkNotNull(
701 LocalServices.getService(NetworkPolicyManagerInternal.class),
702 "missing NetworkPolicyManagerInternal");
703
Jeff Sharkey82f85212012-08-24 11:17:25 -0700704 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700705 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700706
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700707 try {
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900708 mPolicyManager.registerListener(mPolicyListener);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700709 } catch (RemoteException e) {
710 // ouch, no rules updates means some processes may never get network
Felipe Lemed31a97f2016-05-06 14:53:50 -0700711 loge("unable to register INetworkPolicyListener" + e);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700712 }
713
714 final PowerManager powerManager = (PowerManager) context.getSystemService(
715 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700716 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
717 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
718 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800719 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700720
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700721 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700722
Wink Saville51f456f2013-04-23 14:26:51 -0700723 // TODO: What is the "correct" way to do determine if this is a wifi only device?
724 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
725 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700726 String[] naStrings = context.getResources().getStringArray(
727 com.android.internal.R.array.networkAttributes);
728 for (String naString : naStrings) {
729 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700730 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700731 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700732 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800733 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700734 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700735 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700736 }
Wink Saville51f456f2013-04-23 14:26:51 -0700737 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
738 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
739 n.type);
740 continue;
741 }
Wink Saville975c8482011-04-07 14:23:45 -0700742 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800743 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700744 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700745 continue;
746 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700747 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700748
Wink Saville975c8482011-04-07 14:23:45 -0700749 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700750 mNetworksDefined++;
751 } catch(Exception e) {
752 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700753 }
754 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700755
756 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
757 if (mNetConfigs[TYPE_VPN] == null) {
758 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
759 // don't need to add TYPE_VPN to mNetConfigs.
760 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
761 mNetworksDefined++; // used only in the log() statement below.
762 }
763
Wink Saville5e56bc52013-07-29 15:00:57 -0700764 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700765
Robert Greenwalt50393202011-06-21 17:26:14 -0700766 mProtectedNetworks = new ArrayList<Integer>();
767 int[] protectedNetworks = context.getResources().getIntArray(
768 com.android.internal.R.array.config_protectedNetworks);
769 for (int p : protectedNetworks) {
770 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
771 mProtectedNetworks.add(p);
772 } else {
773 if (DBG) loge("Ignoring protectedNetwork " + p);
774 }
775 }
776
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700777 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
778 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700779
Christopher Wiley497c1472016-10-11 13:26:03 -0700780 mTethering = new Tethering(mContext, mNetd, statsService, mPolicyManager,
781 IoThread.get().getLooper(), new MockableSystemProperties());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800782
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700783 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
784
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700785 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700786 IntentFilter intentFilter = new IntentFilter();
Robin Lee323f29d2016-05-04 16:38:06 +0100787 intentFilter.addAction(Intent.ACTION_USER_STARTED);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -0700788 intentFilter.addAction(Intent.ACTION_USER_STOPPED);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700789 intentFilter.addAction(Intent.ACTION_USER_ADDED);
790 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Robin Lee89e7a692016-02-29 14:38:17 +0000791 intentFilter.addAction(Intent.ACTION_USER_UNLOCKED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700792 mContext.registerReceiverAsUser(
793 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Robin Lee95204e02017-01-27 11:59:22 +0000794 mContext.registerReceiverAsUser(mUserPresentReceiver, UserHandle.SYSTEM,
795 new IntentFilter(Intent.ACTION_USER_PRESENT), null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900796
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700797 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700798 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700799 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700800 } catch (RemoteException e) {
801 loge("Error registering observer :" + e);
802 }
803
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700804 if (DBG) {
805 mInetLog = new ArrayList();
806 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700807
Erik Klineda4bfa82015-04-30 12:58:40 +0900808 mSettingsObserver = new SettingsObserver(mContext, mHandler);
809 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800810
John Spurlockbf991a82013-06-24 14:20:23 -0400811 mDataConnectionStats = new DataConnectionStats(mContext);
812 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400813
Jason Monkdecd2952013-10-10 14:02:51 -0400814 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700815
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400816 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900817
818 mKeepaliveTracker = new KeepaliveTracker(mHandler);
Lorenzo Colitti0b599062016-08-22 22:36:19 +0900819 mNotifier = new NetworkNotificationManager(mContext, mTelephonyManager,
820 mContext.getSystemService(NotificationManager.class));
Lorenzo Colitti84e6f1232016-08-29 14:03:11 +0900821
822 final int dailyLimit = Settings.Global.getInt(mContext.getContentResolver(),
823 Settings.Global.NETWORK_SWITCH_NOTIFICATION_DAILY_LIMIT,
824 LingerMonitor.DEFAULT_NOTIFICATION_DAILY_LIMIT);
825 final long rateLimit = Settings.Global.getLong(mContext.getContentResolver(),
826 Settings.Global.NETWORK_SWITCH_NOTIFICATION_RATE_LIMIT_MILLIS,
827 LingerMonitor.DEFAULT_NOTIFICATION_RATE_LIMIT_MILLIS);
828 mLingerMonitor = new LingerMonitor(mContext, mNotifier, dailyLimit, rateLimit);
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +0900829
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900830 mMultinetworkPolicyTracker = createMultinetworkPolicyTracker(
Erik Kline065ab6e2016-10-02 18:02:14 +0900831 mContext, mHandler, () -> rematchForAvoidBadWifiUpdate());
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +0900832 mMultinetworkPolicyTracker.start();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800833 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700834
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900835 private NetworkRequest createInternetRequestForTransport(
836 int transportType, NetworkRequest.Type type) {
Erik Klineda4bfa82015-04-30 12:58:40 +0900837 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900838 netCap.addCapability(NET_CAPABILITY_INTERNET);
839 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900840 if (transportType > -1) {
841 netCap.addTransportType(transportType);
842 }
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +0900843 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId(), type);
Erik Klineda4bfa82015-04-30 12:58:40 +0900844 }
845
Lorenzo Colitti762ea7a2016-06-05 21:00:23 +0900846 // Used only for testing.
847 // TODO: Delete this and either:
848 // 1. Give Fake SettingsProvider the ability to send settings change notifications (requires
849 // changing ContentResolver to make registerContentObserver non-final).
850 // 2. Give FakeSettingsProvider an alternative notification mechanism and have the test use it
851 // by subclassing SettingsObserver.
852 @VisibleForTesting
853 void updateMobileDataAlwaysOn() {
854 mHandler.sendEmptyMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
855 }
856
Erik Klineda4bfa82015-04-30 12:58:40 +0900857 private void handleMobileDataAlwaysOn() {
858 final boolean enable = (Settings.Global.getInt(
Lorenzo Colitti5d6bf6d2017-01-17 11:07:10 +0900859 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 1) == 1);
Erik Klineda4bfa82015-04-30 12:58:40 +0900860 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
861 if (enable == isEnabled) {
862 return; // Nothing to do.
863 }
864
865 if (enable) {
866 handleRegisterNetworkRequest(new NetworkRequestInfo(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +0900867 null, mDefaultMobileDataRequest, new Binder()));
Erik Klineda4bfa82015-04-30 12:58:40 +0900868 } else {
869 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
870 }
871 }
872
873 private void registerSettingsCallbacks() {
874 // Watch for global HTTP proxy changes.
875 mSettingsObserver.observe(
876 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
877 EVENT_APPLY_GLOBAL_HTTP_PROXY);
878
879 // Watch for whether or not to keep mobile data always on.
880 mSettingsObserver.observe(
881 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
882 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
883 }
884
Robert Greenwalt34524f02014-05-18 16:22:10 -0700885 private synchronized int nextNetworkRequestId() {
886 return mNextNetworkRequestId++;
887 }
888
Paul Jensen67b0b072015-06-10 11:22:17 -0400889 @VisibleForTesting
890 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400891 synchronized (mNetworkForNetId) {
892 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
893 int netId = mNextNetId;
894 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
895 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500896 if (!mNetIdInUse.get(netId)) {
897 mNetIdInUse.put(netId, true);
898 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400899 }
900 }
901 }
902 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700903 }
904
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600905 private NetworkState getFilteredNetworkState(int networkType, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800906 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600907 final NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
908 final NetworkState state;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800909 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600910 state = nai.getNetworkState();
911 state.networkInfo.setType(networkType);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800912 } else {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600913 final NetworkInfo info = new NetworkInfo(networkType, 0,
914 getNetworkTypeName(networkType), "");
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800915 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
916 info.setIsAvailable(true);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600917 state = new NetworkState(info, new LinkProperties(), new NetworkCapabilities(),
918 null, null, null);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800919 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600920 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600921 return state;
922 } else {
923 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800924 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400925 }
926
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800927 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
928 if (network == null) {
929 return null;
930 }
931 synchronized (mNetworkForNetId) {
932 return mNetworkForNetId.get(network.netId);
933 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600934 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900936 private Network[] getVpnUnderlyingNetworks(int uid) {
937 if (!mLockdownEnabled) {
938 int user = UserHandle.getUserId(uid);
939 synchronized (mVpns) {
940 Vpn vpn = mVpns.get(user);
941 if (vpn != null && vpn.appliesToUid(uid)) {
942 return vpn.getUnderlyingNetworks();
943 }
944 }
945 }
946 return null;
947 }
948
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800949 private NetworkState getUnfilteredActiveNetworkState(int uid) {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400950 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800951
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900952 final Network[] networks = getVpnUnderlyingNetworks(uid);
953 if (networks != null) {
954 // getUnderlyingNetworks() returns:
955 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
956 // empty array => the VPN explicitly said "no default network".
957 // non-empty array => the VPN specified one or more default networks; we use the
958 // first one.
959 if (networks.length > 0) {
960 nai = getNetworkAgentInfoForNetwork(networks[0]);
961 } else {
962 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800963 }
964 }
965
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800966 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -0600967 return nai.getNetworkState();
968 } else {
969 return NetworkState.EMPTY;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800970 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400971 }
972
973 /**
974 * Check if UID should be blocked from using the network with the given LinkProperties.
975 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600976 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid,
977 boolean ignoreBlocked) {
978 // Networks aren't blocked when ignoring blocked status
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900979 if (ignoreBlocked) {
980 return false;
981 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -0600982 // Networks are never blocked for system services
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900983 // TODO: consider moving this check to NetworkPolicyManagerInternal.isUidNetworkingBlocked.
984 if (isSystem(uid)) {
985 return false;
986 }
Robin Lee17e61832016-05-09 13:46:28 +0100987 synchronized (mVpns) {
988 final Vpn vpn = mVpns.get(UserHandle.getUserId(uid));
989 if (vpn != null && vpn.isBlockingUid(uid)) {
990 return true;
991 }
992 }
Robert Greenwalt12e67352014-05-13 21:41:06 -0700993 final String iface = (lp == null ? "" : lp.getInterfaceName());
Hugo Benichi938ab4f2017-02-11 17:04:43 +0900994 return mPolicyManagerInternal.isUidNetworkingBlocked(uid, iface);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700995 }
996
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +0900997 private void maybeLogBlockedNetworkInfo(NetworkInfo ni, int uid) {
Hugo Benichic2ae2872016-07-11 11:05:12 +0900998 if (ni == null || !LOGD_BLOCKED_NETWORKINFO) {
999 return;
1000 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001001 boolean removed = false;
1002 boolean added = false;
1003 synchronized (mBlockedAppUids) {
1004 if (ni.getDetailedState() == DetailedState.BLOCKED && mBlockedAppUids.add(uid)) {
1005 added = true;
1006 } else if (ni.isConnected() && mBlockedAppUids.remove(uid)) {
1007 removed = true;
1008 }
1009 }
Hugo Benichic2ae2872016-07-11 11:05:12 +09001010 if (added) {
1011 log("Returning blocked NetworkInfo to uid=" + uid);
1012 mNetworkInfoBlockingLogs.log("BLOCKED " + uid);
1013 } else if (removed) {
1014 log("Returning unblocked NetworkInfo to uid=" + uid);
1015 mNetworkInfoBlockingLogs.log("UNBLOCKED " + uid);
1016 }
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09001017 }
1018
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001019 /**
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001020 * Apply any relevant filters to {@link NetworkState} for the given UID. For
1021 * example, this may mark the network as {@link DetailedState#BLOCKED} based
1022 * on {@link #isNetworkWithLinkPropertiesBlocked}, or
1023 * {@link NetworkInfo#isMetered()} based on network policies.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001024 */
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001025 private void filterNetworkStateForUid(NetworkState state, int uid, boolean ignoreBlocked) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001026 if (state == null || state.networkInfo == null || state.linkProperties == null) return;
1027
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001028 if (isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, ignoreBlocked)) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001029 state.networkInfo.setDetailedState(DetailedState.BLOCKED, null, null);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001030 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001031 if (mLockdownTracker != null) {
1032 mLockdownTracker.augmentNetworkInfo(state.networkInfo);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001033 }
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001034
1035 // TODO: apply metered state closer to NetworkAgentInfo
1036 final long token = Binder.clearCallingIdentity();
1037 try {
1038 state.networkInfo.setMetered(mPolicyManager.isNetworkMetered(state));
1039 } catch (RemoteException e) {
1040 } finally {
1041 Binder.restoreCallingIdentity(token);
1042 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001043 }
1044
1045 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 * Return NetworkInfo for the active (i.e., connected) network interface.
1047 * It is assumed that at most one network is active at a time. If more
1048 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001049 * @return the info for the active network, or {@code null} if none is
1050 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001051 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001052 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001053 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 enforceAccessPermission();
1055 final int uid = Binder.getCallingUid();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001056 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001057 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001058 maybeLogBlockedNetworkInfo(state.networkInfo, uid);
1059 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001060 }
1061
Paul Jensen31a94f42015-02-13 14:18:39 -05001062 @Override
1063 public Network getActiveNetwork() {
1064 enforceAccessPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001065 return getActiveNetworkForUidInternal(Binder.getCallingUid(), false);
Robin Leed2baf792016-03-24 12:07:00 +00001066 }
1067
1068 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001069 public Network getActiveNetworkForUid(int uid, boolean ignoreBlocked) {
Robin Leed2baf792016-03-24 12:07:00 +00001070 enforceConnectivityInternalPermission();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001071 return getActiveNetworkForUidInternal(uid, ignoreBlocked);
Robin Leed2baf792016-03-24 12:07:00 +00001072 }
1073
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001074 private Network getActiveNetworkForUidInternal(final int uid, boolean ignoreBlocked) {
Paul Jensen31a94f42015-02-13 14:18:39 -05001075 final int user = UserHandle.getUserId(uid);
1076 int vpnNetId = NETID_UNSET;
1077 synchronized (mVpns) {
1078 final Vpn vpn = mVpns.get(user);
1079 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1080 }
1081 NetworkAgentInfo nai;
1082 if (vpnNetId != NETID_UNSET) {
1083 synchronized (mNetworkForNetId) {
1084 nai = mNetworkForNetId.get(vpnNetId);
1085 }
1086 if (nai != null) return nai.network;
1087 }
1088 nai = getDefaultNetwork();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001089 if (nai != null
1090 && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, ignoreBlocked)) {
1091 nai = null;
1092 }
Paul Jensen31a94f42015-02-13 14:18:39 -05001093 return nai != null ? nai.network : null;
1094 }
1095
Lorenzo Colitti18660282016-07-04 12:55:44 +09001096 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001097 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1098 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001099 final int uid = Binder.getCallingUid();
1100 NetworkState state = getUnfilteredActiveNetworkState(uid);
1101 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001102 }
1103
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001104 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001105 public NetworkInfo getActiveNetworkInfoForUid(int uid, boolean ignoreBlocked) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001106 enforceConnectivityInternalPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001107 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001108 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001109 return state.networkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001110 }
1111
1112 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001113 public NetworkInfo getNetworkInfo(int networkType) {
1114 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001115 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001116 if (getVpnUnderlyingNetworks(uid) != null) {
1117 // A VPN is active, so we may need to return one of its underlying networks. This
1118 // information is not available in LegacyTypeTracker, so we have to get it from
1119 // getUnfilteredActiveNetworkState.
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001120 final NetworkState state = getUnfilteredActiveNetworkState(uid);
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001121 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001122 filterNetworkStateForUid(state, uid, false);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001123 return state.networkInfo;
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001124 }
1125 }
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001126 final NetworkState state = getFilteredNetworkState(networkType, uid, false);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001127 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001128 }
1129
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001130 @Override
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001131 public NetworkInfo getNetworkInfoForUid(Network network, int uid, boolean ignoreBlocked) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001132 enforceAccessPermission();
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001133 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001134 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001135 final NetworkState state = nai.getNetworkState();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001136 filterNetworkStateForUid(state, uid, ignoreBlocked);
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001137 return state.networkInfo;
1138 } else {
1139 return null;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001140 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001141 }
1142
1143 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001144 public NetworkInfo[] getAllNetworkInfo() {
1145 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001146 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001147 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1148 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001149 NetworkInfo info = getNetworkInfo(networkType);
1150 if (info != null) {
1151 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001152 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001153 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001154 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001155 }
1156
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001157 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001158 public Network getNetworkForType(int networkType) {
1159 enforceAccessPermission();
1160 final int uid = Binder.getCallingUid();
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06001161 NetworkState state = getFilteredNetworkState(networkType, uid, false);
1162 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid, false)) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001163 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001164 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001165 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001166 }
1167
1168 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001169 public Network[] getAllNetworks() {
1170 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001171 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001172 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001173 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001174 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001175 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001176 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001177 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001178 }
1179
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001180 @Override
1181 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1182 // The basic principle is: if an app's traffic could possibly go over a
1183 // network, without the app doing anything multinetwork-specific,
1184 // (hence, by "default"), then include that network's capabilities in
1185 // the array.
1186 //
1187 // In the normal case, app traffic only goes over the system's default
1188 // network connection, so that's the only network returned.
1189 //
1190 // With a VPN in force, some app traffic may go into the VPN, and thus
1191 // over whatever underlying networks the VPN specifies, while other app
1192 // traffic may go over the system default network (e.g.: a split-tunnel
1193 // VPN, or an app disallowed by the VPN), so the set of networks
1194 // returned includes the VPN's underlying networks and the system
1195 // default.
1196 enforceAccessPermission();
1197
1198 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1199
1200 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001201 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001202 if (nc != null) {
1203 result.put(nai.network, nc);
1204 }
1205
1206 if (!mLockdownEnabled) {
1207 synchronized (mVpns) {
1208 Vpn vpn = mVpns.get(userId);
1209 if (vpn != null) {
1210 Network[] networks = vpn.getUnderlyingNetworks();
1211 if (networks != null) {
1212 for (Network network : networks) {
1213 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001214 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001215 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001216 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001217 }
1218 }
1219 }
1220 }
1221 }
1222 }
1223
1224 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1225 out = result.values().toArray(out);
1226 return out;
1227 }
1228
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001229 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001230 public boolean isNetworkSupported(int networkType) {
1231 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001232 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001233 }
1234
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001235 /**
1236 * Return LinkProperties for the active (i.e., connected) default
1237 * network interface. It is assumed that at most one default network
1238 * is active at a time. If more than one is active, it is indeterminate
1239 * which will be returned.
1240 * @return the ip properties for the active network, or {@code null} if
1241 * none is active
1242 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001243 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001244 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001245 enforceAccessPermission();
1246 final int uid = Binder.getCallingUid();
1247 NetworkState state = getUnfilteredActiveNetworkState(uid);
1248 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001249 }
1250
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001251 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001252 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001253 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001254 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1255 if (nai != null) {
1256 synchronized (nai) {
1257 return new LinkProperties(nai.linkProperties);
1258 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001259 }
1260 return null;
1261 }
1262
Robert Greenwalt12e67352014-05-13 21:41:06 -07001263 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001264 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001265 public LinkProperties getLinkProperties(Network network) {
1266 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001267 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001268 if (nai != null) {
1269 synchronized (nai) {
1270 return new LinkProperties(nai.linkProperties);
1271 }
1272 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001273 return null;
1274 }
1275
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001276 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001277 if (nai != null) {
1278 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001279 if (nai.networkCapabilities != null) {
1280 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001281 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001282 }
1283 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001284 return null;
1285 }
1286
1287 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001288 public NetworkCapabilities getNetworkCapabilities(Network network) {
1289 enforceAccessPermission();
1290 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1291 }
1292
1293 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001294 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001295 // Require internal since we're handing out IMSI details
1296 enforceConnectivityInternalPermission();
1297
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001298 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001299 for (Network network : getAllNetworks()) {
1300 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1301 if (nai != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001302 result.add(nai.getNetworkState());
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001303 }
1304 }
1305 return result.toArray(new NetworkState[result.size()]);
1306 }
1307
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001308 @Override
1309 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1310 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001311 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001312 final long token = Binder.clearCallingIdentity();
1313 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001314 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1315 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001316 try {
1317 return mPolicyManager.getNetworkQuotaInfo(state);
1318 } catch (RemoteException e) {
1319 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001320 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001321 return null;
1322 } finally {
1323 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001324 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001325 }
1326
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001327 @Override
1328 public boolean isActiveNetworkMetered() {
1329 enforceAccessPermission();
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001330
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001331 final NetworkInfo info = getActiveNetworkInfo();
1332 return (info != null) ? info.isMetered() : false;
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001333 }
1334
Jeff Sharkey216c1812012-08-05 14:29:23 -07001335 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1336 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001337 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001338 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001339 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001340 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001341 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001342
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001343 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001344 * Ensure that a network route exists to deliver traffic to the specified
1345 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001346 * @param networkType the type of the network over which traffic to the
1347 * specified host is to be routed
1348 * @param hostAddress the IP address of the host to which the route is
1349 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 * @return {@code true} on success, {@code false} on failure
1351 */
Lorenzo Colitti18660282016-07-04 12:55:44 +09001352 @Override
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001353 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001354 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001355 if (mProtectedNetworks.contains(networkType)) {
1356 enforceConnectivityInternalPermission();
1357 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001358
Chad Brubakerc0234532014-02-14 13:24:29 -08001359 InetAddress addr;
1360 try {
1361 addr = InetAddress.getByAddress(hostAddress);
1362 } catch (UnknownHostException e) {
1363 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1364 return false;
1365 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001366
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001368 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001369 return false;
1370 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001371
1372 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1373 if (nai == null) {
1374 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1375 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1376 } else {
1377 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1378 }
1379 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001380 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001381
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001382 DetailedState netState;
1383 synchronized (nai) {
1384 netState = nai.networkInfo.getDetailedState();
1385 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001386
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001387 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001388 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001389 log("requestRouteToHostAddress on down network "
1390 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001391 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001392 }
1393 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001394 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001395
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001396 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001397 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001398 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001399 LinkProperties lp;
1400 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001401 synchronized (nai) {
1402 lp = nai.linkProperties;
1403 netId = nai.network.netId;
1404 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001405 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001406 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1407 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001408 } finally {
1409 Binder.restoreCallingIdentity(token);
1410 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001411 }
1412
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001413 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001414 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001415 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001416 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001417 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001418 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001419 if (bestRoute.getGateway().equals(addr)) {
1420 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001421 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001422 } else {
1423 // if we will connect to this through another route, add a direct route
1424 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001425 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001426 }
1427 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001428 if (DBG) log("Adding legacy route " + bestRoute +
1429 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001430 try {
1431 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1432 } catch (Exception e) {
1433 // never crash - catch them all
1434 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001435 return false;
1436 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001437 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001438 }
1439
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001440 private final INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001441 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001442 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001443 // TODO: notify UID when it has requested targeted updates
1444 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001445 @Override
1446 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001447 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001448 @Override
1449 public void onRestrictBackgroundChanged(boolean restrictBackground) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09001450 // TODO: relocate this specific callback in Tethering.
Felipe Leme70c8b9b2016-04-25 14:41:31 -07001451 if (restrictBackground) {
1452 log("onRestrictBackgroundChanged(true): disabling tethering");
1453 mTethering.untetherAll();
1454 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001455 }
Felipe Leme019fcd22016-04-19 10:24:39 -07001456 @Override
Felipe Leme0ecfcd12016-09-06 12:49:48 -07001457 public void onUidPoliciesChanged(int uid, int uidPolicies) {
Felipe Leme99d5d3d2016-05-16 13:30:57 -07001458 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001459 };
1460
Robin Lee3b3dd942015-05-12 18:14:58 +01001461 /**
1462 * Require that the caller is either in the same user or has appropriate permission to interact
1463 * across users.
1464 *
1465 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1466 */
1467 private void enforceCrossUserPermission(int userId) {
1468 if (userId == UserHandle.getCallingUserId()) {
1469 // Not a cross-user call.
1470 return;
1471 }
1472 mContext.enforceCallingOrSelfPermission(
1473 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1474 "ConnectivityService");
1475 }
1476
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001477 private void enforceInternetPermission() {
1478 mContext.enforceCallingOrSelfPermission(
1479 android.Manifest.permission.INTERNET,
1480 "ConnectivityService");
1481 }
1482
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001483 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001484 mContext.enforceCallingOrSelfPermission(
1485 android.Manifest.permission.ACCESS_NETWORK_STATE,
1486 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001487 }
1488
1489 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001490 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001493 private void enforceTetherAccessPermission() {
1494 mContext.enforceCallingOrSelfPermission(
1495 android.Manifest.permission.ACCESS_NETWORK_STATE,
1496 "ConnectivityService");
1497 }
1498
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001499 private void enforceConnectivityInternalPermission() {
1500 mContext.enforceCallingOrSelfPermission(
1501 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1502 "ConnectivityService");
1503 }
1504
Hugo Benichi514da602016-07-19 15:59:27 +09001505 private void enforceConnectivityRestrictedNetworksPermission() {
1506 try {
1507 mContext.enforceCallingOrSelfPermission(
1508 android.Manifest.permission.CONNECTIVITY_USE_RESTRICTED_NETWORKS,
1509 "ConnectivityService");
1510 return;
1511 } catch (SecurityException e) { /* fallback to ConnectivityInternalPermission */ }
1512 enforceConnectivityInternalPermission();
1513 }
1514
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001515 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001516 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001517 }
1518
Lorenzo Colitti18660282016-07-04 12:55:44 +09001519 // Public because it's used by mLockdownTracker.
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001520 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001521 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001522 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001523 }
1524
1525 private void sendInetConditionBroadcast(NetworkInfo info) {
1526 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1527 }
1528
Wink Saville628b0852011-08-04 15:01:58 -07001529 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001530 if (mLockdownTracker != null) {
Jeff Sharkeyf07c7b92016-04-22 09:50:16 -06001531 info = new NetworkInfo(info);
1532 mLockdownTracker.augmentNetworkInfo(info);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001533 }
1534
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001535 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001536 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001537 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001538 if (info.isFailover()) {
1539 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1540 info.setFailover(false);
1541 }
1542 if (info.getReason() != null) {
1543 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1544 }
1545 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001546 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1547 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001548 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001549 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001550 return intent;
1551 }
1552
1553 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1554 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1555 }
1556
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001557 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001558 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1559 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1560 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001561 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001562 final long ident = Binder.clearCallingIdentity();
1563 try {
1564 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1565 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1566 } finally {
1567 Binder.restoreCallingIdentity(ident);
1568 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001569 }
1570
Mike Lockwood0f79b542009-08-14 14:18:49 -04001571 private void sendStickyBroadcast(Intent intent) {
1572 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001573 if (!mSystemReady) {
1574 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001575 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001576 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001577 if (VDBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001578 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001579 }
1580
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001581 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001582 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001583 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001584 final NetworkInfo ni = intent.getParcelableExtra(
1585 ConnectivityManager.EXTRA_NETWORK_INFO);
1586 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1587 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1588 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001589 } else {
1590 BroadcastOptions opts = BroadcastOptions.makeBasic();
1591 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1592 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001593 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001594 final IBatteryStats bs = BatteryStatsService.getService();
1595 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001596 bs.noteConnectivityChanged(intent.getIntExtra(
1597 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1598 ni != null ? ni.getState().toString() : "?");
1599 } catch (RemoteException e) {
1600 }
1601 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001602 try {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001603 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001604 } finally {
1605 Binder.restoreCallingIdentity(ident);
1606 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001607 }
1608 }
1609
1610 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001611 loadGlobalProxy();
1612
Mike Lockwood0f79b542009-08-14 14:18:49 -04001613 synchronized(this) {
1614 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001615 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001616 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001617 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001618 }
1619 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001620 // load the global proxy at startup
1621 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001622
Robin Lee244ce8e2016-01-05 18:03:46 +00001623 // Try bringing up tracker, but KeyStore won't be ready yet for secondary users so wait
1624 // for user to unlock device too.
1625 updateLockdownVpn();
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001626
Erik Klineda4bfa82015-04-30 12:58:40 +09001627 // Configure whether mobile data is always on.
1628 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1629
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001630 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001631
1632 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001633 }
1634
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001635 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001636 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001637 *
1638 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001639 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001640 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001641 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1642 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001643
1644 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001646
Robert Greenwalt7b816022014-04-18 15:25:25 -07001647 if (networkAgent.networkCapabilities.hasTransport(
1648 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001649 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1650 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001651 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001652 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001653 } else if (networkAgent.networkCapabilities.hasTransport(
1654 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001655 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1656 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001657 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001658 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001659 } else {
1660 // do not track any other networks
1661 timeout = 0;
1662 }
1663
Robert Greenwalt7b816022014-04-18 15:25:25 -07001664 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001665 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001666 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001667 } catch (Exception e) {
1668 // You shall not crash!
1669 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001670 }
1671 }
1672 }
1673
1674 /**
1675 * Remove data activity tracking when network disconnects.
1676 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001677 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1678 final String iface = networkAgent.linkProperties.getInterfaceName();
1679 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001680
Robert Greenwalt7b816022014-04-18 15:25:25 -07001681 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1682 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001683 try {
1684 // the call fails silently if no idletimer setup for this interface
1685 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001686 } catch (Exception e) {
1687 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001688 }
1689 }
1690 }
1691
1692 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001693 * Reads the network specific MTU size from reources.
1694 * and set it on it's iface.
1695 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001696 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1697 final String iface = newLp.getInterfaceName();
1698 final int mtu = newLp.getMtu();
Pierre Imai54f0d9e2016-02-08 16:01:40 +09001699 if (oldLp == null && mtu == 0) {
1700 // Silently ignore unset MTU value.
1701 return;
1702 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001703 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1704 if (VDBG) log("identical MTU - not setting");
1705 return;
1706 }
Robert Greenwalt43074032014-08-15 17:53:05 -07001707 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001708 if (mtu != 0) loge("Unexpected mtu value: " + mtu + ", " + iface);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001709 return;
1710 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001711
w1997615afd812014-08-05 15:18:11 -07001712 // Cannot set MTU without interface name
1713 if (TextUtils.isEmpty(iface)) {
1714 loge("Setting MTU size with null iface.");
1715 return;
1716 }
1717
Robert Greenwalt7b816022014-04-18 15:25:25 -07001718 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001719 if (VDBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001720 mNetd.setMtu(iface, mtu);
1721 } catch (Exception e) {
1722 Slog.e(TAG, "exception in setMtu()" + e);
1723 }
1724 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001725
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001726 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001727 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1728
1729 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001730 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001731 protected int getDefaultTcpRwnd() {
1732 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1733 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001734
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001735 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1736 if (isDefaultNetwork(nai) == false) {
1737 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001738 }
1739
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001740 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1741 String[] values = null;
1742 if (tcpBufferSizes != null) {
1743 values = tcpBufferSizes.split(",");
1744 }
1745
1746 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001747 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001748 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1749 values = tcpBufferSizes.split(",");
1750 }
1751
1752 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1753
1754 try {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09001755 if (VDBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001756
1757 final String prefix = "/sys/kernel/ipv4/tcp_";
1758 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1759 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1760 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1761 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1762 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1763 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1764 mCurrentTcpBufferSizes = tcpBufferSizes;
1765 } catch (IOException e) {
1766 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001767 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001768
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001769 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001770 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001771 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1772 if (rwndValue != 0) {
1773 SystemProperties.set(sysctlKey, rwndValue.toString());
1774 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001775 }
1776
Mattias Falk8b47b362011-08-23 14:15:13 +02001777 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001778 /*
1779 * Tell the VMs to toss their DNS caches
1780 */
1781 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1782 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001783 /*
1784 * Connectivity events can happen before boot has completed ...
1785 */
1786 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001787 final long ident = Binder.clearCallingIdentity();
1788 try {
1789 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1790 } finally {
1791 Binder.restoreCallingIdentity(ident);
1792 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001793 }
1794
Robert Greenwalt562cc542014-05-15 18:07:26 -07001795 @Override
1796 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001797 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1798 NETWORK_RESTORE_DELAY_PROP_NAME);
1799 if(restoreDefaultNetworkDelayStr != null &&
1800 restoreDefaultNetworkDelayStr.length() != 0) {
1801 try {
Narayan Kamatha09b4d22016-04-15 18:32:45 +01001802 return Integer.parseInt(restoreDefaultNetworkDelayStr);
Robert Greenwalt42acef32009-08-12 16:08:25 -07001803 } catch (NumberFormatException e) {
1804 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001805 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001806 // if the system property isn't set, use the value for the apn type
1807 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1808
1809 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1810 (mNetConfigs[networkType] != null)) {
1811 ret = mNetConfigs[networkType].restoreTime;
1812 }
1813 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001814 }
1815
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001816 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001817 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001818 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001819 }
1820 return false;
1821 }
1822
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001823 private void dumpNetworkDiagnostics(IndentingPrintWriter pw) {
1824 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1825 final long DIAG_TIME_MS = 5000;
1826 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1827 // Start gathering diagnostic information.
1828 netDiags.add(new NetworkDiagnostics(
1829 nai.network,
1830 new LinkProperties(nai.linkProperties), // Must be a copy.
1831 DIAG_TIME_MS));
1832 }
1833
1834 for (NetworkDiagnostics netDiag : netDiags) {
1835 pw.println();
1836 netDiag.waitForMeasurements();
1837 netDiag.dump(pw);
1838 }
1839 }
1840
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001841 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001842 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1843 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001844 if (mContext.checkCallingOrSelfPermission(
1845 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001846 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001847 pw.println("Permission Denial: can't dump ConnectivityService " +
1848 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1849 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001850 return;
1851 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001852
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001853 if (argsContain(args, "--diag")) {
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001854 dumpNetworkDiagnostics(pw);
1855 return;
1856 }
Erik Kline379747a2015-06-05 17:47:34 +09001857
Lorenzo Colittie3805462015-06-03 11:18:24 +09001858 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001859 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001860 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001861 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001862 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001863 pw.println();
1864
Paul Jensen85cf78e2015-06-25 13:25:07 -04001865 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001866 pw.print("Active default network: ");
1867 if (defaultNai == null) {
1868 pw.println("none");
1869 } else {
1870 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001871 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001872 pw.println();
1873
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001874 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001875 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001876 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1877 pw.println(nai.toString());
1878 pw.increaseIndent();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09001879 pw.println(String.format(
1880 "Requests: REQUEST:%d LISTEN:%d BACKGROUND_REQUEST:%d total:%d",
1881 nai.numForegroundNetworkRequests(),
1882 nai.numNetworkRequests() - nai.numRequestNetworkRequests(),
1883 nai.numBackgroundNetworkRequests(),
1884 nai.numNetworkRequests()));
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001885 pw.increaseIndent();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09001886 for (int i = 0; i < nai.numNetworkRequests(); i++) {
1887 pw.println(nai.requestAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001888 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001889 pw.decreaseIndent();
1890 pw.println("Lingered:");
1891 pw.increaseIndent();
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09001892 nai.dumpLingerTimers(pw);
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001893 pw.decreaseIndent();
1894 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001895 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001896 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001897 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001898
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001899 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001900 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001901 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1902 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001903 }
1904 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001905 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001906
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001907 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001908
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001909 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001910 pw.print("mNetTransitionWakeLock: currently " +
1911 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1912 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1913 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1914 } else {
1915 pw.println(", last requested never");
1916 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001917 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001918
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001919 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001920 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001921
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001922 pw.println();
1923 mKeepaliveTracker.dump(pw);
1924
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001925 pw.println();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001926 dumpAvoidBadWifiSettings(pw);
Lorenzo Colitti5ff640d2016-03-03 17:53:46 +09001927
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09001928 pw.println();
Lorenzo Colittie3805462015-06-03 11:18:24 +09001929 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001930 pw.println();
1931 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001932 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001933 for(int i = 0; i < mInetLog.size(); i++) {
1934 pw.println(mInetLog.get(i));
1935 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001936 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001937 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001938
1939 if (argsContain(args, "--short") == false) {
1940 pw.println();
1941 synchronized (mValidationLogs) {
1942 pw.println("mValidationLogs (most recent first):");
Paul Jensen0808eb82016-06-03 13:51:21 -04001943 for (ValidationLog p : mValidationLogs) {
1944 pw.println(p.mNetwork + " - " + p.mNetworkExtraInfo);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001945 pw.increaseIndent();
Paul Jensen0808eb82016-06-03 13:51:21 -04001946 p.mLog.dump(fd, pw, args);
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001947 pw.decreaseIndent();
1948 }
1949 }
Erik Kline7523eb32015-07-09 18:24:03 +09001950
1951 pw.println();
1952 pw.println("mNetworkRequestInfoLogs (most recent first):");
1953 pw.increaseIndent();
1954 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1955 pw.decreaseIndent();
Hugo Benichic2ae2872016-07-11 11:05:12 +09001956
1957 pw.println();
1958 pw.println("mNetworkInfoBlockingLogs (most recent first):");
1959 pw.increaseIndent();
1960 mNetworkInfoBlockingLogs.reverseDump(fd, pw, args);
1961 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001962 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001963 }
1964
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001965 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, int what) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001966 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001967 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001968 if (officialNai != null && officialNai.equals(nai)) return true;
1969 if (officialNai != null || VDBG) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001970 final String msg = sMagicDecoderRing.get(what, Integer.toString(what));
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001971 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001972 " - " + nai);
1973 }
1974 return false;
1975 }
1976
Robert Greenwalt42acef32009-08-12 16:08:25 -07001977 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001978 private class NetworkStateTrackerHandler extends Handler {
1979 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001980 super(looper);
1981 }
1982
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001983 private boolean maybeHandleAsyncChannelMessage(Message msg) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001984 switch (msg.what) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09001985 default:
1986 return false;
Robert Greenwalte049c232014-04-11 15:53:27 -07001987 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001988 handleAsyncChannelHalfConnect(msg);
1989 break;
1990 }
1991 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1992 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1993 if (nai != null) nai.asyncChannel.disconnect();
1994 break;
1995 }
1996 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1997 handleAsyncChannelDisconnected(msg);
1998 break;
1999 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002000 }
2001 return true;
2002 }
2003
2004 private void maybeHandleNetworkAgentMessage(Message msg) {
2005 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2006 if (nai == null) {
2007 if (VDBG) {
2008 final String what = sMagicDecoderRing.get(msg.what, Integer.toString(msg.what));
2009 log(String.format("%s from unknown NetworkAgent", what));
2010 }
2011 return;
2012 }
2013
2014 switch (msg.what) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002015 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002016 final NetworkCapabilities networkCapabilities = (NetworkCapabilities) msg.obj;
2017 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002018 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED) ||
2019 networkCapabilities.hasCapability(NET_CAPABILITY_FOREGROUND)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002020 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Robert Greenwalte049c232014-04-11 15:53:27 -07002021 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002022 updateCapabilities(nai.getCurrentScore(), nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07002023 break;
2024 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002025 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002026 if (VDBG) {
2027 log("Update of LinkProperties for " + nai.name() +
Robin Lee585e2482016-05-01 23:00:00 +01002028 "; created=" + nai.created +
2029 "; everConnected=" + nai.everConnected);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002030 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002031 LinkProperties oldLp = nai.linkProperties;
2032 synchronized (nai) {
2033 nai.linkProperties = (LinkProperties)msg.obj;
2034 }
Robin Lee585e2482016-05-01 23:00:00 +01002035 if (nai.everConnected) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002036 break;
2037 }
2038 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002039 NetworkInfo info = (NetworkInfo) msg.obj;
Robert Greenwalt7b816022014-04-18 15:25:25 -07002040 updateNetworkInfo(nai, info);
2041 break;
2042 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07002043 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002044 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07002045 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07002046 break;
2047 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002048 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002049 try {
2050 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002051 } catch (Exception e) {
2052 // Never crash!
2053 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002054 }
2055 break;
2056 }
2057 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002058 try {
2059 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002060 } catch (Exception e) {
2061 // Never crash!
2062 loge("Exception in removeVpnUidRanges: " + e);
2063 }
2064 break;
2065 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002066 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
Robin Lee585e2482016-05-01 23:00:00 +01002067 if (nai.everConnected && !nai.networkMisc.explicitlySelected) {
2068 loge("ERROR: already-connected network explicitly selected.");
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002069 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002070 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002071 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002072 break;
2073 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002074 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002075 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2076 break;
2077 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002078 }
2079 }
2080
2081 private boolean maybeHandleNetworkMonitorMessage(Message msg) {
2082 switch (msg.what) {
2083 default:
2084 return false;
Paul Jensenad50a1f2014-09-05 12:06:44 -04002085 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Paul Jensen232437312016-04-06 09:51:26 -04002086 final NetworkAgentInfo nai;
2087 synchronized (mNetworkForNetId) {
2088 nai = mNetworkForNetId.get(msg.arg2);
2089 }
2090 if (nai != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002091 final boolean valid =
2092 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002093 final boolean wasValidated = nai.lastValidated;
Paul Jensen232437312016-04-06 09:51:26 -04002094 if (DBG) log(nai.name() + " validation " + (valid ? "passed" : "failed") +
2095 (msg.obj == null ? "" : " with redirect to " + (String)msg.obj));
Paul Jensen1c7ba022015-06-16 14:27:36 -04002096 if (valid != nai.lastValidated) {
2097 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002098 nai.lastValidated = valid;
2099 nai.everValidated |= valid;
Hugo Benichif15b2822016-09-15 18:18:48 +09002100 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002101 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2102 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002103 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002104 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002105 // Let the NetworkAgent know the state of its network
Paul Jensen232437312016-04-06 09:51:26 -04002106 Bundle redirectUrlBundle = new Bundle();
2107 redirectUrlBundle.putString(NetworkAgent.REDIRECT_URL_KEY, (String)msg.obj);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002108 nai.asyncChannel.sendMessage(
Paul Jensen232437312016-04-06 09:51:26 -04002109 NetworkAgent.CMD_REPORT_NETWORK_STATUS,
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002110 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
Paul Jensen232437312016-04-06 09:51:26 -04002111 0, redirectUrlBundle);
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002112 if (wasValidated && !nai.lastValidated) {
2113 handleNetworkUnvalidated(nai);
2114 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002115 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002116 break;
2117 }
Paul Jensen869868be2014-05-15 10:33:05 -04002118 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002119 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002120 final boolean visible = (msg.arg1 != 0);
2121 final NetworkAgentInfo nai;
2122 synchronized (mNetworkForNetId) {
2123 nai = mNetworkForNetId.get(netId);
2124 }
Calvin Onbe96da12016-10-11 15:10:46 -07002125 // If captive portal status has changed, update capabilities or disconnect.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002126 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
Hugo Benichif15b2822016-09-15 18:18:48 +09002127 final int oldScore = nai.getCurrentScore();
Paul Jensen3d194ea2015-06-16 14:27:36 -04002128 nai.lastCaptivePortalDetected = visible;
2129 nai.everCaptivePortalDetected |= visible;
Calvin Onbe96da12016-10-11 15:10:46 -07002130 if (nai.lastCaptivePortalDetected &&
2131 Settings.Global.CAPTIVE_PORTAL_MODE_AVOID == getCaptivePortalMode()) {
2132 if (DBG) log("Avoiding captive portal network: " + nai.name());
2133 nai.asyncChannel.sendMessage(
2134 NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2135 teardownUnneededNetwork(nai);
2136 break;
2137 }
Hugo Benichif15b2822016-09-15 18:18:48 +09002138 updateCapabilities(oldScore, nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002139 }
2140 if (!visible) {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002141 mNotifier.clearNotification(netId);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002142 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002143 if (nai == null) {
2144 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2145 break;
2146 }
fionaxu1bf6ec22016-05-23 16:33:16 -07002147 if (!nai.networkMisc.provisioningNotificationDisabled) {
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002148 mNotifier.showNotification(netId, NotificationType.SIGN_IN, nai, null,
Lorenzo Colitti0b599062016-08-22 22:36:19 +09002149 (PendingIntent) msg.obj, nai.networkMisc.explicitlySelected);
fionaxu1bf6ec22016-05-23 16:33:16 -07002150 }
Paul Jensen869868be2014-05-15 10:33:05 -04002151 }
Paul Jensen869868be2014-05-15 10:33:05 -04002152 break;
2153 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002154 }
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002155 return true;
2156 }
2157
Calvin Onbe96da12016-10-11 15:10:46 -07002158 private int getCaptivePortalMode() {
2159 return Settings.Global.getInt(mContext.getContentResolver(),
2160 Settings.Global.CAPTIVE_PORTAL_MODE,
2161 Settings.Global.CAPTIVE_PORTAL_MODE_PROMPT);
2162 }
2163
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002164 private boolean maybeHandleNetworkAgentInfoMessage(Message msg) {
2165 switch (msg.what) {
2166 default:
2167 return false;
2168 case NetworkAgentInfo.EVENT_NETWORK_LINGER_COMPLETE: {
2169 NetworkAgentInfo nai = (NetworkAgentInfo) msg.obj;
2170 if (nai != null && isLiveNetworkAgent(nai, msg.what)) {
2171 handleLingerComplete(nai);
2172 }
2173 break;
2174 }
2175 }
2176 return true;
2177 }
2178
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002179 @Override
2180 public void handleMessage(Message msg) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002181 if (!maybeHandleAsyncChannelMessage(msg) &&
2182 !maybeHandleNetworkMonitorMessage(msg) &&
2183 !maybeHandleNetworkAgentInfoMessage(msg)) {
Lorenzo Colitti9b0c8fd2016-04-05 17:52:16 +09002184 maybeHandleNetworkAgentMessage(msg);
2185 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002186 }
2187 }
2188
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002189 private void updateLingerState(NetworkAgentInfo nai, long now) {
2190 // 1. Update the linger timer. If it's changed, reschedule or cancel the alarm.
2191 // 2. If the network was lingering and there are now requests, unlinger it.
2192 // 3. If this network is unneeded (which implies it is not lingering), and there is at least
2193 // one lingered request, start lingering.
2194 nai.updateLingerTimer();
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002195 if (nai.isLingering() && nai.numForegroundNetworkRequests() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002196 if (DBG) log("Unlingering " + nai.name());
2197 nai.unlinger();
2198 logNetworkEvent(nai, NetworkEvent.NETWORK_UNLINGER);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002199 } else if (unneeded(nai, UnneededFor.LINGER) && nai.getLingerExpiry() > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002200 int lingerTime = (int) (nai.getLingerExpiry() - now);
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002201 if (DBG) log("Lingering " + nai.name() + " for " + lingerTime + "ms");
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002202 nai.linger();
2203 logNetworkEvent(nai, NetworkEvent.NETWORK_LINGER);
2204 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING, lingerTime);
2205 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002206 }
2207
Robert Greenwalt7b816022014-04-18 15:25:25 -07002208 private void handleAsyncChannelHalfConnect(Message msg) {
2209 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002210 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002211 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2212 if (VDBG) log("NetworkFactory connected");
2213 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002214 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002215 if (nri.request.isListen()) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002216 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002217 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002218 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002219 }
2220 } else {
2221 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002222 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002223 }
2224 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2225 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2226 if (VDBG) log("NetworkAgent connected");
2227 // A network agent has requested a connection. Establish the connection.
2228 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2229 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2230 } else {
2231 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002232 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002233 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002234 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002235 synchronized (mNetworkForNetId) {
2236 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002237 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002238 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002239 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002240 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002241 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002242 }
2243 }
2244 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002245
Robert Greenwalt7b816022014-04-18 15:25:25 -07002246 private void handleAsyncChannelDisconnected(Message msg) {
2247 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2248 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002249 if (DBG) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002250 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.numNetworkRequests());
Robert Greenwalt9258c642014-03-26 16:47:06 -07002251 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002252 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002253 // TODO - if we move the logic to the network agent (have them disconnect
2254 // because they lost all their requests or because their score isn't good)
2255 // then they would disconnect organically, report their new state and then
2256 // disconnect the channel.
2257 if (nai.networkInfo.isConnected()) {
2258 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2259 null, null);
2260 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002261 final boolean wasDefault = isDefaultNetwork(nai);
2262 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002263 mDefaultInetConditionPublished = 0;
Hugo Benichi1654b1d2016-05-24 11:50:31 +09002264 // Log default network disconnection before required book-keeping.
2265 // Let rematchAllNetworksAndRequests() below record a new default network event
2266 // if there is a fallback. Taken together, the two form a X -> 0, 0 -> Y sequence
2267 // whose timestamps tell how long it takes to recover a default network.
2268 logDefaultNetworkEvent(null, nai);
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002269 }
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08002270 notifyIfacesChangedForNetworkStats();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002271 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2272 // by other networks that are already connected. Perhaps that can be done by
2273 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2274 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002275 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002276 mKeepaliveTracker.handleStopAllKeepalives(nai,
2277 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002278 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002279 mNetworkAgentInfos.remove(msg.replyTo);
2280 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002281 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002282 // Remove the NetworkAgent, but don't mark the netId as
2283 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002284 mNetworkForNetId.remove(nai.network.netId);
2285 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002286 // Remove all previously satisfied requests.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002287 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2288 NetworkRequest request = nai.requestAt(i);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002289 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2290 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2291 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002292 sendUpdatedScoreToFactories(request, 0);
2293 }
2294 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002295 nai.clearLingerState();
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002296 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002297 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002298 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002299 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002300 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002301 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002302 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09002303 mLingerMonitor.noteDisconnect(nai);
Paul Jensen62d30802015-06-17 14:42:30 -04002304 if (nai.created) {
2305 // Tell netd to clean up the configuration for this network
2306 // (routing rules, DNS, etc).
2307 // This may be slow as it requires a lot of netd shelling out to ip and
2308 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2309 // after we've rematched networks with requests which should make a potential
2310 // fallback network the default or requested a new network from the
2311 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2312 // long time.
2313 try {
2314 mNetd.removeNetwork(nai.network.netId);
2315 } catch (Exception e) {
2316 loge("Exception removing network: " + e);
2317 }
2318 }
2319 synchronized (mNetworkForNetId) {
2320 mNetIdInUse.delete(nai.network.netId);
2321 }
2322 } else {
2323 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2324 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002325 }
2326 }
2327
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002328 // If this method proves to be too slow then we can maintain a separate
2329 // pendingIntent => NetworkRequestInfo map.
2330 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2331 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2332 Intent intent = pendingIntent.getIntent();
2333 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2334 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2335 if (existingPendingIntent != null &&
2336 existingPendingIntent.getIntent().filterEquals(intent)) {
2337 return entry.getValue();
2338 }
2339 }
2340 return null;
2341 }
2342
2343 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2344 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2345
2346 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2347 if (existingRequest != null) { // remove the existing request.
2348 if (DBG) log("Replacing " + existingRequest.request + " with "
2349 + nri.request + " because their intents matched.");
2350 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2351 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002352 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002353 }
2354
Erik Klineda4bfa82015-04-30 12:58:40 +09002355 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002356 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002357 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09002358 if (nri.request.isListen()) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002359 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002360 if (nri.request.networkCapabilities.hasSignalStrength() &&
2361 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2362 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002363 }
2364 }
2365 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002366 rematchAllNetworksAndRequests(null, 0);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002367 if (nri.request.isRequest() && mNetworkForRequestId.get(nri.request.requestId) == null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002368 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002369 }
2370 }
2371
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002372 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2373 int callingUid) {
2374 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2375 if (nri != null) {
2376 handleReleaseNetworkRequest(nri.request, callingUid);
2377 }
2378 }
2379
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002380 // Determines whether the network is the best (or could become the best, if it validated), for
2381 // none of a particular type of NetworkRequests. The type of NetworkRequests considered depends
2382 // on the value of reason:
2383 //
2384 // - UnneededFor.TEARDOWN: non-listen NetworkRequests. If a network is unneeded for this reason,
2385 // then it should be torn down.
2386 // - UnneededFor.LINGER: foreground NetworkRequests. If a network is unneeded for this reason,
2387 // then it should be lingered.
2388 private boolean unneeded(NetworkAgentInfo nai, UnneededFor reason) {
2389 final int numRequests;
2390 switch (reason) {
2391 case TEARDOWN:
2392 numRequests = nai.numRequestNetworkRequests();
2393 break;
2394 case LINGER:
2395 numRequests = nai.numForegroundNetworkRequests();
2396 break;
2397 default:
2398 Slog.wtf(TAG, "Invalid reason. Cannot happen.");
2399 return true;
2400 }
2401
2402 if (!nai.everConnected || nai.isVPN() || nai.isLingering() || numRequests > 0) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09002403 return false;
2404 }
Paul Jensene0988542015-06-25 15:30:08 -04002405 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002406 if (reason == UnneededFor.LINGER && nri.request.isBackgroundRequest()) {
2407 // Background requests don't affect lingering.
2408 continue;
2409 }
2410
Paul Jensene0988542015-06-25 15:30:08 -04002411 // If this Network is already the highest scoring Network for a request, or if
2412 // there is hope for it to become one if it validated, then it is needed.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09002413 if (nri.request.isRequest() && nai.satisfies(nri.request) &&
Lorenzo Colitti767708d2016-07-01 01:37:11 +09002414 (nai.isSatisfyingRequest(nri.request.requestId) ||
Paul Jensene0988542015-06-25 15:30:08 -04002415 // Note that this catches two important cases:
2416 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2417 // is currently satisfying the request. This is desirable when
2418 // cellular ends up validating but WiFi does not.
2419 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002420 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002421 // WiFi ends up validating and out scoring cellular.
2422 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2423 nai.getCurrentScoreAsValidated())) {
2424 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002425 }
2426 }
Paul Jensene0988542015-06-25 15:30:08 -04002427 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002428 }
2429
Erik Klineacdd6392016-07-07 16:50:58 +09002430 private NetworkRequestInfo getNriForAppRequest(
2431 NetworkRequest request, int callingUid, String requestedOperation) {
2432 final NetworkRequestInfo nri = mNetworkRequests.get(request);
2433
Robert Greenwalt9258c642014-03-26 16:47:06 -07002434 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002435 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Erik Klineacdd6392016-07-07 16:50:58 +09002436 log(String.format("UID %d attempted to %s for unowned request %s",
2437 callingUid, requestedOperation, nri));
2438 return null;
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002439 }
Erik Klineacdd6392016-07-07 16:50:58 +09002440 }
2441
2442 return nri;
2443 }
2444
Erik Kline57faba92015-11-25 12:49:38 +09002445 private void handleTimedOutNetworkRequest(final NetworkRequestInfo nri) {
2446 if (mNetworkRequests.get(nri.request) != null && mNetworkForRequestId.get(
2447 nri.request.requestId) == null) {
2448 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_UNAVAIL);
2449 }
2450 }
2451
Erik Klineacdd6392016-07-07 16:50:58 +09002452 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2453 final NetworkRequestInfo nri = getNriForAppRequest(
2454 request, callingUid, "release NetworkRequest");
Erik Kline57faba92015-11-25 12:49:38 +09002455 if (nri != null) {
2456 handleRemoveNetworkRequest(nri, ConnectivityManager.CALLBACK_RELEASED);
2457 }
2458 }
Erik Klineacdd6392016-07-07 16:50:58 +09002459
Erik Kline57faba92015-11-25 12:49:38 +09002460 private void handleRemoveNetworkRequest(final NetworkRequestInfo nri, final int whichCallback) {
2461 final String logCallbackType = ConnectivityManager.getCallbackName(whichCallback);
2462 if (VDBG || (DBG && nri.request.isRequest())) {
2463 log("releasing " + nri.request + " (" + logCallbackType + ")");
2464 }
Erik Klineacdd6392016-07-07 16:50:58 +09002465 nri.unlinkDeathRecipient();
Erik Kline57faba92015-11-25 12:49:38 +09002466 mNetworkRequests.remove(nri.request);
Erik Klineacdd6392016-07-07 16:50:58 +09002467 synchronized (mUidToNetworkRequestCount) {
2468 int requests = mUidToNetworkRequestCount.get(nri.mUid, 0);
2469 if (requests < 1) {
2470 Slog.wtf(TAG, "BUG: too small request count " + requests + " for UID " +
2471 nri.mUid);
2472 } else if (requests == 1) {
2473 mUidToNetworkRequestCount.removeAt(
2474 mUidToNetworkRequestCount.indexOfKey(nri.mUid));
2475 } else {
2476 mUidToNetworkRequestCount.put(nri.mUid, requests - 1);
2477 }
2478 }
2479 mNetworkRequestInfoLogs.log("RELEASE " + nri);
2480 if (nri.request.isRequest()) {
2481 boolean wasKept = false;
2482 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2483 if (nai != null) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002484 boolean wasBackgroundNetwork = nai.isBackgroundNetwork();
Erik Klineacdd6392016-07-07 16:50:58 +09002485 nai.removeRequest(nri.request.requestId);
2486 if (VDBG) {
2487 log(" Removing from current network " + nai.name() +
2488 ", leaving " + nai.numNetworkRequests() + " requests.");
2489 }
2490 // If there are still lingered requests on this network, don't tear it down,
2491 // but resume lingering instead.
2492 updateLingerState(nai, SystemClock.elapsedRealtime());
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09002493 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Erik Klineacdd6392016-07-07 16:50:58 +09002494 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
2495 teardownUnneededNetwork(nai);
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002496 } else {
Erik Klineacdd6392016-07-07 16:50:58 +09002497 wasKept = true;
2498 }
2499 mNetworkForRequestId.remove(nri.request.requestId);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002500 if (!wasBackgroundNetwork && nai.isBackgroundNetwork()) {
2501 // Went from foreground to background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09002502 updateCapabilities(nai.getCurrentScore(), nai, nai.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09002503 }
Erik Klineacdd6392016-07-07 16:50:58 +09002504 }
2505
2506 // TODO: remove this code once we know that the Slog.wtf is never hit.
2507 //
2508 // Find all networks that are satisfying this request and remove the request
2509 // from their request lists.
2510 // TODO - it's my understanding that for a request there is only a single
2511 // network satisfying it, so this loop is wasteful
2512 for (NetworkAgentInfo otherNai : mNetworkAgentInfos.values()) {
2513 if (otherNai.isSatisfyingRequest(nri.request.requestId) && otherNai != nai) {
2514 Slog.wtf(TAG, "Request " + nri.request + " satisfied by " +
2515 otherNai.name() + ", but mNetworkAgentInfos says " +
2516 (nai != null ? nai.name() : "null"));
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04002517 }
2518 }
Lorenzo Colitti446598c2016-07-06 19:04:26 +09002519
Erik Klineacdd6392016-07-07 16:50:58 +09002520 // Maintain the illusion. When this request arrived, we might have pretended
2521 // that a network connected to serve it, even though the network was already
2522 // connected. Now that this request has gone away, we might have to pretend
2523 // that the network disconnected. LegacyTypeTracker will generate that
2524 // phantom disconnect for this type.
2525 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2526 boolean doRemove = true;
2527 if (wasKept) {
2528 // check if any of the remaining requests for this network are for the
2529 // same legacy type - if so, don't remove the nai
2530 for (int i = 0; i < nai.numNetworkRequests(); i++) {
2531 NetworkRequest otherRequest = nai.requestAt(i);
2532 if (otherRequest.legacyType == nri.request.legacyType &&
2533 otherRequest.isRequest()) {
2534 if (DBG) log(" still have other legacy request - leaving");
2535 doRemove = false;
Robert Greenwalt51481852015-01-08 14:43:31 -08002536 }
2537 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002538 }
2539
Erik Klineacdd6392016-07-07 16:50:58 +09002540 if (doRemove) {
2541 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002542 }
2543 }
Erik Klineacdd6392016-07-07 16:50:58 +09002544
2545 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
2546 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2547 nri.request);
2548 }
2549 } else {
2550 // listens don't have a singular affectedNetwork. Check all networks to see
2551 // if this listen request applies and remove it.
2552 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2553 nai.removeRequest(nri.request.requestId);
2554 if (nri.request.networkCapabilities.hasSignalStrength() &&
2555 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2556 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
2557 }
2558 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002559 }
Erik Kline57faba92015-11-25 12:49:38 +09002560 callCallbackForRequest(nri, null, whichCallback, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002561 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002562
Lorenzo Colitti18660282016-07-04 12:55:44 +09002563 @Override
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002564 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2565 enforceConnectivityInternalPermission();
2566 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2567 accept ? 1 : 0, always ? 1: 0, network));
2568 }
2569
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002570 @Override
2571 public void setAvoidUnvalidated(Network network) {
2572 enforceConnectivityInternalPermission();
2573 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_AVOID_UNVALIDATED, network));
2574 }
2575
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002576 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2577 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2578 " accept=" + accept + " always=" + always);
2579
2580 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2581 if (nai == null) {
2582 // Nothing to do.
2583 return;
2584 }
2585
2586 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002587 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002588 return;
2589 }
2590
2591 if (!nai.networkMisc.explicitlySelected) {
2592 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2593 }
2594
2595 if (accept != nai.networkMisc.acceptUnvalidated) {
2596 int oldScore = nai.getCurrentScore();
2597 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002598 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002599 sendUpdatedScoreToFactories(nai);
2600 }
2601
2602 if (always) {
2603 nai.asyncChannel.sendMessage(
2604 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2605 }
2606
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002607 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002608 // Tell the NetworkAgent to not automatically reconnect to the network.
2609 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2610 // Teardown the nework.
2611 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002612 }
2613
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002614 }
2615
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002616 private void handleSetAvoidUnvalidated(Network network) {
2617 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2618 if (nai == null || nai.lastValidated) {
2619 // Nothing to do. The network either disconnected or revalidated.
2620 return;
2621 }
2622 if (!nai.avoidUnvalidated) {
2623 int oldScore = nai.getCurrentScore();
2624 nai.avoidUnvalidated = true;
2625 rematchAllNetworksAndRequests(nai, oldScore);
2626 sendUpdatedScoreToFactories(nai);
2627 }
2628 }
2629
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002630 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002631 if (VDBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002632 mHandler.sendMessageDelayed(
2633 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2634 PROMPT_UNVALIDATED_DELAY_MS);
2635 }
2636
Hugo Benichic8e9e122016-09-14 23:23:08 +00002637 public boolean avoidBadWifi() {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002638 return mMultinetworkPolicyTracker.getAvoidBadWifi();
Lorenzo Colitti2618c1b2016-09-16 23:43:38 +09002639 }
2640
Erik Kline065ab6e2016-10-02 18:02:14 +09002641 private void rematchForAvoidBadWifiUpdate() {
2642 rematchAllNetworksAndRequests(null, 0);
2643 for (NetworkAgentInfo nai: mNetworkAgentInfos.values()) {
2644 if (nai.networkCapabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI)) {
2645 sendUpdatedScoreToFactories(nai);
2646 }
2647 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002648 }
2649
Erik Kline065ab6e2016-10-02 18:02:14 +09002650 // TODO: Evaluate whether this is of interest to other consumers of
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002651 // MultinetworkPolicyTracker and worth moving out of here.
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002652 private void dumpAvoidBadWifiSettings(IndentingPrintWriter pw) {
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002653 final boolean configRestrict = mMultinetworkPolicyTracker.configRestrictsAvoidBadWifi();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002654 if (!configRestrict) {
2655 pw.println("Bad Wi-Fi avoidance: unrestricted");
2656 return;
2657 }
2658
2659 pw.println("Bad Wi-Fi avoidance: " + avoidBadWifi());
2660 pw.increaseIndent();
2661 pw.println("Config restrict: " + configRestrict);
2662
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002663 final String value = mMultinetworkPolicyTracker.getAvoidBadWifiSetting();
Lorenzo Colitti29bd3842016-09-20 16:03:27 +09002664 String description;
2665 // Can't use a switch statement because strings are legal case labels, but null is not.
2666 if ("0".equals(value)) {
2667 description = "get stuck";
2668 } else if (value == null) {
2669 description = "prompt";
2670 } else if ("1".equals(value)) {
2671 description = "avoid";
2672 } else {
2673 description = value + " (?)";
2674 }
2675 pw.println("User setting: " + description);
2676 pw.println("Network overrides:");
2677 pw.increaseIndent();
2678 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2679 if (nai.avoidUnvalidated) {
2680 pw.println(nai.name());
2681 }
2682 }
2683 pw.decreaseIndent();
2684 pw.decreaseIndent();
2685 }
2686
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002687 private void showValidationNotification(NetworkAgentInfo nai, NotificationType type) {
2688 final String action;
2689 switch (type) {
2690 case NO_INTERNET:
2691 action = ConnectivityManager.ACTION_PROMPT_UNVALIDATED;
2692 break;
2693 case LOST_INTERNET:
2694 action = ConnectivityManager.ACTION_PROMPT_LOST_VALIDATION;
2695 break;
2696 default:
2697 Slog.wtf(TAG, "Unknown notification type " + type);
2698 return;
2699 }
2700
2701 Intent intent = new Intent(action);
2702 intent.setData(Uri.fromParts("netId", Integer.toString(nai.network.netId), null));
2703 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2704 intent.setClassName("com.android.settings",
2705 "com.android.settings.wifi.WifiNoInternetDialog");
2706
2707 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2708 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2709 mNotifier.showNotification(nai.network.netId, type, nai, null, pendingIntent, true);
2710 }
2711
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002712 private void handlePromptUnvalidated(Network network) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002713 if (VDBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002714 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2715
2716 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2717 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002718 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002719 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002720 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2721 return;
2722 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002723 showValidationNotification(nai, NotificationType.NO_INTERNET);
2724 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002725
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002726 private void handleNetworkUnvalidated(NetworkAgentInfo nai) {
2727 NetworkCapabilities nc = nai.networkCapabilities;
2728 if (DBG) log("handleNetworkUnvalidated " + nai.name() + " cap=" + nc);
fionaxu1bf6ec22016-05-23 16:33:16 -07002729
Erik Kline065ab6e2016-10-02 18:02:14 +09002730 if (nc.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) &&
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09002731 mMultinetworkPolicyTracker.shouldNotifyWifiUnvalidated()) {
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09002732 showValidationNotification(nai, NotificationType.LOST_INTERNET);
2733 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002734 }
2735
Lorenzo Colitti2de49252017-01-24 18:08:41 +09002736 @Override
2737 public int getMultipathPreference(Network network) {
2738 enforceAccessPermission();
2739
2740 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2741 if (nai != null && !nai.networkInfo.isMetered()) {
2742 return ConnectivityManager.MULTIPATH_PREFERENCE_UNMETERED;
2743 }
2744
2745 return mMultinetworkPolicyTracker.getMeteredMultipathPreference();
2746 }
2747
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002748 private class InternalHandler extends Handler {
2749 public InternalHandler(Looper looper) {
2750 super(looper);
2751 }
2752
2753 @Override
2754 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002755 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002756 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002757 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002758 String causedBy = null;
2759 synchronized (ConnectivityService.this) {
2760 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2761 mNetTransitionWakeLock.isHeld()) {
2762 mNetTransitionWakeLock.release();
2763 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002764 } else {
2765 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002766 }
2767 }
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09002768 if (VDBG) {
2769 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2770 log("Failed to find a new network - expiring NetTransition Wakelock");
2771 } else {
2772 log("NetTransition Wakelock (" +
2773 (causedBy == null ? "unknown" : causedBy) +
2774 " cleared because we found a replacement network");
2775 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002776 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002777 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002778 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002779 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002780 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002781 break;
2782 }
Jason Monkdecd2952013-10-10 14:02:51 -04002783 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002784 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002785 break;
2786 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002787 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002788 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2789 break;
2790 }
2791 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2792 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002793 break;
2794 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002795 case EVENT_REGISTER_NETWORK_AGENT: {
2796 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2797 break;
2798 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002799 case EVENT_REGISTER_NETWORK_REQUEST:
2800 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002801 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002802 break;
2803 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002804 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2805 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002806 handleRegisterNetworkRequestWithIntent(msg);
2807 break;
2808 }
Erik Kline57faba92015-11-25 12:49:38 +09002809 case EVENT_TIMEOUT_NETWORK_REQUEST: {
2810 NetworkRequestInfo nri = (NetworkRequestInfo) msg.obj;
2811 handleTimedOutNetworkRequest(nri);
2812 break;
2813 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002814 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2815 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2816 break;
2817 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002818 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002819 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002820 break;
2821 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002822 case EVENT_SET_ACCEPT_UNVALIDATED: {
2823 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2824 break;
2825 }
Lorenzo Colitti165c51c2016-09-19 01:00:19 +09002826 case EVENT_SET_AVOID_UNVALIDATED: {
2827 handleSetAvoidUnvalidated((Network) msg.obj);
2828 break;
2829 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002830 case EVENT_PROMPT_UNVALIDATED: {
2831 handlePromptUnvalidated((Network) msg.obj);
2832 break;
2833 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002834 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2835 handleMobileDataAlwaysOn();
2836 break;
2837 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002838 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2839 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2840 mKeepaliveTracker.handleStartKeepalive(msg);
2841 break;
2842 }
2843 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2844 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2845 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2846 int slot = msg.arg1;
2847 int reason = msg.arg2;
2848 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2849 break;
2850 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002851 case EVENT_SYSTEM_READY: {
2852 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2853 nai.networkMonitor.systemReady = true;
2854 }
2855 break;
2856 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002857 }
2858 }
2859 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002860
2861 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002862 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002863 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002864 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002865 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002866 final int status = mTethering.tether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002867 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002868 } else {
2869 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2870 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002871 }
2872
2873 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002874 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002875 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002876 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002877
2878 if (isTetheringSupported()) {
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002879 final int status = mTethering.untether(iface);
Felipe Leme70c8b9b2016-04-25 14:41:31 -07002880 return status;
Robert Greenwalt5a735062010-03-02 17:25:02 -08002881 } else {
2882 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2883 }
2884 }
2885
2886 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002887 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002888 public int getLastTetherError(String iface) {
2889 enforceTetherAccessPermission();
2890
2891 if (isTetheringSupported()) {
2892 return mTethering.getLastTetherError(iface);
2893 } else {
2894 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2895 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002896 }
2897
2898 // TODO - proper iface API for selection by property, inspection, etc
Lorenzo Colitti18660282016-07-04 12:55:44 +09002899 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002900 public String[] getTetherableUsbRegexs() {
2901 enforceTetherAccessPermission();
2902 if (isTetheringSupported()) {
2903 return mTethering.getTetherableUsbRegexs();
2904 } else {
2905 return new String[0];
2906 }
2907 }
2908
Lorenzo Colitti18660282016-07-04 12:55:44 +09002909 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002910 public String[] getTetherableWifiRegexs() {
2911 enforceTetherAccessPermission();
2912 if (isTetheringSupported()) {
2913 return mTethering.getTetherableWifiRegexs();
2914 } else {
2915 return new String[0];
2916 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002917 }
2918
Lorenzo Colitti18660282016-07-04 12:55:44 +09002919 @Override
Danica Chang6fdd0c62010-08-11 14:54:43 -07002920 public String[] getTetherableBluetoothRegexs() {
2921 enforceTetherAccessPermission();
2922 if (isTetheringSupported()) {
2923 return mTethering.getTetherableBluetoothRegexs();
2924 } else {
2925 return new String[0];
2926 }
2927 }
2928
Lorenzo Colitti18660282016-07-04 12:55:44 +09002929 @Override
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002930 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002931 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002932 if (isTetheringSupported()) {
2933 return mTethering.setUsbTethering(enable);
2934 } else {
2935 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2936 }
2937 }
2938
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002939 // TODO - move iface listing, queries, etc to new module
2940 // javadoc from interface
Lorenzo Colitti18660282016-07-04 12:55:44 +09002941 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002942 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002943 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002944 return mTethering.getTetherableIfaces();
2945 }
2946
Lorenzo Colitti18660282016-07-04 12:55:44 +09002947 @Override
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002948 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002949 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002950 return mTethering.getTetheredIfaces();
2951 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002952
Lorenzo Colitti18660282016-07-04 12:55:44 +09002953 @Override
Robert Greenwalt5a735062010-03-02 17:25:02 -08002954 public String[] getTetheringErroredIfaces() {
2955 enforceTetherAccessPermission();
2956 return mTethering.getErroredIfaces();
2957 }
2958
Lorenzo Colitti18660282016-07-04 12:55:44 +09002959 @Override
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002960 public String[] getTetheredDhcpRanges() {
2961 enforceConnectivityInternalPermission();
2962 return mTethering.getTetheredDhcpRanges();
2963 }
2964
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002965 // if ro.tether.denied = true we default to no tethering
2966 // gservices could set the secure setting to 1 though to enable it on a build where it
2967 // had previously been turned off.
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002968 @Override
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002969 public boolean isTetheringSupported() {
2970 enforceTetherAccessPermission();
2971 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002972 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002973 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2974 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Jeremy Klein246a1fe2017-03-17 14:30:02 -07002975
2976 // Elevate to system UID to avoid caller requiring MANAGE_USERS permission.
2977 boolean adminUser = false;
2978 final long token = Binder.clearCallingIdentity();
2979 try {
2980 adminUser = mUserManager.isAdminUser();
2981 } finally {
2982 Binder.restoreCallingIdentity(token);
2983 }
2984
2985 return tetherEnabledInSettings && adminUser &&
Erik Klined781fba2017-01-23 13:01:58 +09002986 mTethering.hasTetherableConfiguration();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002987 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002988
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002989 @Override
Hugo Benichib55fb222017-03-10 14:20:57 +09002990 public void startTethering(int type, ResultReceiver receiver, boolean showProvisioningUi) {
Jeremy Klein36c7aa02016-01-22 14:11:45 -08002991 ConnectivityManager.enforceTetherChangePermission(mContext);
2992 if (!isTetheringSupported()) {
2993 receiver.send(ConnectivityManager.TETHER_ERROR_UNSUPPORTED, null);
2994 return;
2995 }
2996 mTethering.startTethering(type, receiver, showProvisioningUi);
2997 }
2998
Jeremy Kleinaaa20ad2016-01-29 12:06:33 -08002999 @Override
Jeremy Klein36c7aa02016-01-22 14:11:45 -08003000 public void stopTethering(int type) {
3001 ConnectivityManager.enforceTetherChangePermission(mContext);
3002 mTethering.stopTethering(type);
3003 }
3004
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07003005 // Called when we lose the default network and have no replacement yet.
3006 // This will automatically be cleared after X seconds or a new default network
3007 // becomes CONNECTED, whichever happens first. The timer is started by the
3008 // first caller and not restarted by subsequent callers.
3009 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07003010 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003011 synchronized (this) {
3012 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07003013 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003014 mNetTransitionWakeLock.acquire();
3015 mNetTransitionWakeLockCausedBy = forWhom;
3016 }
3017 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07003018 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07003019 mNetTransitionWakeLockTimeout);
3020 return;
3021 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07003022
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003023 // 100 percent is full good, 0 is full bad.
Lorenzo Colitti18660282016-07-04 12:55:44 +09003024 @Override
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07003025 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003026 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09003027 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04003028 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07003029 }
3030
Lorenzo Colitti18660282016-07-04 12:55:44 +09003031 @Override
Paul Jensenbfd17b72015-04-07 12:43:13 -04003032 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003033 enforceAccessPermission();
3034 enforceInternetPermission();
3035
Paul Jensenbfd17b72015-04-07 12:43:13 -04003036 NetworkAgentInfo nai;
3037 if (network == null) {
3038 nai = getDefaultNetwork();
3039 } else {
3040 nai = getNetworkAgentInfoForNetwork(network);
3041 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04003042 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
3043 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
3044 return;
3045 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04003046 // Revalidate if the app report does not match our current validated state.
3047 if (hasConnectivity == nai.lastValidated) return;
3048 final int uid = Binder.getCallingUid();
3049 if (DBG) {
3050 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
3051 ") by " + uid);
3052 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003053 synchronized (nai) {
Robin Lee585e2482016-05-01 23:00:00 +01003054 // Validating a network that has not yet connected could result in a call to
3055 // rematchNetworkAndRequests() which is not meant to work on such networks.
3056 if (!nai.everConnected) return;
Paul Jensenc8b9a742014-09-30 15:37:41 -04003057
Jeff Sharkey1b6519b2016-04-28 15:33:18 -06003058 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid, false)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04003059
3060 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
3061 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003062 }
3063
Paul Jensencee9b512015-05-06 07:32:40 -04003064 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003065 // this information is already available as a world read/writable jvm property
3066 // so this API change wouldn't have a benifit. It also breaks the passing
3067 // of proxy info to all the JVMs.
3068 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003069 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04003070 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04003071 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
3072 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003073 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003074 }
3075
Lorenzo Colitti18660282016-07-04 12:55:44 +09003076 @Override
Paul Jensencee9b512015-05-06 07:32:40 -04003077 public ProxyInfo getProxyForNetwork(Network network) {
3078 if (network == null) return getDefaultProxy();
3079 final ProxyInfo globalProxy = getGlobalProxy();
3080 if (globalProxy != null) return globalProxy;
3081 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
3082 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
3083 // caller may not have.
3084 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
3085 if (nai == null) return null;
3086 synchronized (nai) {
3087 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
3088 if (proxyInfo == null) return null;
3089 return new ProxyInfo(proxyInfo);
3090 }
3091 }
3092
Paul Jensene0bef712014-12-10 15:12:18 -05003093 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
3094 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
3095 // proxy is null then there is no proxy in place).
3096 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
3097 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
3098 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
3099 proxy = null;
3100 }
3101 return proxy;
3102 }
3103
3104 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
3105 // better for determining if a new proxy broadcast is necessary:
3106 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
3107 // avoid unnecessary broadcasts.
3108 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
3109 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
3110 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
3111 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
3112 // all set.
3113 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
3114 a = canonicalizeProxyInfo(a);
3115 b = canonicalizeProxyInfo(b);
3116 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
3117 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
3118 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
3119 }
3120
Jason Monk207900c2014-04-25 15:00:09 -04003121 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003122 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04003123
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003124 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003125 if (proxyProperties == mGlobalProxy) return;
3126 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
3127 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
3128
3129 String host = "";
3130 int port = 0;
3131 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04003132 String pacFileUrl = "";
3133 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003134 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003135 if (!proxyProperties.isValid()) {
3136 if (DBG)
3137 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3138 return;
3139 }
Jason Monk207900c2014-04-25 15:00:09 -04003140 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003141 host = mGlobalProxy.getHost();
3142 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04003143 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003144 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04003145 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04003146 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003147 } else {
3148 mGlobalProxy = null;
3149 }
3150 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003151 final long token = Binder.clearCallingIdentity();
3152 try {
3153 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
3154 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
3155 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
3156 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003157 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07003158 } finally {
3159 Binder.restoreCallingIdentity(token);
3160 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003161
Jason Monkcf0f97a2014-10-02 15:39:38 -04003162 if (mGlobalProxy == null) {
3163 proxyProperties = mDefaultProxy;
3164 }
3165 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003166 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003167 }
3168
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003169 private void loadGlobalProxy() {
3170 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07003171 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
3172 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
3173 String exclList = Settings.Global.getString(res,
3174 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04003175 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
3176 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003177 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04003178 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04003179 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04003180 } else {
Jason Monk207900c2014-04-25 15:00:09 -04003181 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04003182 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08003183 if (!proxyProperties.isValid()) {
3184 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
3185 return;
3186 }
3187
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003188 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08003189 mGlobalProxy = proxyProperties;
3190 }
3191 }
3192 }
3193
Jason Monk207900c2014-04-25 15:00:09 -04003194 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08003195 // this information is already available as a world read/writable jvm property
3196 // so this API change wouldn't have a benifit. It also breaks the passing
3197 // of proxy info to all the JVMs.
3198 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003199 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003200 return mGlobalProxy;
3201 }
3202 }
3203
Jason Monk207900c2014-04-25 15:00:09 -04003204 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04003205 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003206 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003207 proxy = null;
3208 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003209 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07003210 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003211 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08003212 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08003213 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
3214 return;
3215 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04003216
3217 // This call could be coming from the PacManager, containing the port of the local
3218 // proxy. If this new proxy matches the global proxy then copy this proxy to the
3219 // global (to get the correct local port), and send a broadcast.
3220 // TODO: Switch PacManager to have its own message to send back rather than
3221 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05003222 if ((mGlobalProxy != null) && (proxy != null)
3223 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04003224 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
3225 mGlobalProxy = proxy;
3226 sendProxyBroadcast(mGlobalProxy);
3227 return;
3228 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003229 mDefaultProxy = proxy;
3230
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07003231 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07003232 if (!mDefaultProxyDisabled) {
3233 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003234 }
3235 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003236 }
3237
Paul Jensene0bef712014-12-10 15:12:18 -05003238 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
3239 // This method gets called when any network changes proxy, but the broadcast only ever contains
3240 // the default proxy (even if it hasn't changed).
3241 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
3242 // world where an app might be bound to a non-default network.
3243 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3244 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
3245 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
3246
3247 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
3248 sendProxyBroadcast(getDefaultProxy());
3249 }
3250 }
3251
Robert Greenwalt434203a2010-10-11 16:00:27 -07003252 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07003253 String proxy = Settings.Global.getString(mContext.getContentResolver(),
3254 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003255 if (!TextUtils.isEmpty(proxy)) {
3256 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07003257 if (data.length == 0) {
3258 return;
3259 }
3260
Robert Greenwalt434203a2010-10-11 16:00:27 -07003261 String proxyHost = data[0];
3262 int proxyPort = 8080;
3263 if (data.length > 1) {
3264 try {
3265 proxyPort = Integer.parseInt(data[1]);
3266 } catch (NumberFormatException e) {
3267 return;
3268 }
3269 }
Jason Monk207900c2014-04-25 15:00:09 -04003270 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07003271 setGlobalProxy(p);
3272 }
3273 }
3274
Jason Monk207900c2014-04-25 15:00:09 -04003275 private void sendProxyBroadcast(ProxyInfo proxy) {
3276 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04003277 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07003278 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003279 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08003280 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
3281 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003282 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07003283 final long ident = Binder.clearCallingIdentity();
3284 try {
3285 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
3286 } finally {
3287 Binder.restoreCallingIdentity(ident);
3288 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003289 }
3290
3291 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09003292 final private HashMap<Uri, Integer> mUriEventMap;
3293 final private Context mContext;
3294 final private Handler mHandler;
3295
3296 SettingsObserver(Context context, Handler handler) {
3297 super(null);
3298 mUriEventMap = new HashMap<Uri, Integer>();
3299 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003300 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07003301 }
3302
Erik Klineda4bfa82015-04-30 12:58:40 +09003303 void observe(Uri uri, int what) {
3304 mUriEventMap.put(uri, what);
3305 final ContentResolver resolver = mContext.getContentResolver();
3306 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07003307 }
3308
3309 @Override
3310 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09003311 Slog.wtf(TAG, "Should never be reached.");
3312 }
3313
3314 @Override
3315 public void onChange(boolean selfChange, Uri uri) {
3316 final Integer what = mUriEventMap.get(uri);
3317 if (what != null) {
3318 mHandler.obtainMessage(what.intValue()).sendToTarget();
3319 } else {
3320 loge("No matching event to send for URI=" + uri);
3321 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003322 }
3323 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003324
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003325 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003326 Slog.d(TAG, s);
3327 }
3328
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003329 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003330 Slog.e(TAG, s);
3331 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003332
Hugo Benichi938ab4f2017-02-11 17:04:43 +09003333 private static void loge(String s, Throwable t) {
3334 Slog.e(TAG, s, t);
3335 }
3336
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003337 private static <T> T checkNotNull(T value, String message) {
3338 if (value == null) {
3339 throw new NullPointerException(message);
3340 }
3341 return value;
3342 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003343
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003344 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003345 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003346 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3347 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3348 *
3349 * @param oldPackage Package name of the application which currently controls VPN, which will
3350 * be replaced. If there is no such application, this should should either be
3351 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3352 * @param newPackage Package name of the application which should gain control of VPN, or
3353 * {@code null} to disable.
3354 * @param userId User for whom to prepare the new VPN.
3355 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003356 * @hide
3357 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003358 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003359 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3360 int userId) {
3361 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003362 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003363
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003364 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003365 Vpn vpn = mVpns.get(userId);
3366 if (vpn != null) {
3367 return vpn.prepare(oldPackage, newPackage);
3368 } else {
3369 return false;
3370 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003371 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003372 }
3373
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003374 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003375 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3376 * This method is used by system-privileged apps.
3377 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3378 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3379 *
3380 * @param packageName The package for which authorization state should change.
3381 * @param userId User for whom {@code packageName} is installed.
3382 * @param authorized {@code true} if this app should be able to start a VPN connection without
3383 * explicit user approval, {@code false} if not.
3384 *
Jeff Davidson05542602014-08-11 14:07:27 -07003385 * @hide
3386 */
3387 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003388 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3389 enforceCrossUserPermission(userId);
3390
Jeff Davidson05542602014-08-11 14:07:27 -07003391 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003392 Vpn vpn = mVpns.get(userId);
3393 if (vpn != null) {
3394 vpn.setPackageAuthorization(packageName, authorized);
3395 }
Jeff Davidson05542602014-08-11 14:07:27 -07003396 }
3397 }
3398
3399 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003400 * Configure a TUN interface and return its file descriptor. Parameters
3401 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003402 * and not available in ConnectivityManager. Permissions are checked in
3403 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003404 * @hide
3405 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003406 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003407 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003408 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003409 int user = UserHandle.getUserId(Binder.getCallingUid());
3410 synchronized(mVpns) {
3411 return mVpns.get(user).establish(config);
3412 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003413 }
3414
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003415 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003416 * Start legacy VPN, controlling native daemons as needed. Creates a
3417 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003418 */
3419 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003420 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003421 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003422 final LinkProperties egress = getActiveLinkProperties();
3423 if (egress == null) {
3424 throw new IllegalStateException("Missing active network connection");
3425 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003426 int user = UserHandle.getUserId(Binder.getCallingUid());
3427 synchronized(mVpns) {
3428 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3429 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003430 }
3431
3432 /**
3433 * Return the information of the ongoing legacy VPN. This method is used
3434 * by VpnSettings and not available in ConnectivityManager. Permissions
3435 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003436 */
3437 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003438 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3439 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003440
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003441 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003442 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003443 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003444 }
3445
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003446 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003447 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3448 * and not available in ConnectivityManager.
3449 */
3450 @Override
3451 public VpnInfo[] getAllVpnInfo() {
3452 enforceConnectivityInternalPermission();
3453 if (mLockdownEnabled) {
3454 return new VpnInfo[0];
3455 }
3456
3457 synchronized(mVpns) {
3458 List<VpnInfo> infoList = new ArrayList<>();
3459 for (int i = 0; i < mVpns.size(); i++) {
3460 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3461 if (info != null) {
3462 infoList.add(info);
3463 }
3464 }
3465 return infoList.toArray(new VpnInfo[infoList.size()]);
3466 }
3467 }
3468
3469 /**
3470 * @return VPN information for accounting, or null if we can't retrieve all required
3471 * information, e.g primary underlying iface.
3472 */
3473 @Nullable
3474 private VpnInfo createVpnInfo(Vpn vpn) {
3475 VpnInfo info = vpn.getVpnInfo();
3476 if (info == null) {
3477 return null;
3478 }
3479 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3480 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3481 // the underlyingNetworks list.
3482 if (underlyingNetworks == null) {
3483 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3484 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3485 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3486 }
3487 } else if (underlyingNetworks.length > 0) {
3488 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3489 if (linkProperties != null) {
3490 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3491 }
3492 }
3493 return info.primaryUnderlyingIface == null ? null : info;
3494 }
3495
3496 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003497 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3498 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003499 * Permissions are checked in Vpn class.
3500 * @hide
3501 */
3502 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003503 public VpnConfig getVpnConfig(int userId) {
3504 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003505 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003506 Vpn vpn = mVpns.get(userId);
3507 if (vpn != null) {
3508 return vpn.getVpnConfig();
3509 } else {
3510 return null;
3511 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003512 }
3513 }
3514
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003515 @Override
3516 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003517 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3518 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3519 return false;
3520 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003521
3522 // Tear down existing lockdown if profile was removed
3523 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3524 if (mLockdownEnabled) {
sj.cha2f73d552017-01-19 08:48:47 +09003525 byte[] profileTag = mKeyStore.get(Credentials.LOCKDOWN_VPN);
3526 if (profileTag == null) {
3527 Slog.e(TAG, "Lockdown VPN configured but cannot be read from keystore");
3528 return false;
3529 }
3530 String profileName = new String(profileTag);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003531 final VpnProfile profile = VpnProfile.decode(
3532 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003533 if (profile == null) {
3534 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3535 setLockdownTracker(null);
3536 return true;
3537 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003538 int user = UserHandle.getUserId(Binder.getCallingUid());
3539 synchronized(mVpns) {
Robin Lee18566c12016-03-14 13:08:48 +00003540 Vpn vpn = mVpns.get(user);
3541 if (vpn == null) {
3542 Slog.w(TAG, "VPN for user " + user + " not ready yet. Skipping lockdown");
3543 return false;
3544 }
3545 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, vpn, profile));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003546 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003547 } else {
3548 setLockdownTracker(null);
3549 }
3550
3551 return true;
3552 }
3553
3554 /**
3555 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3556 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3557 */
3558 private void setLockdownTracker(LockdownVpnTracker tracker) {
3559 // Shutdown any existing tracker
3560 final LockdownVpnTracker existing = mLockdownTracker;
3561 mLockdownTracker = null;
3562 if (existing != null) {
3563 existing.shutdown();
3564 }
3565
3566 try {
3567 if (tracker != null) {
3568 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003569 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003570 mLockdownTracker = tracker;
3571 mLockdownTracker.init();
3572 } else {
3573 mNetd.setFirewallEnabled(false);
3574 }
3575 } catch (RemoteException e) {
3576 // ignored; NMS lives inside system_server
3577 }
3578 }
3579
3580 private void throwIfLockdownEnabled() {
3581 if (mLockdownEnabled) {
3582 throw new IllegalStateException("Unavailable in lockdown mode");
3583 }
3584 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003585
Robin Lee244ce8e2016-01-05 18:03:46 +00003586 /**
Robin Lee17e61832016-05-09 13:46:28 +01003587 * Starts the always-on VPN {@link VpnService} for user {@param userId}, which should perform
3588 * some setup and then call {@code establish()} to connect.
Robin Lee244ce8e2016-01-05 18:03:46 +00003589 *
Robin Lee17e61832016-05-09 13:46:28 +01003590 * @return {@code true} if the service was started, the service was already connected, or there
3591 * was no always-on VPN to start. {@code false} otherwise.
Robin Lee244ce8e2016-01-05 18:03:46 +00003592 */
Robin Lee17e61832016-05-09 13:46:28 +01003593 private boolean startAlwaysOnVpn(int userId) {
Robin Lee17e61832016-05-09 13:46:28 +01003594 synchronized (mVpns) {
3595 Vpn vpn = mVpns.get(userId);
3596 if (vpn == null) {
3597 // Shouldn't happen as all codepaths that point here should have checked the Vpn
3598 // exists already.
3599 Slog.wtf(TAG, "User " + userId + " has no Vpn configuration");
3600 return false;
3601 }
Robin Lee244ce8e2016-01-05 18:03:46 +00003602
Robin Lee812800c2016-05-13 15:38:08 +01003603 return vpn.startAlwaysOnVpn();
Robin Lee244ce8e2016-01-05 18:03:46 +00003604 }
3605 }
3606
3607 @Override
Robin Leedc679712016-05-03 13:23:03 +01003608 public boolean setAlwaysOnVpnPackage(int userId, String packageName, boolean lockdown) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003609 enforceConnectivityInternalPermission();
3610 enforceCrossUserPermission(userId);
3611
3612 // Can't set always-on VPN if legacy VPN is already in lockdown mode.
3613 if (LockdownVpnTracker.isEnabled()) {
3614 return false;
3615 }
3616
Robin Lee244ce8e2016-01-05 18:03:46 +00003617 synchronized (mVpns) {
3618 Vpn vpn = mVpns.get(userId);
3619 if (vpn == null) {
3620 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3621 return false;
3622 }
Robin Lee17e61832016-05-09 13:46:28 +01003623 if (!vpn.setAlwaysOnPackage(packageName, lockdown)) {
Robin Lee244ce8e2016-01-05 18:03:46 +00003624 return false;
3625 }
Robin Lee17e61832016-05-09 13:46:28 +01003626 if (!startAlwaysOnVpn(userId)) {
3627 vpn.setAlwaysOnPackage(null, false);
Robin Lee244ce8e2016-01-05 18:03:46 +00003628 return false;
3629 }
Robin Lee17e61832016-05-09 13:46:28 +01003630
Robin Lee812800c2016-05-13 15:38:08 +01003631 vpn.saveAlwaysOnPackage();
Robin Lee244ce8e2016-01-05 18:03:46 +00003632 }
3633 return true;
3634 }
3635
3636 @Override
3637 public String getAlwaysOnVpnPackage(int userId) {
3638 enforceConnectivityInternalPermission();
3639 enforceCrossUserPermission(userId);
3640
3641 synchronized (mVpns) {
3642 Vpn vpn = mVpns.get(userId);
3643 if (vpn == null) {
3644 Slog.w(TAG, "User " + userId + " has no Vpn configuration");
3645 return null;
3646 }
3647 return vpn.getAlwaysOnPackage();
3648 }
3649 }
3650
Wink Savilleab9321d2013-06-29 21:10:57 -07003651 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003652 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003653 // TODO: Remove? Any reason to trigger a provisioning check?
3654 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003655 }
3656
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003657 /** Location to an updatable file listing carrier provisioning urls.
3658 * An example:
3659 *
3660 * <?xml version="1.0" encoding="utf-8"?>
3661 * <provisioningUrls>
3662 * <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 -07003663 * </provisioningUrls>
3664 */
3665 private static final String PROVISIONING_URL_PATH =
3666 "/data/misc/radio/provisioning_urls.xml";
3667 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003668
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003669 /** XML tag for root element. */
3670 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3671 /** XML tag for individual url */
3672 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003673 /** XML attribute for mcc */
3674 private static final String ATTR_MCC = "mcc";
3675 /** XML attribute for mnc */
3676 private static final String ATTR_MNC = "mnc";
3677
Paul Jensen434dde82015-06-11 09:43:30 -04003678 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003679 FileReader fileReader = null;
3680 XmlPullParser parser = null;
3681 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003682
3683 try {
3684 fileReader = new FileReader(mProvisioningUrlFile);
3685 parser = Xml.newPullParser();
3686 parser.setInput(fileReader);
3687 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3688
3689 while (true) {
3690 XmlUtils.nextElement(parser);
3691
3692 String element = parser.getName();
3693 if (element == null) break;
3694
Paul Jensen434dde82015-06-11 09:43:30 -04003695 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003696 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3697 try {
3698 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3699 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3700 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3701 parser.next();
3702 if (parser.getEventType() == XmlPullParser.TEXT) {
3703 return parser.getText();
3704 }
3705 }
3706 }
3707 } catch (NumberFormatException e) {
3708 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3709 }
3710 }
3711 }
3712 return null;
3713 } catch (FileNotFoundException e) {
3714 loge("Carrier Provisioning Urls file not found");
3715 } catch (XmlPullParserException e) {
3716 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3717 } catch (IOException e) {
3718 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3719 } finally {
3720 if (fileReader != null) {
3721 try {
3722 fileReader.close();
3723 } catch (IOException e) {}
3724 }
3725 }
3726 return null;
3727 }
3728
Wink Saville42d4f082013-07-20 20:31:59 -07003729 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003730 public String getMobileProvisioningUrl() {
3731 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003732 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003733 if (TextUtils.isEmpty(url)) {
3734 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003735 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003736 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003737 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003738 }
Wink Saville8cf35602013-07-10 23:00:07 -07003739 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003740 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003741 String phoneNumber = mTelephonyManager.getLine1Number();
3742 if (TextUtils.isEmpty(phoneNumber)) {
3743 phoneNumber = "0000000000";
3744 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003745 url = String.format(url,
3746 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3747 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003748 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003749 }
3750
Wink Savilleab9321d2013-06-29 21:10:57 -07003751 return url;
3752 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003753
Wink Saville948282b2013-08-29 08:55:16 -07003754 @Override
3755 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003756 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003757 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003758 final long ident = Binder.clearCallingIdentity();
3759 try {
Lorenzo Colitti0b599062016-08-22 22:36:19 +09003760 // Concatenate the range of types onto the range of NetIDs.
3761 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
3762 mNotifier.setProvNotificationVisible(visible, id, action);
Paul Jensen89e0f092014-09-15 15:59:36 -04003763 } finally {
3764 Binder.restoreCallingIdentity(ident);
3765 }
Wink Saville948282b2013-08-29 08:55:16 -07003766 }
Wink Saville7788c612013-08-29 14:57:08 -07003767
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003768 @Override
3769 public void setAirplaneMode(boolean enable) {
3770 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003771 final long ident = Binder.clearCallingIdentity();
3772 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003773 final ContentResolver cr = mContext.getContentResolver();
3774 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3775 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3776 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003777 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003778 } finally {
3779 Binder.restoreCallingIdentity(ident);
3780 }
3781 }
3782
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003783 private void onUserStart(int userId) {
3784 synchronized(mVpns) {
3785 Vpn userVpn = mVpns.get(userId);
3786 if (userVpn != null) {
3787 loge("Starting user already has a VPN");
3788 return;
3789 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003790 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003791 mVpns.put(userId, userVpn);
Robin Lee17e61832016-05-09 13:46:28 +01003792
3793 final ContentResolver cr = mContext.getContentResolver();
3794 String alwaysOnPackage = Settings.Secure.getStringForUser(cr,
3795 Settings.Secure.ALWAYS_ON_VPN_APP, userId);
3796 final boolean alwaysOnLockdown = Settings.Secure.getIntForUser(cr,
3797 Settings.Secure.ALWAYS_ON_VPN_LOCKDOWN, /* default */ 0, userId) != 0;
3798 if (alwaysOnPackage != null) {
3799 userVpn.setAlwaysOnPackage(alwaysOnPackage, alwaysOnLockdown);
3800 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003801 }
Robin Lee9a5f4852015-12-17 11:42:22 +00003802 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3803 updateLockdownVpn();
Robin Lee9a5f4852015-12-17 11:42:22 +00003804 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003805 }
3806
3807 private void onUserStop(int userId) {
3808 synchronized(mVpns) {
3809 Vpn userVpn = mVpns.get(userId);
3810 if (userVpn == null) {
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003811 loge("Stopped user has no VPN");
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003812 return;
3813 }
Robin Lee17e61832016-05-09 13:46:28 +01003814 userVpn.onUserStopped();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003815 mVpns.delete(userId);
3816 }
3817 }
3818
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003819 private void onUserAdded(int userId) {
3820 synchronized(mVpns) {
3821 final int vpnsSize = mVpns.size();
3822 for (int i = 0; i < vpnsSize; i++) {
3823 Vpn vpn = mVpns.valueAt(i);
3824 vpn.onUserAdded(userId);
3825 }
3826 }
3827 }
3828
3829 private void onUserRemoved(int userId) {
3830 synchronized(mVpns) {
3831 final int vpnsSize = mVpns.size();
3832 for (int i = 0; i < vpnsSize; i++) {
3833 Vpn vpn = mVpns.valueAt(i);
3834 vpn.onUserRemoved(userId);
3835 }
3836 }
3837 }
3838
Robin Lee89e7a692016-02-29 14:38:17 +00003839 private void onUserUnlocked(int userId) {
Robin Lee9a5f4852015-12-17 11:42:22 +00003840 // User present may be sent because of an unlock, which might mean an unlocked keystore.
3841 if (mUserManager.getUserInfo(userId).isPrimary() && LockdownVpnTracker.isEnabled()) {
3842 updateLockdownVpn();
3843 } else {
Robin Lee17e61832016-05-09 13:46:28 +01003844 startAlwaysOnVpn(userId);
Robin Lee9a5f4852015-12-17 11:42:22 +00003845 }
3846 }
3847
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003848 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3849 @Override
3850 public void onReceive(Context context, Intent intent) {
3851 final String action = intent.getAction();
3852 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3853 if (userId == UserHandle.USER_NULL) return;
3854
Robin Lee323f29d2016-05-04 16:38:06 +01003855 if (Intent.ACTION_USER_STARTED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003856 onUserStart(userId);
Amith Yamasaniad2e4bf2016-04-26 14:35:54 -07003857 } else if (Intent.ACTION_USER_STOPPED.equals(action)) {
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003858 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003859 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3860 onUserAdded(userId);
3861 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3862 onUserRemoved(userId);
Robin Lee89e7a692016-02-29 14:38:17 +00003863 } else if (Intent.ACTION_USER_UNLOCKED.equals(action)) {
3864 onUserUnlocked(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003865 }
3866 }
3867 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003868
Robin Lee95204e02017-01-27 11:59:22 +00003869 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
3870 @Override
3871 public void onReceive(Context context, Intent intent) {
3872 // Try creating lockdown tracker, since user present usually means
3873 // unlocked keystore.
3874 updateLockdownVpn();
3875 mContext.unregisterReceiver(this);
3876 }
3877 };
3878
Robert Greenwalta67be032014-05-16 15:49:14 -07003879 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3880 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003881 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3882 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003883
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003884 private static final int MAX_NETWORK_REQUESTS_PER_UID = 100;
3885 // Map from UID to number of NetworkRequests that UID has filed.
3886 @GuardedBy("mUidToNetworkRequestCount")
3887 private final SparseIntArray mUidToNetworkRequestCount = new SparseIntArray();
3888
Robert Greenwalta67be032014-05-16 15:49:14 -07003889 private static class NetworkFactoryInfo {
3890 public final String name;
3891 public final Messenger messenger;
3892 public final AsyncChannel asyncChannel;
3893
3894 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3895 this.name = name;
3896 this.messenger = messenger;
3897 this.asyncChannel = asyncChannel;
3898 }
3899 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003900
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003901 private void ensureNetworkRequestHasType(NetworkRequest request) {
3902 if (request.type == NetworkRequest.Type.NONE) {
3903 throw new IllegalArgumentException(
3904 "All NetworkRequests in ConnectivityService must have a type");
3905 }
3906 }
3907
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003908 /**
3909 * Tracks info about the requester.
3910 * Also used to notice when the calling process dies so we can self-expire
3911 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003912 private class NetworkRequestInfo implements IBinder.DeathRecipient {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003913 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003914 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003915 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003916 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003917 final int mPid;
3918 final int mUid;
3919 final Messenger messenger;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003920
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003921 NetworkRequestInfo(NetworkRequest r, PendingIntent pi) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003922 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003923 ensureNetworkRequestHasType(request);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003924 mPendingIntent = pi;
3925 messenger = null;
3926 mBinder = null;
3927 mPid = getCallingPid();
3928 mUid = getCallingUid();
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003929 enforceRequestCountLimit();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003930 }
3931
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003932 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003933 super();
3934 messenger = m;
3935 request = r;
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09003936 ensureNetworkRequestHasType(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003937 mBinder = binder;
3938 mPid = getCallingPid();
3939 mUid = getCallingUid();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003940 mPendingIntent = null;
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003941 enforceRequestCountLimit();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003942
3943 try {
3944 mBinder.linkToDeath(this, 0);
3945 } catch (RemoteException e) {
3946 binderDied();
3947 }
3948 }
3949
Paul Jensen4e1d3fd2016-04-08 13:56:52 -04003950 private void enforceRequestCountLimit() {
3951 synchronized (mUidToNetworkRequestCount) {
3952 int networkRequests = mUidToNetworkRequestCount.get(mUid, 0) + 1;
3953 if (networkRequests >= MAX_NETWORK_REQUESTS_PER_UID) {
3954 throw new IllegalArgumentException("Too many NetworkRequests filed");
3955 }
3956 mUidToNetworkRequestCount.put(mUid, networkRequests);
3957 }
3958 }
3959
Robert Greenwalt9258c642014-03-26 16:47:06 -07003960 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003961 if (mBinder != null) {
3962 mBinder.unlinkToDeath(this, 0);
3963 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003964 }
3965
3966 public void binderDied() {
3967 log("ConnectivityService NetworkRequestInfo binderDied(" +
3968 request + ", " + mBinder + ")");
3969 releaseNetworkRequest(request);
3970 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003971
3972 public String toString() {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09003973 return "uid/pid:" + mUid + "/" + mPid + " " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003974 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003975 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003976 }
3977
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003978 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3979 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3980 if (badCapability != null) {
3981 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003982 }
3983 }
3984
Erik Kline9d598e12015-07-13 16:37:51 +09003985 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003986 final SortedSet<Integer> thresholds = new TreeSet();
3987 synchronized (nai) {
3988 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3989 if (nri.request.networkCapabilities.hasSignalStrength() &&
3990 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3991 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3992 }
3993 }
3994 }
Erik Kline9d598e12015-07-13 16:37:51 +09003995 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003996 }
3997
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003998 private void updateSignalStrengthThresholds(
3999 NetworkAgentInfo nai, String reason, NetworkRequest request) {
4000 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09004001 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004002 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
4003
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004004 if (VDBG || (DBG && !"CONNECT".equals(reason))) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004005 String detail;
4006 if (request != null && request.networkCapabilities.hasSignalStrength()) {
4007 detail = reason + " " + request.networkCapabilities.getSignalStrength();
4008 } else {
4009 detail = reason;
4010 }
4011 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
4012 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
4013 }
4014
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004015 nai.asyncChannel.sendMessage(
4016 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09004017 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004018 }
4019
Robert Greenwalt9258c642014-03-26 16:47:06 -07004020 @Override
4021 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004022 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004023 final NetworkRequest.Type type = (networkCapabilities == null)
4024 ? NetworkRequest.Type.TRACK_DEFAULT
4025 : NetworkRequest.Type.REQUEST;
Erik Klinea2d29402016-03-16 15:31:39 +09004026 // If the requested networkCapabilities is null, take them instead from
4027 // the default network request. This allows callers to keep track of
4028 // the system default network.
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004029 if (type == NetworkRequest.Type.TRACK_DEFAULT) {
Erik Klinea2d29402016-03-16 15:31:39 +09004030 networkCapabilities = new NetworkCapabilities(mDefaultRequest.networkCapabilities);
4031 enforceAccessPermission();
4032 } else {
4033 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4034 enforceNetworkRequestPermissions(networkCapabilities);
Lorenzo Colittib60570c2016-07-01 13:20:10 +09004035 // TODO: this is incorrect. We mark the request as metered or not depending on the state
4036 // of the app when the request is filed, but we never change the request if the app
4037 // changes network state. http://b/29964605
4038 enforceMeteredApnPolicy(networkCapabilities);
Erik Klinea2d29402016-03-16 15:31:39 +09004039 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004040 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004041
Etan Cohenba07c8c2017-02-05 10:42:27 -08004042 if (timeoutMs < 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004043 throw new IllegalArgumentException("Bad timeout specified");
4044 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004045
Etan Cohenddb9ef02015-11-18 10:56:15 -08004046 if (NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER
4047 .equals(networkCapabilities.getNetworkSpecifier())) {
4048 throw new IllegalArgumentException("Invalid network specifier - must not be '"
4049 + NetworkCapabilities.MATCH_ALL_REQUESTS_NETWORK_SPECIFIER + "'");
4050 }
4051
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07004052 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004053 nextNetworkRequestId(), type);
4054 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Erik Kline7523eb32015-07-09 18:24:03 +09004055 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004056
4057 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07004058 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004059 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07004060 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061 }
4062 return networkRequest;
4063 }
4064
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004065 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004066 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Hugo Benichi514da602016-07-19 15:59:27 +09004067 enforceConnectivityRestrictedNetworksPermission();
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004068 } else {
4069 enforceChangePermission();
4070 }
4071 }
4072
fenglub15e72b2015-03-20 11:29:56 -07004073 @Override
fengludb571472015-04-21 17:12:05 -07004074 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07004075 enforceAccessPermission();
4076 NetworkAgentInfo nai = null;
4077 if (network == null) {
4078 return false;
4079 }
4080 synchronized (mNetworkForNetId) {
4081 nai = mNetworkForNetId.get(network.netId);
4082 }
4083 if (nai != null) {
4084 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
4085 return true;
4086 }
4087 return false;
4088 }
4089
Felipe Lemeee27cab2016-06-20 16:36:29 -07004090 private boolean isSystem(int uid) {
4091 return uid < Process.FIRST_APPLICATION_UID;
4092 }
fenglub15e72b2015-03-20 11:29:56 -07004093
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004094 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
Felipe Lemeee27cab2016-06-20 16:36:29 -07004095 final int uid = Binder.getCallingUid();
4096 if (isSystem(uid)) {
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004097 // Exemption for system uid.
Felipe Lemeee27cab2016-06-20 16:36:29 -07004098 return;
4099 }
Hugo Benichi938ab4f2017-02-11 17:04:43 +09004100 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED)) {
4101 // Policy already enforced.
4102 return;
4103 }
4104 if (mPolicyManagerInternal.isUidRestrictedOnMeteredNetworks(uid)) {
4105 // If UID is restricted, don't allow them to bring up metered APNs.
4106 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004107 }
4108 }
4109
Robert Greenwalt9258c642014-03-26 16:47:06 -07004110 @Override
4111 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
4112 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004113 checkNotNull(operation, "PendingIntent cannot be null.");
4114 networkCapabilities = new NetworkCapabilities(networkCapabilities);
4115 enforceNetworkRequestPermissions(networkCapabilities);
4116 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09004117 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004118
4119 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004120 nextNetworkRequestId(), NetworkRequest.Type.REQUEST);
4121 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Erik Kline7523eb32015-07-09 18:24:03 +09004122 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004123 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
4124 nri));
4125 return networkRequest;
4126 }
4127
Jeremy Joslin79294842014-12-03 17:15:28 -08004128 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
4129 mHandler.sendMessageDelayed(
4130 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4131 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
4132 }
4133
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004134 @Override
4135 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04004136 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004137 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
4138 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004139 }
4140
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004141 // In order to implement the compatibility measure for pre-M apps that call
4142 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
4143 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
4144 // This ensures it has permission to do so.
4145 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
4146 if (nc == null) {
4147 return false;
4148 }
4149 int[] transportTypes = nc.getTransportTypes();
4150 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
4151 return false;
4152 }
4153 try {
4154 mContext.enforceCallingOrSelfPermission(
4155 android.Manifest.permission.ACCESS_WIFI_STATE,
4156 "ConnectivityService");
4157 } catch (SecurityException e) {
4158 return false;
4159 }
4160 return true;
4161 }
4162
Robert Greenwalt9258c642014-03-26 16:47:06 -07004163 @Override
4164 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
4165 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09004166 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4167 enforceAccessPermission();
4168 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004169
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004170 NetworkCapabilities nc = new NetworkCapabilities(networkCapabilities);
4171 if (!ConnectivityManager.checkChangePermission(mContext)) {
4172 // Apps without the CHANGE_NETWORK_STATE permission can't use background networks, so
4173 // make all their listens include NET_CAPABILITY_FOREGROUND. That way, they will get
4174 // onLost and onAvailable callbacks when networks move in and out of the background.
4175 // There is no need to do this for requests because an app without CHANGE_NETWORK_STATE
4176 // can't request networks.
4177 nc.addCapability(NET_CAPABILITY_FOREGROUND);
4178 }
4179
4180 NetworkRequest networkRequest = new NetworkRequest(nc, TYPE_NONE, nextNetworkRequestId(),
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004181 NetworkRequest.Type.LISTEN);
4182 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004183 if (VDBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004184
4185 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
4186 return networkRequest;
4187 }
4188
4189 @Override
4190 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
4191 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04004192 checkNotNull(operation, "PendingIntent cannot be null.");
4193 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
4194 enforceAccessPermission();
4195 }
4196
Erik Kline7523eb32015-07-09 18:24:03 +09004197 NetworkRequest networkRequest = new NetworkRequest(
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004198 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId(),
4199 NetworkRequest.Type.LISTEN);
4200 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation);
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004201 if (VDBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04004202
4203 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004204 }
4205
Erik Klineacdd6392016-07-07 16:50:58 +09004206 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07004207 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Lorenzo Colitti1ec11eb2016-07-05 01:22:13 +09004208 ensureNetworkRequestHasType(networkRequest);
Erik Klineacdd6392016-07-07 16:50:58 +09004209 mHandler.sendMessage(mHandler.obtainMessage(
4210 EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(), 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004211 }
4212
4213 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07004214 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07004215 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07004216 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
4217 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07004218 }
4219
Robert Greenwalta67be032014-05-16 15:49:14 -07004220 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004221 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07004222 mNetworkFactoryInfos.put(nfi.messenger, nfi);
4223 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
4224 }
4225
4226 @Override
4227 public void unregisterNetworkFactory(Messenger messenger) {
4228 enforceConnectivityInternalPermission();
4229 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
4230 }
4231
4232 private void handleUnregisterNetworkFactory(Messenger messenger) {
4233 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
4234 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004235 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07004236 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07004237 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004238 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07004239 }
4240
Robert Greenwalt7b816022014-04-18 15:25:25 -07004241 /**
4242 * NetworkAgentInfo supporting a request by requestId.
4243 * These have already been vetted (their Capabilities satisfy the request)
4244 * and the are the highest scored network available.
4245 * the are keyed off the Requests requestId.
4246 */
Paul Jensen31a94f42015-02-13 14:18:39 -05004247 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004248 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
4249 new SparseArray<NetworkAgentInfo>();
4250
Paul Jensen31a94f42015-02-13 14:18:39 -05004251 // NOTE: Accessed on multiple threads, must be synchronized on itself.
4252 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07004253 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
4254 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05004255 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
4256 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
4257 // there may not be a strict 1:1 correlation between the two.
4258 @GuardedBy("mNetworkForNetId")
4259 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004260
Robert Greenwalt7b816022014-04-18 15:25:25 -07004261 // NetworkAgentInfo keyed off its connecting messenger
4262 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05004263 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07004264 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
4265 new HashMap<Messenger, NetworkAgentInfo>();
4266
Lorenzo Colittic1a6ce72016-01-22 04:04:57 +09004267 @GuardedBy("mBlockedAppUids")
4268 private final HashSet<Integer> mBlockedAppUids = new HashSet();
4269
Paul Jensen2c311d62014-11-17 12:34:51 -05004270 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004271 private final NetworkRequest mDefaultRequest;
4272
Erik Klineda4bfa82015-04-30 12:58:40 +09004273 // Request used to optionally keep mobile data active even when higher
4274 // priority networks like Wi-Fi are active.
4275 private final NetworkRequest mDefaultMobileDataRequest;
4276
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004277 private NetworkAgentInfo getDefaultNetwork() {
4278 return mNetworkForRequestId.get(mDefaultRequest.requestId);
4279 }
4280
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004281 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09004282 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07004283 }
4284
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004285 private boolean isDefaultRequest(NetworkRequestInfo nri) {
4286 return nri.request.requestId == mDefaultRequest.requestId;
4287 }
4288
Paul Jensen31a94f42015-02-13 14:18:39 -05004289 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004290 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004291 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004292 enforceConnectivityInternalPermission();
4293
Paul Jensen2c311d62014-11-17 12:34:51 -05004294 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
4295 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04004296 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05004297 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
4298 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04004299 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07004300 synchronized (this) {
4301 nai.networkMonitor.systemReady = mSystemReady;
4302 }
Paul Jensen0808eb82016-06-03 13:51:21 -04004303 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network,
4304 networkInfo.getExtraInfo());
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004305 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004306 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05004307 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004308 }
4309
4310 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
4311 if (VDBG) log("Got NetworkAgent Messenger");
4312 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05004313 synchronized (mNetworkForNetId) {
4314 mNetworkForNetId.put(na.network.netId, na);
4315 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004316 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
4317 NetworkInfo networkInfo = na.networkInfo;
4318 na.networkInfo = null;
4319 updateNetworkInfo(na, networkInfo);
4320 }
4321
4322 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
4323 LinkProperties newLp = networkAgent.linkProperties;
4324 int netId = networkAgent.network.netId;
4325
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004326 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
4327 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09004328 if (networkAgent.clatd != null) {
4329 networkAgent.clatd.fixupLinkProperties(oldLp);
4330 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004331
Paul Jensen992f2522014-04-28 10:33:11 -04004332 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004333 updateMtu(newLp, oldLp);
4334 // TODO - figure out what to do for clat
4335// for (LinkProperties lp : newLp.getStackedLinks()) {
4336// updateMtu(lp, null);
4337// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004338 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004339
Erik Kline94887872016-04-05 13:30:49 +09004340 updateRoutes(newLp, oldLp, netId);
4341 updateDnses(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004342
Paul Jensen3b759822014-05-13 11:44:01 -04004343 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05004344 if (isDefaultNetwork(networkAgent)) {
4345 handleApplyDefaultProxy(newLp.getHttpProxy());
4346 } else {
4347 updateProxy(newLp, oldLp, networkAgent);
4348 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004349 // TODO - move this check to cover the whole function
4350 if (!Objects.equals(newLp, oldLp)) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08004351 notifyIfacesChangedForNetworkStats();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004352 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
4353 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004354
4355 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04004356 }
4357
Lorenzo Colitti95439462014-10-09 13:44:48 +09004358 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
4359 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4360 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004361
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004362 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004363 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4364 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004365 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004366 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004367 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004368 }
Paul Jensen992f2522014-04-28 10:33:11 -04004369
4370 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4371 CompareResult<String> interfaceDiff = new CompareResult<String>();
4372 if (oldLp != null) {
4373 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4374 } else if (newLp != null) {
4375 interfaceDiff.added = newLp.getAllInterfaceNames();
4376 }
4377 for (String iface : interfaceDiff.added) {
4378 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004379 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004380 mNetd.addInterfaceToNetwork(iface, netId);
4381 } catch (Exception e) {
4382 loge("Exception adding interface: " + e);
4383 }
4384 }
4385 for (String iface : interfaceDiff.removed) {
4386 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004387 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004388 mNetd.removeInterfaceFromNetwork(iface, netId);
4389 } catch (Exception e) {
4390 loge("Exception removing interface: " + e);
4391 }
4392 }
4393 }
4394
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004395 /**
4396 * Have netd update routes from oldLp to newLp.
4397 * @return true if routes changed between oldLp and newLp
4398 */
4399 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004400 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4401 if (oldLp != null) {
4402 routeDiff = oldLp.compareAllRoutes(newLp);
4403 } else if (newLp != null) {
4404 routeDiff.added = newLp.getAllRoutes();
4405 }
4406
4407 // add routes before removing old in case it helps with continuous connectivity
4408
4409 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4410 for (RouteInfo route : routeDiff.added) {
4411 if (route.hasGateway()) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004412 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004413 try {
4414 mNetd.addRoute(netId, route);
4415 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004416 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4417 loge("Exception in addRoute for non-gateway: " + e);
4418 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004419 }
4420 }
4421 for (RouteInfo route : routeDiff.added) {
4422 if (route.hasGateway() == false) continue;
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004423 if (VDBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004424 try {
4425 mNetd.addRoute(netId, route);
4426 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004427 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4428 loge("Exception in addRoute for gateway: " + e);
4429 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004430 }
4431 }
4432
4433 for (RouteInfo route : routeDiff.removed) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004434 if (VDBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004435 try {
4436 mNetd.removeRoute(netId, route);
4437 } catch (Exception e) {
4438 loge("Exception in removeRoute: " + e);
4439 }
4440 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004441 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004442 }
Erik Kline41368502015-06-17 13:19:54 +09004443
Erik Kline94887872016-04-05 13:30:49 +09004444 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId) {
4445 if (oldLp != null && newLp.isIdenticalDnses(oldLp)) {
4446 return; // no updating necessary
Robert Greenwalt7b816022014-04-18 15:25:25 -07004447 }
Erik Kline94887872016-04-05 13:30:49 +09004448
4449 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004450 if (DBG) log("Setting DNS servers for network " + netId + " to " + dnses);
Erik Kline94887872016-04-05 13:30:49 +09004451 try {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004452 mNetd.setDnsConfigurationForNetwork(
Erik Kline94887872016-04-05 13:30:49 +09004453 netId, NetworkUtils.makeStrings(dnses), newLp.getDomains());
4454 } catch (Exception e) {
Pierre Imaibd8759b2016-04-28 17:00:04 +09004455 loge("Exception in setDnsConfigurationForNetwork: " + e);
Erik Kline94887872016-04-05 13:30:49 +09004456 }
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004457 final NetworkAgentInfo defaultNai = getDefaultNetwork();
4458 if (defaultNai != null && defaultNai.network.netId == netId) {
4459 setDefaultDnsSystemProperties(dnses);
4460 }
Erik Kline94887872016-04-05 13:30:49 +09004461 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004462 }
4463
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004464 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4465 int last = 0;
4466 for (InetAddress dns : dnses) {
4467 ++last;
4468 String key = "net.dns" + last;
4469 String value = dns.getHostAddress();
4470 SystemProperties.set(key, value);
4471 }
4472 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4473 String key = "net.dns" + i;
4474 SystemProperties.set(key, "");
4475 }
4476 mNumDnsEntries = last;
4477 }
4478
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004479 private String getNetworkPermission(NetworkCapabilities nc) {
4480 // TODO: make these permission strings AIDL constants instead.
4481 if (!nc.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4482 return NetworkManagementService.PERMISSION_SYSTEM;
4483 }
4484 if (!nc.hasCapability(NET_CAPABILITY_FOREGROUND)) {
4485 return NetworkManagementService.PERMISSION_NETWORK;
4486 }
4487 return null;
4488 }
4489
Paul Jensen3d194ea2015-06-16 14:27:36 -04004490 /**
4491 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4492 * augmented with any stateful capabilities implied from {@code networkAgent}
4493 * (e.g., validated status and captive portal status).
4494 *
Hugo Benichif15b2822016-09-15 18:18:48 +09004495 * @param oldScore score of the network before any of the changes that prompted us
4496 * to call this function.
Paul Jensene0988542015-06-25 15:30:08 -04004497 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004498 * @param networkCapabilities the new network capabilities.
4499 */
Hugo Benichif15b2822016-09-15 18:18:48 +09004500 private void updateCapabilities(
4501 int oldScore, NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004502 if (nai.everConnected && !nai.networkCapabilities.equalImmutableCapabilities(
4503 networkCapabilities)) {
4504 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
4505 + nai.networkCapabilities + " -> " + networkCapabilities);
4506 }
4507
Paul Jensen3d194ea2015-06-16 14:27:36 -04004508 // Don't modify caller's NetworkCapabilities.
4509 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004510 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004511 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4512 } else {
4513 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4514 }
Paul Jensene0988542015-06-25 15:30:08 -04004515 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004516 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4517 } else {
4518 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4519 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004520 if (nai.isBackgroundNetwork()) {
4521 networkCapabilities.removeCapability(NET_CAPABILITY_FOREGROUND);
4522 } else {
4523 networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
4524 }
4525
4526 if (Objects.equals(nai.networkCapabilities, networkCapabilities)) return;
4527
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004528 final String oldPermission = getNetworkPermission(nai.networkCapabilities);
4529 final String newPermission = getNetworkPermission(networkCapabilities);
4530 if (!Objects.equals(oldPermission, newPermission) && nai.created && !nai.isVPN()) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004531 try {
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09004532 mNetd.setNetworkPermission(nai.network.netId, newPermission);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004533 } catch (RemoteException e) {
4534 loge("Exception in setNetworkPermission: " + e);
Paul Jensen487ffe72015-07-24 15:57:11 -04004535 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004536 }
4537
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004538 final NetworkCapabilities prevNc = nai.networkCapabilities;
4539 synchronized (nai) {
4540 nai.networkCapabilities = networkCapabilities;
4541 }
4542 if (nai.getCurrentScore() == oldScore &&
4543 networkCapabilities.equalRequestableCapabilities(prevNc)) {
4544 // If the requestable capabilities haven't changed, and the score hasn't changed, then
4545 // the change we're processing can't affect any requests, it can only affect the listens
4546 // on this network. We might have been called by rematchNetworkAndRequests when a
4547 // network changed foreground state.
4548 processListenRequests(nai, true);
4549 } else {
4550 // If the requestable capabilities have changed or the score changed, we can't have been
4551 // called by rematchNetworkAndRequests, so it's safe to start a rematch.
Paul Jensene0988542015-06-25 15:30:08 -04004552 rematchAllNetworksAndRequests(nai, oldScore);
4553 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004554 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004555 }
4556
Paul Jensenc8b9a742014-09-30 15:37:41 -04004557 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004558 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4559 NetworkRequest nr = nai.requestAt(i);
Paul Jensenc8b9a742014-09-30 15:37:41 -04004560 // Don't send listening requests to factories. b/17393458
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004561 if (nr.isListen()) continue;
Paul Jensenc8b9a742014-09-30 15:37:41 -04004562 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4563 }
4564 }
4565
Robert Greenwalt7b816022014-04-18 15:25:25 -07004566 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4567 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004568 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004569 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4570 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004571 }
4572 }
4573
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004574 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4575 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004576 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004577 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004578 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4579 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004580 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004581 sendIntent(nri.mPendingIntent, intent);
4582 }
4583 // else not handled
4584 }
4585
4586 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4587 mPendingIntentWakeLock.acquire();
4588 try {
4589 if (DBG) log("Sending " + pendingIntent);
4590 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4591 } catch (PendingIntent.CanceledException e) {
4592 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4593 mPendingIntentWakeLock.release();
4594 releasePendingNetworkRequest(pendingIntent);
4595 }
4596 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4597 }
4598
4599 @Override
4600 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4601 String resultData, Bundle resultExtras) {
4602 if (DBG) log("Finished sending " + pendingIntent);
4603 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004604 // Release with a delay so the receiving client has an opportunity to put in its
4605 // own request.
4606 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004607 }
4608
Robert Greenwalt9258c642014-03-26 16:47:06 -07004609 private void callCallbackForRequest(NetworkRequestInfo nri,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004610 NetworkAgentInfo networkAgent, int notificationType, int arg1) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004611 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004612 Bundle bundle = new Bundle();
4613 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4614 new NetworkRequest(nri.request));
4615 Message msg = Message.obtain();
4616 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4617 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4618 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4619 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004620 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004621 case ConnectivityManager.CALLBACK_LOSING: {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004622 msg.arg1 = arg1;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004623 break;
4624 }
4625 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4626 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4627 new NetworkCapabilities(networkAgent.networkCapabilities));
4628 break;
4629 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004630 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004631 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4632 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004633 break;
4634 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004635 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004636 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004637 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004638 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004639 if (VDBG) {
4640 log("sending notification " + notifyTypeToName(notificationType) +
4641 " for " + nri.request);
4642 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004643 nri.messenger.send(msg);
4644 } catch (RemoteException e) {
4645 // may occur naturally in the race of binder death.
4646 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4647 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004648 }
4649
Paul Jensenc8b9a742014-09-30 15:37:41 -04004650 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004651 if (nai.numRequestNetworkRequests() != 0) {
4652 for (int i = 0; i < nai.numNetworkRequests(); i++) {
4653 NetworkRequest nr = nai.requestAt(i);
4654 // Ignore listening requests.
Lorenzo Colittif4a45f42016-07-18 18:17:08 +09004655 if (nr.isListen()) continue;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004656 loge("Dead network still had at least " + nr);
4657 break;
4658 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004659 }
4660 nai.asyncChannel.disconnect();
4661 }
4662
Robert Greenwalt7b816022014-04-18 15:25:25 -07004663 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4664 if (oldNetwork == null) {
4665 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4666 return;
4667 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004668 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004669
4670 // If we get here it means that the last linger timeout for this network expired. So there
4671 // must be no other active linger timers, and we must stop lingering.
4672 oldNetwork.clearLingerState();
4673
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004674 if (unneeded(oldNetwork, UnneededFor.TEARDOWN)) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004675 // Tear the network down.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004676 teardownUnneededNetwork(oldNetwork);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004677 } else {
4678 // Put the network in the background.
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004679 updateCapabilities(oldNetwork.getCurrentScore(), oldNetwork,
4680 oldNetwork.networkCapabilities);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004681 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004682 }
4683
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004684 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004685 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004686 setupDataActivityTracking(newNetwork);
4687 try {
4688 mNetd.setDefaultNetId(newNetwork.network.netId);
4689 } catch (Exception e) {
4690 loge("Exception setting default network :" + e);
4691 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004692 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004693 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004694 updateTcpBufferSizes(newNetwork);
Lorenzo Colittie3b85df2017-01-06 10:25:02 +09004695 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004696 }
4697
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004698 private void processListenRequests(NetworkAgentInfo nai, boolean capabilitiesChanged) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004699 // For consistency with previous behaviour, send onLost callbacks before onAvailable.
4700 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4701 NetworkRequest nr = nri.request;
4702 if (!nr.isListen()) continue;
4703 if (nai.isSatisfyingRequest(nr.requestId) && !nai.satisfies(nr)) {
4704 nai.removeRequest(nri.request.requestId);
4705 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_LOST, 0);
4706 }
4707 }
4708
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004709 if (capabilitiesChanged) {
4710 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
4711 }
4712
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004713 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
4714 NetworkRequest nr = nri.request;
4715 if (!nr.isListen()) continue;
4716 if (nai.satisfies(nr) && !nai.isSatisfyingRequest(nr.requestId)) {
4717 nai.addRequest(nr);
Erik Klinec75d4fa2017-02-15 19:59:17 +09004718 notifyNetworkAvailable(nai, nri);
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004719 }
4720 }
4721 }
4722
Paul Jensen2161a8e2014-09-11 11:00:39 -04004723 // Handles a network appearing or improving its score.
4724 //
4725 // - Evaluates all current NetworkRequests that can be
4726 // satisfied by newNetwork, and reassigns to newNetwork
4727 // any such requests for which newNetwork is the best.
4728 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004729 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004730 // needed. A network is needed if it is the best network for
4731 // one or more NetworkRequests, or if it is a VPN.
4732 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004733 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004734 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004735 //
4736 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4737 // networks that have no chance (i.e. even if validated)
4738 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004739 //
4740 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4741 // it does not remove NetworkRequests that other Networks could better satisfy.
4742 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4743 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4744 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004745 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004746 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004747 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4748 // performed to tear down unvalidated networks that have no chance (i.e. even if
4749 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004750 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004751 ReapUnvalidatedNetworks reapUnvalidatedNetworks, long now) {
Robin Lee585e2482016-05-01 23:00:00 +01004752 if (!newNetwork.everConnected) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004753 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004754 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004755 NetworkAgentInfo oldDefaultNetwork = null;
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004756
4757 final boolean wasBackgroundNetwork = newNetwork.isBackgroundNetwork();
4758 final int score = newNetwork.getCurrentScore();
4759
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004760 if (VDBG) log("rematching " + newNetwork.name());
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004761
Paul Jensen2161a8e2014-09-11 11:00:39 -04004762 // Find and migrate to this Network any NetworkRequests for
4763 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004764 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004765 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004766 NetworkCapabilities nc = newNetwork.networkCapabilities;
4767 if (VDBG) log(" network has: " + nc);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004768 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004769 // Process requests in the first pass and listens in the second pass. This allows us to
4770 // change a network's capabilities depending on which requests it has. This is only
4771 // correct if the change in capabilities doesn't affect whether the network satisfies
4772 // requests or not, and doesn't affect the network's score.
4773 if (nri.request.isListen()) continue;
4774
Paul Jensencf4c2c62015-07-01 14:16:32 -04004775 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4776 final boolean satisfies = newNetwork.satisfies(nri.request);
4777 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004778 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004779 log("Network " + newNetwork.name() + " was already satisfying" +
4780 " request " + nri.request.requestId + ". No change.");
4781 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004782 keep = true;
4783 continue;
4784 }
4785
4786 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004787 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004788 if (satisfies) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004789 // next check if it's better than any current network we're using for
4790 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004791 if (VDBG) {
4792 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004793 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004794 ", newScore = " + score);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004795 }
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004796 if (currentNetwork == null || currentNetwork.getCurrentScore() < score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004797 if (VDBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004798 if (currentNetwork != null) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004799 if (VDBG) log(" accepting network in place of " + currentNetwork.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004800 currentNetwork.removeRequest(nri.request.requestId);
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004801 currentNetwork.lingerRequest(nri.request, now, mLingerDelayMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004802 affectedNetworks.add(currentNetwork);
4803 } else {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09004804 if (VDBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004805 }
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004806 newNetwork.unlingerRequest(nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004807 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004808 if (!newNetwork.addRequest(nri.request)) {
4809 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4810 }
4811 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004812 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004813 // Tell NetworkFactories about the new score, so they can stop
4814 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004815 // TODO - this could get expensive if we have alot of requests for this
4816 // network. Think about if there is a way to reduce this. Push
4817 // netid->request mapping to each factory?
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004818 sendUpdatedScoreToFactories(nri.request, score);
Lorenzo Colitti5526f9c2016-08-22 16:46:40 +09004819 if (isDefaultRequest(nri)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004820 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004821 oldDefaultNetwork = currentNetwork;
Lorenzo Colittic2e10bb2016-08-29 14:03:11 +09004822 if (currentNetwork != null) {
4823 mLingerMonitor.noteLingerDefaultNetwork(currentNetwork, newNetwork);
4824 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004825 }
4826 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004827 } else if (newNetwork.isSatisfyingRequest(nri.request.requestId)) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004828 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4829 // mark it as no longer satisfying "nri". Because networks are processed by
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09004830 // rematchAllNetworksAndRequests() in descending score order, "currentNetwork" will
Paul Jensencf4c2c62015-07-01 14:16:32 -04004831 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4832 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4833 // This means this code doesn't have to handle the case where "currentNetwork" no
4834 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4835 if (DBG) {
4836 log("Network " + newNetwork.name() + " stopped satisfying" +
4837 " request " + nri.request.requestId);
4838 }
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004839 newNetwork.removeRequest(nri.request.requestId);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004840 if (currentNetwork == newNetwork) {
4841 mNetworkForRequestId.remove(nri.request.requestId);
4842 sendUpdatedScoreToFactories(nri.request, 0);
4843 } else {
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004844 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4845 newNetwork.name() +
4846 " without updating mNetworkForRequestId or factories!");
Paul Jensencf4c2c62015-07-01 14:16:32 -04004847 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004848 // TODO: Technically, sending CALLBACK_LOST here is
4849 // incorrect if there is a replacement network currently
4850 // connected that can satisfy nri, which is a request
4851 // (not a listen). However, the only capability that can both
Paul Jensencf4c2c62015-07-01 14:16:32 -04004852 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4853 // so this code is only incorrect for a network that loses
4854 // the TRUSTED capability, which is a rare case.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004855 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004856 }
4857 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004858 if (isNewDefault) {
4859 // Notify system services that this network is up.
Hugo Benichi1654b1d2016-05-24 11:50:31 +09004860 makeDefault(newNetwork);
4861 // Log 0 -> X and Y -> X default network transitions, where X is the new default.
4862 logDefaultNetworkEvent(newNetwork, oldDefaultNetwork);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004863 synchronized (ConnectivityService.this) {
4864 // have a new default network, release the transition wakelock in
4865 // a second if it's held. The second pause is to allow apps
4866 // to reconnect over the new network
4867 if (mNetTransitionWakeLock.isHeld()) {
4868 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4869 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4870 mNetTransitionWakeLockSerialNumber, 0),
4871 1000);
4872 }
4873 }
4874 }
4875
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004876 if (!newNetwork.networkCapabilities.equalRequestableCapabilities(nc)) {
4877 Slog.wtf(TAG, String.format(
4878 "BUG: %s changed requestable capabilities during rematch: %s -> %s",
4879 nc, newNetwork.networkCapabilities));
4880 }
4881 if (newNetwork.getCurrentScore() != score) {
4882 Slog.wtf(TAG, String.format(
4883 "BUG: %s changed score during rematch: %d -> %d",
4884 score, newNetwork.getCurrentScore()));
4885 }
4886
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004887 // Second pass: process all listens.
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004888 if (wasBackgroundNetwork != newNetwork.isBackgroundNetwork()) {
4889 // If the network went from background to foreground or vice versa, we need to update
4890 // its foreground state. It is safe to do this after rematching the requests because
4891 // NET_CAPABILITY_FOREGROUND does not affect requests, as is not a requestable
4892 // capability and does not affect the network's score (see the Slog.wtf call above).
Lorenzo Colittib8167f62016-09-15 22:47:08 +09004893 updateCapabilities(score, newNetwork, newNetwork.networkCapabilities);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09004894 } else {
4895 processListenRequests(newNetwork, false);
4896 }
Lorenzo Colitti72bbf482016-07-20 02:39:22 +09004897
Paul Jensencf4c2c62015-07-01 14:16:32 -04004898 // do this after the default net is switched, but
4899 // before LegacyTypeTracker sends legacy broadcasts
Erik Klinec75d4fa2017-02-15 19:59:17 +09004900 for (NetworkRequestInfo nri : addedRequests) notifyNetworkAvailable(newNetwork, nri);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004901
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004902 // Linger any networks that are no longer needed. This should be done after sending the
4903 // available callback for newNetwork.
4904 for (NetworkAgentInfo nai : affectedNetworks) {
4905 updateLingerState(nai, now);
4906 }
4907 // Possibly unlinger newNetwork. Unlingering a network does not send any callbacks so it
4908 // does not need to be done in any particular order.
4909 updateLingerState(newNetwork, now);
4910
Paul Jensencf4c2c62015-07-01 14:16:32 -04004911 if (isNewDefault) {
4912 // Maintain the illusion: since the legacy API only
4913 // understands one network at a time, we must pretend
4914 // that the current default network disconnected before
4915 // the new one connected.
4916 if (oldDefaultNetwork != null) {
4917 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4918 oldDefaultNetwork, true);
4919 }
4920 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4921 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4922 notifyLockdownVpn(newNetwork);
4923 }
4924
Robert Greenwalt7b816022014-04-18 15:25:25 -07004925 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004926 // Notify battery stats service about this network, both the normal
4927 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004928 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004929 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004930 final IBatteryStats bs = BatteryStatsService.getService();
4931 final int type = newNetwork.networkInfo.getType();
4932
4933 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4934 bs.noteNetworkInterfaceType(baseIface, type);
4935 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4936 final String stackedIface = stacked.getInterfaceName();
4937 bs.noteNetworkInterfaceType(stackedIface, type);
4938 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4939 }
4940 } catch (RemoteException ignored) {
4941 }
4942
Robert Greenwalt152ed372014-12-17 17:19:53 -08004943 // This has to happen after the notifyNetworkCallbacks as that tickles each
4944 // ConnectivityManager instance so that legacy requests correctly bind dns
4945 // requests to this network. The legacy users are listening for this bcast
4946 // and will generally do a dns request so they can ensureRouteToHost and if
4947 // they do that before the callbacks happen they'll use the default network.
4948 //
4949 // TODO: Is there still a race here? We send the broadcast
4950 // after sending the callback, but if the app can receive the
4951 // broadcast before the callback, it might still break.
4952 //
4953 // This *does* introduce a race where if the user uses the new api
4954 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4955 // they may get old info. Reverse this after the old startUsing api is removed.
4956 // This is on top of the multiple intent sequencing referenced in the todo above.
Lorenzo Colitti767708d2016-07-01 01:37:11 +09004957 for (int i = 0; i < newNetwork.numNetworkRequests(); i++) {
4958 NetworkRequest nr = newNetwork.requestAt(i);
Lorenzo Colittib35d40d2016-07-01 13:19:21 +09004959 if (nr.legacyType != TYPE_NONE && nr.isRequest()) {
Robert Greenwalt152ed372014-12-17 17:19:53 -08004960 // legacy type tracker filters out repeat adds
4961 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4962 }
4963 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004964
4965 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4966 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4967 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4968 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4969 if (newNetwork.isVPN()) {
4970 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4971 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004972 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004973 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4974 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Lorenzo Colitti3d4a1062016-09-09 18:48:56 +09004975 if (unneeded(nai, UnneededFor.TEARDOWN)) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09004976 if (nai.getLingerExpiry() > 0) {
4977 // This network has active linger timers and no requests, but is not
4978 // lingering. Linger it.
4979 //
4980 // One way (the only way?) this can happen if this network is unvalidated
4981 // and became unneeded due to another network improving its score to the
4982 // point where this network will no longer be able to satisfy any requests
4983 // even if it validates.
4984 updateLingerState(nai, now);
4985 } else {
4986 if (DBG) log("Reaping " + nai.name());
4987 teardownUnneededNetwork(nai);
4988 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004989 }
4990 }
4991 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004992 }
4993
Paul Jensen1c7ba022015-06-16 14:27:36 -04004994 /**
4995 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4996 * being disconnected.
4997 * @param changed If only one Network's score or capabilities have been modified since the last
4998 * time this function was called, pass this Network in this argument, otherwise pass
4999 * null.
5000 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
5001 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
5002 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
5003 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
5004 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04005005 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04005006 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04005007 // TODO: This may get slow. The "changed" parameter is provided for future optimization
5008 // to avoid the slowness. It is not simply enough to process just "changed", for
5009 // example in the case where "changed"'s score decreases and another network should begin
5010 // satifying a NetworkRequest that "changed" currently satisfies.
5011
5012 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
5013 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
5014 // rematchNetworkAndRequests() handles.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005015 final long now = SystemClock.elapsedRealtime();
Paul Jensen85cf78e2015-06-25 13:25:07 -04005016 if (changed != null && oldScore < changed.getCurrentScore()) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005017 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP, now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005018 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005019 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
5020 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
5021 // Rematch higher scoring networks first to prevent requests first matching a lower
5022 // scoring network and then a higher scoring network, which could produce multiple
5023 // callbacks and inadvertently unlinger networks.
5024 Arrays.sort(nais);
5025 for (NetworkAgentInfo nai : nais) {
5026 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05005027 // Only reap the last time through the loop. Reaping before all rematching
5028 // is complete could incorrectly teardown a network that hasn't yet been
5029 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04005030 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005031 : ReapUnvalidatedNetworks.REAP,
5032 now);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005033 }
5034 }
5035 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005036
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005037 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04005038 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09005039 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005040 // For now only update icons for default connection.
5041 // TODO: Update WiFi and cellular icons separately. b/17237507
5042 if (!isDefaultNetwork(nai)) return;
5043
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09005044 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04005045 // Don't repeat publish.
5046 if (newInetCondition == mDefaultInetConditionPublished) return;
5047
5048 mDefaultInetConditionPublished = newInetCondition;
5049 sendInetConditionBroadcast(nai.networkInfo);
5050 }
5051
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005052 private void notifyLockdownVpn(NetworkAgentInfo nai) {
5053 if (mLockdownTracker != null) {
5054 if (nai != null && nai.isVPN()) {
5055 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
5056 } else {
5057 mLockdownTracker.onNetworkInfoChanged();
5058 }
5059 }
5060 }
5061
Robert Greenwalt7b816022014-04-18 15:25:25 -07005062 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
Erik Klinec75d4fa2017-02-15 19:59:17 +09005063 final NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005064 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07005065 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07005066 synchronized (networkAgent) {
5067 oldInfo = networkAgent.networkInfo;
5068 networkAgent.networkInfo = newInfo;
5069 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09005070 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005071
5072 if (oldInfo != null && oldInfo.getState() == state) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005073 if (oldInfo.isRoaming() != newInfo.isRoaming()) {
5074 if (VDBG) log("roaming status changed, notifying NetworkStatsService");
5075 notifyIfacesChangedForNetworkStats();
5076 } else if (VDBG) log("ignoring duplicate network state non-change");
5077 // In either case, no further work should be needed.
Robert Greenwalt7b816022014-04-18 15:25:25 -07005078 return;
5079 }
5080 if (DBG) {
5081 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
5082 (oldInfo == null ? "null" : oldInfo.getState()) +
5083 " to " + state);
5084 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005085
Robin Lee585e2482016-05-01 23:00:00 +01005086 if (!networkAgent.created
5087 && (state == NetworkInfo.State.CONNECTED
5088 || (state == NetworkInfo.State.CONNECTING && networkAgent.isVPN()))) {
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005089
5090 // A network that has just connected has zero requests and is thus a foreground network.
5091 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_FOREGROUND);
5092
Robert Greenwalt7b816022014-04-18 15:25:25 -07005093 try {
Paul Jenseneec75412014-08-04 12:21:19 -04005094 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005095 if (networkAgent.isVPN()) {
5096 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07005097 !networkAgent.linkProperties.getDnsServers().isEmpty(),
5098 (networkAgent.networkMisc == null ||
5099 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005100 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04005101 mNetd.createPhysicalNetwork(networkAgent.network.netId,
Lorenzo Colittifbe9b1a2016-07-28 17:14:11 +09005102 getNetworkPermission(networkAgent.networkCapabilities));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005103 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005104 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09005105 loge("Error creating network " + networkAgent.network.netId + ": "
5106 + e.getMessage());
5107 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07005108 }
Paul Jenseneec75412014-08-04 12:21:19 -04005109 networkAgent.created = true;
Robin Lee585e2482016-05-01 23:00:00 +01005110 }
5111
5112 if (!networkAgent.everConnected && state == NetworkInfo.State.CONNECTED) {
5113 networkAgent.everConnected = true;
5114
Robert Greenwalt7b816022014-04-18 15:25:25 -07005115 updateLinkProperties(networkAgent, null);
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005116 notifyIfacesChangedForNetworkStats();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005117
Paul Jensenca8f16a2014-05-09 12:47:55 -04005118 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09005119 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005120
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005121 if (networkAgent.isVPN()) {
5122 // Temporarily disable the default proxy (not global).
5123 synchronized (mProxyLock) {
5124 if (!mDefaultProxyDisabled) {
5125 mDefaultProxyDisabled = true;
5126 if (mGlobalProxy == null && mDefaultProxy != null) {
5127 sendProxyBroadcast(null);
5128 }
5129 }
5130 }
5131 // TODO: support proxy per network.
5132 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005133
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005134 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
5135 // be communicated to a particular NetworkAgent depends only on the network's immutable,
5136 // capabilities, so it only needs to be done once on initial connect, not every time the
5137 // network's capabilities change. Note that we do this before rematching the network,
5138 // so we could decide to tear it down immediately afterwards. That's fine though - on
5139 // disconnection NetworkAgents should stop any signal strength monitoring they have been
5140 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09005141 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09005142
Paul Jensen2161a8e2014-09-11 11:00:39 -04005143 // Consider network even though it is not yet validated.
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005144 final long now = SystemClock.elapsedRealtime();
5145 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP, now);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09005146
5147 // This has to happen after matching the requests, because callbacks are just requests.
5148 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005149 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07005150 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04005151 if (networkAgent.isVPN()) {
5152 synchronized (mProxyLock) {
5153 if (mDefaultProxyDisabled) {
5154 mDefaultProxyDisabled = false;
5155 if (mGlobalProxy == null && mDefaultProxy != null) {
5156 sendProxyBroadcast(mDefaultProxy);
5157 }
5158 }
5159 }
5160 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07005161 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
5162 state == NetworkInfo.State.SUSPENDED) {
5163 // going into or coming out of SUSPEND: rescore and notify
5164 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04005165 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005166 }
5167 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
5168 ConnectivityManager.CALLBACK_SUSPENDED :
5169 ConnectivityManager.CALLBACK_RESUMED));
5170 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07005171 }
5172 }
5173
Robert Greenwaltac96c522014-06-03 16:43:57 -07005174 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005175 if (VDBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07005176 if (score < 0) {
5177 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
5178 "). Bumping score to min of 0");
5179 score = 0;
5180 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07005181
Paul Jensen2161a8e2014-09-11 11:00:39 -04005182 final int oldScore = nai.getCurrentScore();
5183 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07005184
Paul Jensen85cf78e2015-06-25 13:25:07 -04005185 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04005186
Paul Jensenc8b9a742014-09-30 15:37:41 -04005187 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07005188 }
5189
Erik Klinec75d4fa2017-02-15 19:59:17 +09005190 // Notify only this one new request of the current state. Transfer all the
5191 // current state by calling NetworkCapabilities and LinkProperties callbacks
5192 // so that callers can be guaranteed to have as close to atomicity in state
5193 // transfer as can be supported by this current API.
5194 protected void notifyNetworkAvailable(NetworkAgentInfo nai, NetworkRequestInfo nri) {
Etan Cohen681fcda2016-10-27 15:05:50 -07005195 mHandler.removeMessages(EVENT_TIMEOUT_NETWORK_REQUEST, nri);
Erik Klinec75d4fa2017-02-15 19:59:17 +09005196 if (nri.mPendingIntent != null) {
5197 sendPendingIntentForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE);
5198 // Attempt no subsequent state pushes where intents are involved.
5199 return;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005200 }
Erik Klinec75d4fa2017-02-15 19:59:17 +09005201
5202 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_AVAILABLE, 0);
5203 // Whether a network is currently suspended is also an important
5204 // element of state to be transferred (it would not otherwise be
5205 // delivered by any currently available mechanism).
5206 if (nai.networkInfo.getState() == NetworkInfo.State.SUSPENDED) {
5207 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_SUSPENDED, 0);
5208 }
5209 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_CAP_CHANGED, 0);
5210 callCallbackForRequest(nri, nai, ConnectivityManager.CALLBACK_IP_CHANGED, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005211 }
5212
Robert Greenwalt8d482522015-06-24 13:23:42 -07005213 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09005214 // The NetworkInfo we actually send out has no bearing on the real
5215 // state of affairs. For example, if the default connection is mobile,
5216 // and a request for HIPRI has just gone away, we need to pretend that
5217 // HIPRI has just disconnected. So we need to set the type to HIPRI and
5218 // the state to DISCONNECTED, even though the network is of type MOBILE
5219 // and is still connected.
5220 NetworkInfo info = new NetworkInfo(nai.networkInfo);
5221 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07005222 if (state != DetailedState.DISCONNECTED) {
5223 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09005224 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005225 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07005226 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005227 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
5228 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
5229 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
5230 if (info.isFailover()) {
5231 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
5232 nai.networkInfo.setFailover(false);
5233 }
5234 if (info.getReason() != null) {
5235 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
5236 }
5237 if (info.getExtraInfo() != null) {
5238 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
5239 }
5240 NetworkAgentInfo newDefaultAgent = null;
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005241 if (nai.isSatisfyingRequest(mDefaultRequest.requestId)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04005242 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005243 if (newDefaultAgent != null) {
5244 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
5245 newDefaultAgent.networkInfo);
5246 } else {
5247 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
5248 }
5249 }
5250 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
5251 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09005252 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005253 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09005254 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07005255 }
5256 }
5257 }
5258
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005259 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType, int arg1) {
Lorenzo Colitti39d2bb52016-04-08 23:09:09 +09005260 if (VDBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Lorenzo Colitti767708d2016-07-01 01:37:11 +09005261 for (int i = 0; i < networkAgent.numNetworkRequests(); i++) {
5262 NetworkRequest nr = networkAgent.requestAt(i);
Robert Greenwalt9258c642014-03-26 16:47:06 -07005263 NetworkRequestInfo nri = mNetworkRequests.get(nr);
5264 if (VDBG) log(" sending notification for " + nr);
Lorenzo Colittif0e9a332016-07-18 18:40:42 +09005265 // TODO: if we're in the middle of a rematch, can we send a CAP_CHANGED callback for
5266 // a network that no longer satisfies the listen?
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005267 if (nri.mPendingIntent == null) {
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005268 callCallbackForRequest(nri, networkAgent, notifyType, arg1);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08005269 } else {
5270 sendPendingIntentForRequest(nri, networkAgent, notifyType);
5271 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005272 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07005273 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07005274
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005275 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
5276 notifyNetworkCallbacks(networkAgent, notifyType, 0);
5277 }
5278
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07005279 private String notifyTypeToName(int notifyType) {
5280 switch (notifyType) {
5281 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
5282 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
5283 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
5284 case ConnectivityManager.CALLBACK_LOST: return "LOST";
5285 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
5286 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
5287 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
5288 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
5289 }
5290 return "UNKNOWN";
5291 }
5292
Jeff Sharkey69736342014-12-08 14:50:12 -08005293 /**
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005294 * Notify NetworkStatsService that the set of active ifaces has changed, or that one of the
5295 * properties tracked by NetworkStatsService on an active iface has changed.
Jeff Sharkey69736342014-12-08 14:50:12 -08005296 */
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005297 private void notifyIfacesChangedForNetworkStats() {
Jeff Sharkey69736342014-12-08 14:50:12 -08005298 try {
5299 mStatsService.forceUpdateIfaces();
5300 } catch (Exception ignored) {
5301 }
5302 }
5303
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07005304 @Override
5305 public boolean addVpnAddress(String address, int prefixLength) {
5306 throwIfLockdownEnabled();
5307 int user = UserHandle.getUserId(Binder.getCallingUid());
5308 synchronized (mVpns) {
5309 return mVpns.get(user).addAddress(address, prefixLength);
5310 }
5311 }
5312
5313 @Override
5314 public boolean removeVpnAddress(String address, int prefixLength) {
5315 throwIfLockdownEnabled();
5316 int user = UserHandle.getUserId(Binder.getCallingUid());
5317 synchronized (mVpns) {
5318 return mVpns.get(user).removeAddress(address, prefixLength);
5319 }
5320 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005321
5322 @Override
5323 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
5324 throwIfLockdownEnabled();
5325 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005326 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005327 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005328 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005329 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005330 if (success) {
Jeff Davidson0b93c5d2016-01-20 11:35:38 -08005331 notifyIfacesChangedForNetworkStats();
Wenchao Tongf5ea3402015-03-04 13:26:38 -08005332 }
5333 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08005334 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005335
5336 @Override
Udam Sainib7c24872016-01-04 12:16:14 -08005337 public String getCaptivePortalServerUrl() {
Hugo Benichi92eb22fd2016-09-27 13:01:41 +09005338 return NetworkMonitor.getCaptivePortalServerHttpUrl(mContext);
Udam Sainib7c24872016-01-04 12:16:14 -08005339 }
5340
5341 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09005342 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
5343 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
5344 enforceKeepalivePermission();
5345 mKeepaliveTracker.startNattKeepalive(
5346 getNetworkAgentInfoForNetwork(network),
5347 intervalSeconds, messenger, binder,
5348 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
5349 }
5350
5351 @Override
5352 public void stopKeepalive(Network network, int slot) {
5353 mHandler.sendMessage(mHandler.obtainMessage(
5354 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
5355 }
5356
5357 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07005358 public void factoryReset() {
5359 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07005360
5361 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
5362 return;
5363 }
5364
Robin Lee3b3dd942015-05-12 18:14:58 +01005365 final int userId = UserHandle.getCallingUserId();
5366
Stuart Scottf1fb3972015-04-02 18:00:02 -07005367 // Turn airplane mode off
5368 setAirplaneMode(false);
5369
Stuart Scotte3e314d2015-04-20 14:07:45 -07005370 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
5371 // Untether
5372 for (String tether : getTetheredIfaces()) {
5373 untether(tether);
5374 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005375 }
5376
Stuart Scotte3e314d2015-04-20 14:07:45 -07005377 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
Victor Changb04a5ea2016-05-30 20:36:30 +01005378 // Remove always-on package
5379 synchronized (mVpns) {
5380 final String alwaysOnPackage = getAlwaysOnVpnPackage(userId);
5381 if (alwaysOnPackage != null) {
5382 setAlwaysOnVpnPackage(userId, null, false);
5383 setVpnPackageAuthorization(alwaysOnPackage, userId, false);
5384 }
5385 }
5386
Koichi, Sugimotoda1a7ac2016-01-27 18:48:58 +09005387 // Turn Always-on VPN off
5388 if (mLockdownEnabled && userId == UserHandle.USER_SYSTEM) {
5389 final long ident = Binder.clearCallingIdentity();
5390 try {
5391 mKeyStore.delete(Credentials.LOCKDOWN_VPN);
5392 mLockdownEnabled = false;
5393 setLockdownTracker(null);
5394 } finally {
5395 Binder.restoreCallingIdentity(ident);
5396 }
5397 }
5398
Stuart Scotte3e314d2015-04-20 14:07:45 -07005399 // Turn VPN off
5400 VpnConfig vpnConfig = getVpnConfig(userId);
5401 if (vpnConfig != null) {
5402 if (vpnConfig.legacy) {
5403 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
5404 } else {
5405 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
5406 // in the future without user intervention.
5407 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005408
Victor Changb04a5ea2016-05-30 20:36:30 +01005409 prepareVpn(null, VpnConfig.LEGACY_VPN, userId);
Stuart Scotte3e314d2015-04-20 14:07:45 -07005410 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07005411 }
5412 }
Lorenzo Colitti9be58c52016-09-15 14:02:29 +09005413
5414 Settings.Global.putString(mContext.getContentResolver(),
5415 Settings.Global.NETWORK_AVOID_BAD_WIFI, null);
Stuart Scottf1fb3972015-04-02 18:00:02 -07005416 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04005417
5418 @VisibleForTesting
5419 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
5420 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
5421 return new NetworkMonitor(context, handler, nai, defaultRequest);
5422 }
Erik Kline48f12f22016-04-14 17:30:59 +09005423
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005424 @VisibleForTesting
Lorenzo Colitti58ebe1c2017-01-24 09:41:36 +09005425 MultinetworkPolicyTracker createMultinetworkPolicyTracker(Context c, Handler h, Runnable r) {
5426 return new MultinetworkPolicyTracker(c, h, r);
Erik Kline065ab6e2016-10-02 18:02:14 +09005427 }
5428
5429 @VisibleForTesting
Lorenzo Colittib57578ca2016-07-01 01:53:25 +09005430 public WakeupMessage makeWakeupMessage(Context c, Handler h, String s, int cmd, Object obj) {
5431 return new WakeupMessage(c, h, s, cmd, 0, 0, obj);
5432 }
5433
Hugo Benichicfddd682016-05-31 16:28:06 +09005434 private void logDefaultNetworkEvent(NetworkAgentInfo newNai, NetworkAgentInfo prevNai) {
Hugo Benichi5f16f762016-04-20 12:09:33 +09005435 int newNetid = NETID_UNSET;
5436 int prevNetid = NETID_UNSET;
5437 int[] transports = new int[0];
5438 boolean hadIPv4 = false;
5439 boolean hadIPv6 = false;
Erik Kline48f12f22016-04-14 17:30:59 +09005440
Hugo Benichi5f16f762016-04-20 12:09:33 +09005441 if (newNai != null) {
5442 newNetid = newNai.network.netId;
5443 transports = newNai.networkCapabilities.getTransportTypes();
5444 }
5445 if (prevNai != null) {
5446 prevNetid = prevNai.network.netId;
5447 final LinkProperties lp = prevNai.linkProperties;
5448 hadIPv4 = lp.hasIPv4Address() && lp.hasIPv4DefaultRoute();
5449 hadIPv6 = lp.hasGlobalIPv6Address() && lp.hasIPv6DefaultRoute();
5450 }
5451
Hugo Benichicfddd682016-05-31 16:28:06 +09005452 mMetricsLog.log(new DefaultNetworkEvent(newNetid, transports, prevNetid, hadIPv4, hadIPv6));
5453 }
5454
5455 private void logNetworkEvent(NetworkAgentInfo nai, int evtype) {
5456 mMetricsLog.log(new NetworkEvent(nai.network.netId, evtype));
Erik Kline48f12f22016-04-14 17:30:59 +09005457 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08005458}