blob: a7e6f1187719390470089c09f172ddc63fcb6b0b [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 Colitti8deb3412015-05-14 17:07:20 +090027import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
30import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070031import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070033import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070034
Wenchao Tongf5ea3402015-03-04 13:26:38 -080035import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070036import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070037import android.app.Notification;
38import android.app.NotificationManager;
39import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070040import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080041import android.content.ContentResolver;
42import android.content.Context;
43import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070044import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080045import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070046import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090047import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070048import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080049import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090050import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080051import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070052import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070053import android.net.INetworkPolicyListener;
54import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070055import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080056import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070057import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070058import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070059import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070061import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080062import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070063import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070064import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070065import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070066import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070067import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070068import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070069import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040070import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070071import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040072import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040073import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070075import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040076import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080077import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070078import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070079import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070080import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080081import android.os.Looper;
82import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070083import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070084import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070085import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070086import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070087import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070088import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080089import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070090import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040091import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080092import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070093import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070094import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070095import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070096import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070097import android.util.LocalLog;
98import android.util.LocalLog.ReadOnlyLocalLog;
99import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800100import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700101import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500102import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700103import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700104import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800105
Wink Savilleab9321d2013-06-29 21:10:57 -0700106import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400107import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400108import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700109import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700110import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700112import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800113import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700114import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700115import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700116import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700117import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700118import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700119import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400120import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900121import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900122import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900123import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700124import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400125import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400126import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700127import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800128import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700129import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700130import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700131import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700132import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700133import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700134
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700135import org.xmlpull.v1.XmlPullParser;
136import org.xmlpull.v1.XmlPullParserException;
137
138import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800139import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700140import java.io.FileNotFoundException;
141import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700142import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800143import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700144import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700145import java.net.InetAddress;
146import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700147import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700148import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700149import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700150import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700151import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700152import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900153import java.util.SortedSet;
154import java.util.TreeSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500155import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700156import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700157import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700158import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700159import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
161/**
162 * @hide
163 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800164public class ConnectivityService extends IConnectivityManager.Stub
165 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700166 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700168 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700169 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800170
Jake Hamby786e71a2014-02-06 14:43:50 -0800171 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700172
Jeff Sharkey899223b2012-08-04 15:24:58 -0700173 // TODO: create better separation between radio types and network types
174
Robert Greenwalt42acef32009-08-12 16:08:25 -0700175 // how long to wait before switching back to a radio's default network
176 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
177 // system property that can override the above value
178 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
179 "android.telephony.apn-restore";
180
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900181 // How long to wait before putting up a "This network doesn't have an Internet connection,
182 // connect anyway?" dialog after the user selects a network that doesn't validate.
183 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
184
Jeremy Joslin79294842014-12-03 17:15:28 -0800185 // How long to delay to removal of a pending intent based request.
186 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
187 private final int mReleasePendingIntentDelayMs;
188
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800189 private Tethering mTethering;
190
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700191 private final PermissionMonitor mPermissionMonitor;
192
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700193 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700194
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700195 @GuardedBy("mVpns")
196 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700197
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700198 private boolean mLockdownEnabled;
199 private LockdownVpnTracker mLockdownTracker;
200
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700201 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
202 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700203 /** Currently active network rules by UID. */
204 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700205 /** Set of ifaces that are costly. */
206 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700207
Erik Klineda4bfa82015-04-30 12:58:40 +0900208 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700210 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700211 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800212
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800213 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
215 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700216 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800217
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700218 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800219 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700220 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700221
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700222 private String mCurrentTcpBufferSizes;
223
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700224 private static final int ENABLED = 1;
225 private static final int DISABLED = 0;
226
Paul Jensenb10e37f2014-11-25 12:33:08 -0500227 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400228 // Tear down networks that have no chance (e.g. even if validated) of becoming
229 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500230 // all networks have been rematched against all NetworkRequests.
231 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400232 // Don't reap networks. This should be passed when some networks have not yet been
233 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500234 DONT_REAP
235 };
236
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700238 * used internally to change our mobile data enabled flag
239 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700240 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241
242 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700244 * from one net to another. Clear happens when we get a new
245 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
246 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700248 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250 /**
251 * used internally to reload global proxy settings
252 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700253 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700255 /**
Wink Saville628b0852011-08-04 15:01:58 -0700256 * used internally to send a sticky broadcast delayed.
257 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700258 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700259
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700260 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400261 * PAC manager has received new port.
262 */
263 private static final int EVENT_PROXY_HAS_CHANGED = 16;
264
Robert Greenwalte049c232014-04-11 15:53:27 -0700265 /**
266 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700267 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700268 */
269 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
270
Robert Greenwalt7b816022014-04-18 15:25:25 -0700271 /**
272 * used internally when registering NetworkAgents
273 * obj = Messenger
274 */
275 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
276
Robert Greenwalt9258c642014-03-26 16:47:06 -0700277 /**
278 * used to add a network request
279 * includes a NetworkRequestInfo
280 */
281 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
282
283 /**
284 * indicates a timeout period is over - check if we had a network yet or not
285 * and if not, call the timeout calback (but leave the request live until they
286 * cancel it.
287 * includes a NetworkRequestInfo
288 */
289 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
290
291 /**
292 * used to add a network listener - no request
293 * includes a NetworkRequestInfo
294 */
295 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
296
297 /**
298 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400299 * arg1 = UID of caller
300 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 */
302 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
303
Robert Greenwalta67be032014-05-16 15:49:14 -0700304 /**
305 * used internally when registering NetworkFactories
306 * obj = Messenger
307 */
308 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
309
Robert Greenwalt27711812014-06-25 16:45:57 -0700310 /**
311 * used internally to expire a wakelock when transitioning
312 * from one net to another. Expire happens when we fail to find
313 * a new network (typically after 1 minute) -
314 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
315 * a replacement network.
316 */
317 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
318
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700319 /**
320 * Used internally to indicate the system is ready.
321 */
322 private static final int EVENT_SYSTEM_READY = 25;
323
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800324 /**
325 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400326 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800327 */
328 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
329
330 /**
331 * used to remove a pending intent and its associated network request.
332 * arg1 = UID of caller
333 * obj = PendingIntent
334 */
335 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
336
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900337 /**
338 * used to specify whether a network should be used even if unvalidated.
339 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
340 * arg2 = whether to remember this choice in the future (1 or 0)
341 * obj = network
342 */
343 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
344
345 /**
346 * used to ask the user to confirm a connection to an unvalidated network.
347 * obj = network
348 */
349 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700350
Erik Klineda4bfa82015-04-30 12:58:40 +0900351 /**
352 * used internally to (re)configure mobile data always-on settings.
353 */
354 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
355
Paul Jensen694f2b82015-06-17 14:15:39 -0400356 /**
357 * used to add a network listener with a pending intent
358 * obj = NetworkRequestInfo
359 */
360 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
361
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900362 /** Handler thread used for both of the handlers below. */
363 @VisibleForTesting
364 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700365 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700366 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700367 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700368 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700369
Mike Lockwood0f79b542009-08-14 14:18:49 -0400370 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800371 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400372
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700373 private PowerManager.WakeLock mNetTransitionWakeLock;
374 private String mNetTransitionWakeLockCausedBy = "";
375 private int mNetTransitionWakeLockSerialNumber;
376 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800377 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700378
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700379 private InetAddress mDefaultDns;
380
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700381 // used in DBG mode to track inet condition reports
382 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
383 private ArrayList mInetLog;
384
Robert Greenwalt434203a2010-10-11 16:00:27 -0700385 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400386 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700387 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700388 private boolean mDefaultProxyDisabled = false;
389
Robert Greenwalt434203a2010-10-11 16:00:27 -0700390 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400391 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700392
Jason Monk602b2322013-07-03 17:04:33 -0400393 private PacManager mPacManager = null;
394
Erik Klineda4bfa82015-04-30 12:58:40 +0900395 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700396
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400397 private UserManager mUserManager;
398
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700399 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700400 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700401
Robert Greenwalt50393202011-06-21 17:26:14 -0700402 // the set of network types that can only be enabled by system/sig apps
403 List mProtectedNetworks;
404
John Spurlockbf991a82013-06-24 14:20:23 -0400405 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700406
Wink Savilleab9321d2013-06-29 21:10:57 -0700407 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400408
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900409 private KeepaliveTracker mKeepaliveTracker;
410
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700411 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
412 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700413 private final static int MAX_NET_ID = 65535;
414 private int mNextNetId = MIN_NET_ID;
415
Robert Greenwalt34524f02014-05-18 16:22:10 -0700416 // sequence number of NetworkRequests
417 private int mNextNetworkRequestId = 1;
418
Erik Kline7523eb32015-07-09 18:24:03 +0900419 // NetworkRequest activity String log entries.
420 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
421 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
422
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700423 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
424 private static final int MAX_VALIDATION_LOGS = 10;
425 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
426 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
427
428 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
429 synchronized(mValidationLogs) {
430 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
431 mValidationLogs.removeLast();
432 }
433 mValidationLogs.addFirst(new Pair(network, log));
434 }
435 }
436
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700437 /**
438 * Implements support for the legacy "one network per network type" model.
439 *
440 * We used to have a static array of NetworkStateTrackers, one for each
441 * network type, but that doesn't work any more now that we can have,
442 * for example, more that one wifi network. This class stores all the
443 * NetworkAgentInfo objects that support a given type, but the legacy
444 * API will only see the first one.
445 *
446 * It serves two main purposes:
447 *
448 * 1. Provide information about "the network for a given type" (since this
449 * API only supports one).
450 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
451 * the first network for a given type changes, or if the default network
452 * changes.
453 */
454 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900455
456 private static final boolean DBG = true;
457 private static final boolean VDBG = false;
458 private static final String TAG = "CSLegacyTypeTracker";
459
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700460 /**
461 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
462 * Each list holds references to all NetworkAgentInfos that are used to
463 * satisfy requests for that network type.
464 *
465 * This array is built out at startup such that an unsupported network
466 * doesn't get an ArrayList instance, making this a tristate:
467 * unsupported, supported but not active and active.
468 *
469 * The actual lists are populated when we scan the network types that
470 * are supported on this device.
471 */
472 private ArrayList<NetworkAgentInfo> mTypeLists[];
473
474 public LegacyTypeTracker() {
475 mTypeLists = (ArrayList<NetworkAgentInfo>[])
476 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
477 }
478
479 public void addSupportedType(int type) {
480 if (mTypeLists[type] != null) {
481 throw new IllegalStateException(
482 "legacy list for type " + type + "already initialized");
483 }
484 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
485 }
486
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700487 public boolean isTypeSupported(int type) {
488 return isNetworkTypeValid(type) && mTypeLists[type] != null;
489 }
490
491 public NetworkAgentInfo getNetworkForType(int type) {
492 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
493 return mTypeLists[type].get(0);
494 } else {
495 return null;
496 }
497 }
498
Robert Greenwalt8d482522015-06-24 13:23:42 -0700499 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900500 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900501 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700502 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900503 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900504 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900505 }
506 }
507
508 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700509 public void add(int type, NetworkAgentInfo nai) {
510 if (!isTypeSupported(type)) {
511 return; // Invalid network type.
512 }
513 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
514
515 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
516 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700517 return;
518 }
519
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900520 list.add(nai);
521
522 // 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 +0900523 final boolean isDefaultNetwork = isDefaultNetwork(nai);
524 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700525 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
526 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700527 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700528 }
529
Lorenzo Colittia793a672014-07-31 23:20:17 +0900530 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900531 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900532 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
533 if (list == null || list.isEmpty()) {
534 return;
535 }
536
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900537 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900538
539 if (!list.remove(nai)) {
540 return;
541 }
542
Robert Greenwalt8d482522015-06-24 13:23:42 -0700543 final DetailedState state = DetailedState.DISCONNECTED;
544
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900545 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700546 maybeLogBroadcast(nai, state, type, wasDefault);
547 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548 }
549
550 if (!list.isEmpty() && wasFirstNetwork) {
551 if (DBG) log("Other network available for type " + type +
552 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900553 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700554 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
555 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900556 }
557 }
558
559 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900560 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
561 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700562 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900563 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700564 }
565 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700566
Robert Greenwalt8d482522015-06-24 13:23:42 -0700567 // send out another legacy broadcast - currently only used for suspend/unsuspend
568 // toggle
569 public void update(NetworkAgentInfo nai) {
570 final boolean isDefault = isDefaultNetwork(nai);
571 final DetailedState state = nai.networkInfo.getDetailedState();
572 for (int type = 0; type < mTypeLists.length; type++) {
573 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700574 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700575 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700576 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700577 maybeLogBroadcast(nai, state, type, isDefault);
578 sendLegacyNetworkBroadcast(nai, state, type);
579 }
580 }
581 }
582
Lorenzo Colittia793a672014-07-31 23:20:17 +0900583 private String naiToString(NetworkAgentInfo nai) {
584 String name = (nai != null) ? nai.name() : "null";
585 String state = (nai.networkInfo != null) ?
586 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
587 "???/???";
588 return name + " " + state;
589 }
590
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700591 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900592 pw.println("mLegacyTypeTracker:");
593 pw.increaseIndent();
594 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700595 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900596 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700597 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900598 pw.println();
599 pw.println("Current state:");
600 pw.increaseIndent();
601 for (int type = 0; type < mTypeLists.length; type++) {
602 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
603 for (NetworkAgentInfo nai : mTypeLists[type]) {
604 pw.println(type + " " + naiToString(nai));
605 }
606 }
607 pw.decreaseIndent();
608 pw.decreaseIndent();
609 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700610 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900611
612 // This class needs its own log method because it has a different TAG.
613 private void log(String s) {
614 Slog.d(TAG, s);
615 }
616
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700617 }
618 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
619
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900620 @VisibleForTesting
621 protected HandlerThread createHandlerThread() {
622 return new HandlerThread("ConnectivityServiceThread");
623 }
624
Jeff Sharkey899223b2012-08-04 15:24:58 -0700625 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700626 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800627 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800628
Erik Klineda4bfa82015-04-30 12:58:40 +0900629 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900630 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
631 new Binder(), NetworkRequestInfo.REQUEST);
632 mNetworkRequests.put(mDefaultRequest, defaultNRI);
633 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900634
635 mDefaultMobileDataRequest = createInternetRequestForTransport(
636 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700637
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900638 mHandlerThread = createHandlerThread();
639 mHandlerThread.start();
640 mHandler = new InternalHandler(mHandlerThread.getLooper());
641 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700642
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800643 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800644 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
645 String id = Settings.Secure.getString(context.getContentResolver(),
646 Settings.Secure.ANDROID_ID);
647 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700648 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800649 SystemProperties.set("net.hostname", name);
650 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800651 }
652
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700653 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700654 String dns = Settings.Global.getString(context.getContentResolver(),
655 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700656 if (dns == null || dns.length() == 0) {
657 dns = context.getResources().getString(
658 com.android.internal.R.string.config_default_dns_server);
659 }
660 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800661 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
662 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800663 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700664 }
665
Jeremy Joslin79294842014-12-03 17:15:28 -0800666 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
667 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
668
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700669 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700670 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800671 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700672 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700673 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700674 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700675
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700676 try {
677 mPolicyManager.registerListener(mPolicyListener);
678 } catch (RemoteException e) {
679 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700680 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700681 }
682
683 final PowerManager powerManager = (PowerManager) context.getSystemService(
684 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700685 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
686 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
687 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800688 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700689
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700690 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700691
Wink Saville51f456f2013-04-23 14:26:51 -0700692 // TODO: What is the "correct" way to do determine if this is a wifi only device?
693 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
694 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700695 String[] naStrings = context.getResources().getStringArray(
696 com.android.internal.R.array.networkAttributes);
697 for (String naString : naStrings) {
698 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700699 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700700 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700701 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800702 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700703 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700704 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700705 }
Wink Saville51f456f2013-04-23 14:26:51 -0700706 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
707 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
708 n.type);
709 continue;
710 }
Wink Saville975c8482011-04-07 14:23:45 -0700711 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800712 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700713 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700714 continue;
715 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700716 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700717
Wink Saville975c8482011-04-07 14:23:45 -0700718 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700719 mNetworksDefined++;
720 } catch(Exception e) {
721 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700722 }
723 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700724
725 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
726 if (mNetConfigs[TYPE_VPN] == null) {
727 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
728 // don't need to add TYPE_VPN to mNetConfigs.
729 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
730 mNetworksDefined++; // used only in the log() statement below.
731 }
732
Wink Saville5e56bc52013-07-29 15:00:57 -0700733 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700734
Robert Greenwalt50393202011-06-21 17:26:14 -0700735 mProtectedNetworks = new ArrayList<Integer>();
736 int[] protectedNetworks = context.getResources().getIntArray(
737 com.android.internal.R.array.config_protectedNetworks);
738 for (int p : protectedNetworks) {
739 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
740 mProtectedNetworks.add(p);
741 } else {
742 if (DBG) loge("Ignoring protectedNetwork " + p);
743 }
744 }
745
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700746 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
747 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700748
Robert Greenwaltfab501672014-07-23 11:44:01 -0700749 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800750
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700751 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
752
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700753 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700754 IntentFilter intentFilter = new IntentFilter();
755 intentFilter.addAction(Intent.ACTION_USER_STARTING);
756 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700757 intentFilter.addAction(Intent.ACTION_USER_ADDED);
758 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700759 mContext.registerReceiverAsUser(
760 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900761
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700762 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700763 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700764 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700765 } catch (RemoteException e) {
766 loge("Error registering observer :" + e);
767 }
768
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700769 if (DBG) {
770 mInetLog = new ArrayList();
771 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700772
Erik Klineda4bfa82015-04-30 12:58:40 +0900773 mSettingsObserver = new SettingsObserver(mContext, mHandler);
774 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800775
John Spurlockbf991a82013-06-24 14:20:23 -0400776 mDataConnectionStats = new DataConnectionStats(mContext);
777 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400778
Jason Monkdecd2952013-10-10 14:02:51 -0400779 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700780
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400781 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900782
783 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800784 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700785
Erik Klineda4bfa82015-04-30 12:58:40 +0900786 private NetworkRequest createInternetRequestForTransport(int transportType) {
787 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900788 netCap.addCapability(NET_CAPABILITY_INTERNET);
789 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900790 if (transportType > -1) {
791 netCap.addTransportType(transportType);
792 }
793 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
794 }
795
796 private void handleMobileDataAlwaysOn() {
797 final boolean enable = (Settings.Global.getInt(
798 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
799 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
800 if (enable == isEnabled) {
801 return; // Nothing to do.
802 }
803
804 if (enable) {
805 handleRegisterNetworkRequest(new NetworkRequestInfo(
806 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
807 } else {
808 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
809 }
810 }
811
812 private void registerSettingsCallbacks() {
813 // Watch for global HTTP proxy changes.
814 mSettingsObserver.observe(
815 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
816 EVENT_APPLY_GLOBAL_HTTP_PROXY);
817
818 // Watch for whether or not to keep mobile data always on.
819 mSettingsObserver.observe(
820 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
821 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
822 }
823
Robert Greenwalt34524f02014-05-18 16:22:10 -0700824 private synchronized int nextNetworkRequestId() {
825 return mNextNetworkRequestId++;
826 }
827
Paul Jensen67b0b072015-06-10 11:22:17 -0400828 @VisibleForTesting
829 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400830 synchronized (mNetworkForNetId) {
831 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
832 int netId = mNextNetId;
833 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
834 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500835 if (!mNetIdInUse.get(netId)) {
836 mNetIdInUse.put(netId, true);
837 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400838 }
839 }
840 }
841 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700842 }
843
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800844 private NetworkState getFilteredNetworkState(int networkType, int uid) {
845 NetworkInfo info = null;
846 LinkProperties lp = null;
847 NetworkCapabilities nc = null;
848 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800849 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800850
851 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
852 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
853 if (nai != null) {
854 synchronized (nai) {
855 info = new NetworkInfo(nai.networkInfo);
856 lp = new LinkProperties(nai.linkProperties);
857 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400858 // Network objects are outwardly immutable so there is no point to duplicating.
859 // Duplicating also precludes sharing socket factories and connection pools.
860 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800861 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800862 }
863 info.setType(networkType);
864 } else {
865 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
866 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
867 info.setIsAvailable(true);
868 lp = new LinkProperties();
869 nc = new NetworkCapabilities();
870 network = null;
871 }
872 info = getFilteredNetworkInfo(info, lp, uid);
873 }
874
Jeff Sharkey32566012014-12-02 18:30:14 -0800875 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400876 }
877
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800878 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
879 if (network == null) {
880 return null;
881 }
882 synchronized (mNetworkForNetId) {
883 return mNetworkForNetId.get(network.netId);
884 }
885 };
886
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900887 private Network[] getVpnUnderlyingNetworks(int uid) {
888 if (!mLockdownEnabled) {
889 int user = UserHandle.getUserId(uid);
890 synchronized (mVpns) {
891 Vpn vpn = mVpns.get(user);
892 if (vpn != null && vpn.appliesToUid(uid)) {
893 return vpn.getUnderlyingNetworks();
894 }
895 }
896 }
897 return null;
898 }
899
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800900 private NetworkState getUnfilteredActiveNetworkState(int uid) {
901 NetworkInfo info = null;
902 LinkProperties lp = null;
903 NetworkCapabilities nc = null;
904 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800905 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800906
Paul Jensen85cf78e2015-06-25 13:25:07 -0400907 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800908
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900909 final Network[] networks = getVpnUnderlyingNetworks(uid);
910 if (networks != null) {
911 // getUnderlyingNetworks() returns:
912 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
913 // empty array => the VPN explicitly said "no default network".
914 // non-empty array => the VPN specified one or more default networks; we use the
915 // first one.
916 if (networks.length > 0) {
917 nai = getNetworkAgentInfoForNetwork(networks[0]);
918 } else {
919 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800920 }
921 }
922
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800923 if (nai != null) {
924 synchronized (nai) {
925 info = new NetworkInfo(nai.networkInfo);
926 lp = new LinkProperties(nai.linkProperties);
927 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400928 // Network objects are outwardly immutable so there is no point to duplicating.
929 // Duplicating also precludes sharing socket factories and connection pools.
930 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800931 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800932 }
933 }
934
Jeff Sharkey32566012014-12-02 18:30:14 -0800935 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400936 }
937
938 /**
939 * Check if UID should be blocked from using the network with the given LinkProperties.
940 */
941 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700942 final boolean networkCostly;
943 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700944
Robert Greenwalt12e67352014-05-13 21:41:06 -0700945 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700946 synchronized (mRulesLock) {
947 networkCostly = mMeteredIfaces.contains(iface);
948 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700949 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700950
Amith Yamasani15e472352015-04-24 19:06:07 -0700951 if ((uidRules & RULE_REJECT_ALL) != 0
952 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700953 return true;
954 }
955
956 // no restrictive rules; network is visible
957 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700958 }
959
960 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700961 * Return a filtered {@link NetworkInfo}, potentially marked
962 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800963 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700964 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800965 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
966 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400967 // network is blocked; clone and override state
968 info = new NetworkInfo(info);
969 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900970 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900971 log("returning Blocked NetworkInfo for ifname=" +
972 lp.getInterfaceName() + ", uid=" + uid);
973 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700974 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800975 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700976 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900977 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700978 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700979 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700980 }
981
982 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800983 * Return NetworkInfo for the active (i.e., connected) network interface.
984 * It is assumed that at most one network is active at a time. If more
985 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700986 * @return the info for the active network, or {@code null} if none is
987 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700989 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800990 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700991 enforceAccessPermission();
992 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 NetworkState state = getUnfilteredActiveNetworkState(uid);
994 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800995 }
996
Paul Jensen31a94f42015-02-13 14:18:39 -0500997 @Override
998 public Network getActiveNetwork() {
999 enforceAccessPermission();
1000 final int uid = Binder.getCallingUid();
1001 final int user = UserHandle.getUserId(uid);
1002 int vpnNetId = NETID_UNSET;
1003 synchronized (mVpns) {
1004 final Vpn vpn = mVpns.get(user);
1005 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1006 }
1007 NetworkAgentInfo nai;
1008 if (vpnNetId != NETID_UNSET) {
1009 synchronized (mNetworkForNetId) {
1010 nai = mNetworkForNetId.get(vpnNetId);
1011 }
1012 if (nai != null) return nai.network;
1013 }
1014 nai = getDefaultNetwork();
1015 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1016 return nai != null ? nai.network : null;
1017 }
1018
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001019 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1020 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001021 final int uid = Binder.getCallingUid();
1022 NetworkState state = getUnfilteredActiveNetworkState(uid);
1023 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001024 }
1025
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001026 @Override
1027 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1028 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 NetworkState state = getUnfilteredActiveNetworkState(uid);
1030 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001031 }
1032
1033 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 public NetworkInfo getNetworkInfo(int networkType) {
1035 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001036 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001037 if (getVpnUnderlyingNetworks(uid) != null) {
1038 // A VPN is active, so we may need to return one of its underlying networks. This
1039 // information is not available in LegacyTypeTracker, so we have to get it from
1040 // getUnfilteredActiveNetworkState.
1041 NetworkState state = getUnfilteredActiveNetworkState(uid);
1042 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1043 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1044 }
1045 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001046 NetworkState state = getFilteredNetworkState(networkType, uid);
1047 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001048 }
1049
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001050 @Override
1051 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1052 enforceAccessPermission();
1053 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001055 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1056 if (nai != null) {
1057 synchronized (nai) {
1058 info = new NetworkInfo(nai.networkInfo);
1059 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001060 }
1061 }
1062 return info;
1063 }
1064
1065 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001066 public NetworkInfo[] getAllNetworkInfo() {
1067 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001068 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001069 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1070 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001071 NetworkInfo info = getNetworkInfo(networkType);
1072 if (info != null) {
1073 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001074 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001075 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001076 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001077 }
1078
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001079 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001080 public Network getNetworkForType(int networkType) {
1081 enforceAccessPermission();
1082 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001083 NetworkState state = getFilteredNetworkState(networkType, uid);
1084 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1085 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001086 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001087 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001088 }
1089
1090 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001091 public Network[] getAllNetworks() {
1092 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001093 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001094 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001095 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001096 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001097 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001098 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001099 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001100 }
1101
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001102 @Override
1103 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1104 // The basic principle is: if an app's traffic could possibly go over a
1105 // network, without the app doing anything multinetwork-specific,
1106 // (hence, by "default"), then include that network's capabilities in
1107 // the array.
1108 //
1109 // In the normal case, app traffic only goes over the system's default
1110 // network connection, so that's the only network returned.
1111 //
1112 // With a VPN in force, some app traffic may go into the VPN, and thus
1113 // over whatever underlying networks the VPN specifies, while other app
1114 // traffic may go over the system default network (e.g.: a split-tunnel
1115 // VPN, or an app disallowed by the VPN), so the set of networks
1116 // returned includes the VPN's underlying networks and the system
1117 // default.
1118 enforceAccessPermission();
1119
1120 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1121
1122 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001123 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001124 if (nc != null) {
1125 result.put(nai.network, nc);
1126 }
1127
1128 if (!mLockdownEnabled) {
1129 synchronized (mVpns) {
1130 Vpn vpn = mVpns.get(userId);
1131 if (vpn != null) {
1132 Network[] networks = vpn.getUnderlyingNetworks();
1133 if (networks != null) {
1134 for (Network network : networks) {
1135 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001136 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001137 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001138 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001139 }
1140 }
1141 }
1142 }
1143 }
1144 }
1145
1146 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1147 out = result.values().toArray(out);
1148 return out;
1149 }
1150
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001151 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001152 public boolean isNetworkSupported(int networkType) {
1153 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001154 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001155 }
1156
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001157 /**
1158 * Return LinkProperties for the active (i.e., connected) default
1159 * network interface. It is assumed that at most one default network
1160 * is active at a time. If more than one is active, it is indeterminate
1161 * which will be returned.
1162 * @return the ip properties for the active network, or {@code null} if
1163 * none is active
1164 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001165 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001166 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001167 enforceAccessPermission();
1168 final int uid = Binder.getCallingUid();
1169 NetworkState state = getUnfilteredActiveNetworkState(uid);
1170 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001171 }
1172
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001173 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001174 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001175 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001176 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1177 if (nai != null) {
1178 synchronized (nai) {
1179 return new LinkProperties(nai.linkProperties);
1180 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001181 }
1182 return null;
1183 }
1184
Robert Greenwalt12e67352014-05-13 21:41:06 -07001185 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001186 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001187 public LinkProperties getLinkProperties(Network network) {
1188 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001189 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001190 if (nai != null) {
1191 synchronized (nai) {
1192 return new LinkProperties(nai.linkProperties);
1193 }
1194 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001195 return null;
1196 }
1197
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001198 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001199 if (nai != null) {
1200 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001201 if (nai.networkCapabilities != null) {
1202 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001203 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001204 }
1205 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001206 return null;
1207 }
1208
1209 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001210 public NetworkCapabilities getNetworkCapabilities(Network network) {
1211 enforceAccessPermission();
1212 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1213 }
1214
1215 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001216 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001217 // Require internal since we're handing out IMSI details
1218 enforceConnectivityInternalPermission();
1219
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001220 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001221 for (Network network : getAllNetworks()) {
1222 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1223 if (nai != null) {
1224 synchronized (nai) {
1225 final String subscriberId = (nai.networkMisc != null)
1226 ? nai.networkMisc.subscriberId : null;
1227 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1228 nai.networkCapabilities, network, subscriberId, null));
1229 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001230 }
1231 }
1232 return result.toArray(new NetworkState[result.size()]);
1233 }
1234
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001235 @Override
1236 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1237 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001238 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001239 final long token = Binder.clearCallingIdentity();
1240 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001241 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1242 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001243 try {
1244 return mPolicyManager.getNetworkQuotaInfo(state);
1245 } catch (RemoteException e) {
1246 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001247 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001248 return null;
1249 } finally {
1250 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001251 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001252 }
1253
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001254 @Override
1255 public boolean isActiveNetworkMetered() {
1256 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001257 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001258 final long token = Binder.clearCallingIdentity();
1259 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001260 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001261 } finally {
1262 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001263 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001264 }
1265
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001266 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1267 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1268 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001269 try {
1270 return mPolicyManager.isNetworkMetered(state);
1271 } catch (RemoteException e) {
1272 }
1273 }
1274 return false;
1275 }
1276
Jeff Sharkey216c1812012-08-05 14:29:23 -07001277 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1278 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001279 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001280 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001281 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001282 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001283 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001284
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001285 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001286 * Ensure that a network route exists to deliver traffic to the specified
1287 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001288 * @param networkType the type of the network over which traffic to the
1289 * specified host is to be routed
1290 * @param hostAddress the IP address of the host to which the route is
1291 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 * @return {@code true} on success, {@code false} on failure
1293 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001294 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001295 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001296 if (mProtectedNetworks.contains(networkType)) {
1297 enforceConnectivityInternalPermission();
1298 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001299
Chad Brubakerc0234532014-02-14 13:24:29 -08001300 InetAddress addr;
1301 try {
1302 addr = InetAddress.getByAddress(hostAddress);
1303 } catch (UnknownHostException e) {
1304 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1305 return false;
1306 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001307
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001308 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001309 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001310 return false;
1311 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001312
1313 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1314 if (nai == null) {
1315 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1316 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1317 } else {
1318 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1319 }
1320 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001321 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001322
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001323 DetailedState netState;
1324 synchronized (nai) {
1325 netState = nai.networkInfo.getDetailedState();
1326 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001327
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001328 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001329 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001330 log("requestRouteToHostAddress on down network "
1331 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001332 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001333 }
1334 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001335 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001336
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001337 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001338 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001339 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001340 LinkProperties lp;
1341 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001342 synchronized (nai) {
1343 lp = nai.linkProperties;
1344 netId = nai.network.netId;
1345 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001346 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001347 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1348 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001349 } finally {
1350 Binder.restoreCallingIdentity(token);
1351 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001352 }
1353
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001354 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001355 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001356 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001357 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001358 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001359 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001360 if (bestRoute.getGateway().equals(addr)) {
1361 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001362 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001363 } else {
1364 // if we will connect to this through another route, add a direct route
1365 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001366 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001367 }
1368 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001369 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001370 try {
1371 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1372 } catch (Exception e) {
1373 // never crash - catch them all
1374 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001375 return false;
1376 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001377 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001378 }
1379
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001380 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1381 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001382 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001383 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001384 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001385 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001386 }
1387
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001388 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001389 // skip update when we've already applied rules
1390 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1391 if (oldRules == uidRules) return;
1392
1393 mUidRules.put(uid, uidRules);
1394 }
1395
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001396 // TODO: notify UID when it has requested targeted updates
1397 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001398
1399 @Override
1400 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001401 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001402 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001403 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001404 }
1405
1406 synchronized (mRulesLock) {
1407 mMeteredIfaces.clear();
1408 for (String iface : meteredIfaces) {
1409 mMeteredIfaces.add(iface);
1410 }
1411 }
1412 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001413
1414 @Override
1415 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1416 // caller is NPMS, since we only register with them
1417 if (LOGD_RULES) {
1418 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1419 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001420 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001421 };
1422
Robin Lee3b3dd942015-05-12 18:14:58 +01001423 /**
1424 * Require that the caller is either in the same user or has appropriate permission to interact
1425 * across users.
1426 *
1427 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1428 */
1429 private void enforceCrossUserPermission(int userId) {
1430 if (userId == UserHandle.getCallingUserId()) {
1431 // Not a cross-user call.
1432 return;
1433 }
1434 mContext.enforceCallingOrSelfPermission(
1435 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1436 "ConnectivityService");
1437 }
1438
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001439 private void enforceInternetPermission() {
1440 mContext.enforceCallingOrSelfPermission(
1441 android.Manifest.permission.INTERNET,
1442 "ConnectivityService");
1443 }
1444
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001445 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001446 mContext.enforceCallingOrSelfPermission(
1447 android.Manifest.permission.ACCESS_NETWORK_STATE,
1448 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001449 }
1450
1451 private void enforceChangePermission() {
Billy Laua7238a32015-08-01 12:45:02 +01001452 int uid = Binder.getCallingUid();
1453 Settings.checkAndNoteChangeNetworkStateOperation(mContext, uid, Settings
1454 .getPackageNameForUid(mContext, uid), true);
1455
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 }
1457
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001458 private void enforceTetherAccessPermission() {
1459 mContext.enforceCallingOrSelfPermission(
1460 android.Manifest.permission.ACCESS_NETWORK_STATE,
1461 "ConnectivityService");
1462 }
1463
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001464 private void enforceConnectivityInternalPermission() {
1465 mContext.enforceCallingOrSelfPermission(
1466 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1467 "ConnectivityService");
1468 }
1469
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001470 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001471 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001472 }
1473
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001474 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001475 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001476 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001477 }
1478
1479 private void sendInetConditionBroadcast(NetworkInfo info) {
1480 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1481 }
1482
Wink Saville628b0852011-08-04 15:01:58 -07001483 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001484 if (mLockdownTracker != null) {
1485 info = mLockdownTracker.augmentNetworkInfo(info);
1486 }
1487
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001488 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001489 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001490 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 if (info.isFailover()) {
1492 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1493 info.setFailover(false);
1494 }
1495 if (info.getReason() != null) {
1496 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1497 }
1498 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001499 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1500 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001501 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001502 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001503 return intent;
1504 }
1505
1506 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1507 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1508 }
1509
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001510 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001511 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1512 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1513 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001514 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001515 final long ident = Binder.clearCallingIdentity();
1516 try {
1517 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1518 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1519 } finally {
1520 Binder.restoreCallingIdentity(ident);
1521 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001522 }
1523
Mike Lockwood0f79b542009-08-14 14:18:49 -04001524 private void sendStickyBroadcast(Intent intent) {
1525 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001526 if (!mSystemReady) {
1527 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001528 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001529 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001530 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001531 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001532 }
1533
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001534 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001535 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001536 final NetworkInfo ni = intent.getParcelableExtra(
1537 ConnectivityManager.EXTRA_NETWORK_INFO);
1538 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1539 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1540 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
1541 }
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001542 final IBatteryStats bs = BatteryStatsService.getService();
1543 try {
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001544 bs.noteConnectivityChanged(intent.getIntExtra(
1545 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1546 ni != null ? ni.getState().toString() : "?");
1547 } catch (RemoteException e) {
1548 }
1549 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001550 try {
1551 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1552 } finally {
1553 Binder.restoreCallingIdentity(ident);
1554 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001555 }
1556 }
1557
1558 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001559 loadGlobalProxy();
1560
Mike Lockwood0f79b542009-08-14 14:18:49 -04001561 synchronized(this) {
1562 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001563 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001564 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001565 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001566 }
1567 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001568 // load the global proxy at startup
1569 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001570
1571 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1572 // for user to unlock device.
1573 if (!updateLockdownVpn()) {
1574 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1575 mContext.registerReceiver(mUserPresentReceiver, filter);
1576 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001577
Erik Klineda4bfa82015-04-30 12:58:40 +09001578 // Configure whether mobile data is always on.
1579 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1580
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001581 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001582
1583 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001584 }
1585
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001586 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1587 @Override
1588 public void onReceive(Context context, Intent intent) {
1589 // Try creating lockdown tracker, since user present usually means
1590 // unlocked keystore.
1591 if (updateLockdownVpn()) {
1592 mContext.unregisterReceiver(this);
1593 }
1594 }
1595 };
1596
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001597 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001598 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001599 *
1600 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001601 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001602 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001603 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1604 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001605
1606 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001607 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001608
Robert Greenwalt7b816022014-04-18 15:25:25 -07001609 if (networkAgent.networkCapabilities.hasTransport(
1610 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001611 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1612 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Adam Lesinskied6160d2015-08-18 11:47:07 -07001613 10);
Haoyu Bai04124232012-06-28 15:26:19 -07001614 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001615 } else if (networkAgent.networkCapabilities.hasTransport(
1616 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001617 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1618 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinski06f46cb2015-06-23 13:42:53 -07001619 15);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001620 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001621 } else {
1622 // do not track any other networks
1623 timeout = 0;
1624 }
1625
Robert Greenwalt7b816022014-04-18 15:25:25 -07001626 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001627 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001628 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001629 } catch (Exception e) {
1630 // You shall not crash!
1631 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001632 }
1633 }
1634 }
1635
1636 /**
1637 * Remove data activity tracking when network disconnects.
1638 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001639 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1640 final String iface = networkAgent.linkProperties.getInterfaceName();
1641 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001642
Robert Greenwalt7b816022014-04-18 15:25:25 -07001643 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1644 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001645 try {
1646 // the call fails silently if no idletimer setup for this interface
1647 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001648 } catch (Exception e) {
1649 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001650 }
1651 }
1652 }
1653
1654 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001655 * Reads the network specific MTU size from reources.
1656 * and set it on it's iface.
1657 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001658 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1659 final String iface = newLp.getInterfaceName();
1660 final int mtu = newLp.getMtu();
1661 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1662 if (VDBG) log("identical MTU - not setting");
1663 return;
1664 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001665
Robert Greenwalt43074032014-08-15 17:53:05 -07001666 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001667 loge("Unexpected mtu value: " + mtu + ", " + iface);
1668 return;
1669 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001670
w1997615afd812014-08-05 15:18:11 -07001671 // Cannot set MTU without interface name
1672 if (TextUtils.isEmpty(iface)) {
1673 loge("Setting MTU size with null iface.");
1674 return;
1675 }
1676
Robert Greenwalt7b816022014-04-18 15:25:25 -07001677 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001678 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001679 mNetd.setMtu(iface, mtu);
1680 } catch (Exception e) {
1681 Slog.e(TAG, "exception in setMtu()" + e);
1682 }
1683 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001684
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001685 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001686 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1687
1688 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001689 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001690 protected int getDefaultTcpRwnd() {
1691 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1692 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001693
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001694 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1695 if (isDefaultNetwork(nai) == false) {
1696 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001697 }
1698
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001699 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1700 String[] values = null;
1701 if (tcpBufferSizes != null) {
1702 values = tcpBufferSizes.split(",");
1703 }
1704
1705 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001706 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001707 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1708 values = tcpBufferSizes.split(",");
1709 }
1710
1711 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1712
1713 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001714 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001715
1716 final String prefix = "/sys/kernel/ipv4/tcp_";
1717 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1718 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1719 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1720 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1721 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1722 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1723 mCurrentTcpBufferSizes = tcpBufferSizes;
1724 } catch (IOException e) {
1725 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001726 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001727
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001728 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001729 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001730 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1731 if (rwndValue != 0) {
1732 SystemProperties.set(sysctlKey, rwndValue.toString());
1733 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001734 }
1735
Mattias Falk8b47b362011-08-23 14:15:13 +02001736 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001737 /*
1738 * Tell the VMs to toss their DNS caches
1739 */
1740 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1741 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001742 /*
1743 * Connectivity events can happen before boot has completed ...
1744 */
1745 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001746 final long ident = Binder.clearCallingIdentity();
1747 try {
1748 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1749 } finally {
1750 Binder.restoreCallingIdentity(ident);
1751 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001752 }
1753
Robert Greenwalt562cc542014-05-15 18:07:26 -07001754 @Override
1755 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001756 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1757 NETWORK_RESTORE_DELAY_PROP_NAME);
1758 if(restoreDefaultNetworkDelayStr != null &&
1759 restoreDefaultNetworkDelayStr.length() != 0) {
1760 try {
1761 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1762 } catch (NumberFormatException e) {
1763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001765 // if the system property isn't set, use the value for the apn type
1766 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1767
1768 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1769 (mNetConfigs[networkType] != null)) {
1770 ret = mNetConfigs[networkType].restoreTime;
1771 }
1772 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001773 }
1774
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001775 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001776 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001777 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001778 }
1779 return false;
1780 }
1781
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001782 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001783 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1784 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001785 if (mContext.checkCallingOrSelfPermission(
1786 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001788 pw.println("Permission Denial: can't dump ConnectivityService " +
1789 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1790 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001791 return;
1792 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001793
Erik Kline379747a2015-06-05 17:47:34 +09001794 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001795 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001796 final long DIAG_TIME_MS = 5000;
1797 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1798 // Start gathering diagnostic information.
1799 netDiags.add(new NetworkDiagnostics(
1800 nai.network,
Lorenzo Colitti87cfc702015-07-27 16:35:33 +09001801 new LinkProperties(nai.linkProperties), // Must be a copy.
Erik Kline379747a2015-06-05 17:47:34 +09001802 DIAG_TIME_MS));
1803 }
1804
1805 for (NetworkDiagnostics netDiag : netDiags) {
1806 pw.println();
1807 netDiag.waitForMeasurements();
1808 netDiag.dump(pw);
1809 }
1810
1811 return;
1812 }
1813
Lorenzo Colittie3805462015-06-03 11:18:24 +09001814 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001815 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001816 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001817 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001818 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001819 pw.println();
1820
Paul Jensen85cf78e2015-06-25 13:25:07 -04001821 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001822 pw.print("Active default network: ");
1823 if (defaultNai == null) {
1824 pw.println("none");
1825 } else {
1826 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001827 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001828 pw.println();
1829
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001830 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001831 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001832 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1833 pw.println(nai.toString());
1834 pw.increaseIndent();
1835 pw.println("Requests:");
1836 pw.increaseIndent();
1837 for (int i = 0; i < nai.networkRequests.size(); i++) {
1838 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001839 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001840 pw.decreaseIndent();
1841 pw.println("Lingered:");
1842 pw.increaseIndent();
1843 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1844 pw.decreaseIndent();
1845 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001846 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001847 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001848 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001849
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001850 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001851 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001852 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1853 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001854 }
1855 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001856 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001857
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001858 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001859
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001860 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001861 pw.print("mNetTransitionWakeLock: currently " +
1862 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1863 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1864 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1865 } else {
1866 pw.println(", last requested never");
1867 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001868 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001869
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001870 pw.println();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001871 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001872
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001873 pw.println();
1874 mKeepaliveTracker.dump(pw);
1875
Lorenzo Colittie3805462015-06-03 11:18:24 +09001876 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001877 pw.println();
1878 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001879 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001880 for(int i = 0; i < mInetLog.size(); i++) {
1881 pw.println(mInetLog.get(i));
1882 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001883 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001884 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001885
1886 if (argsContain(args, "--short") == false) {
1887 pw.println();
1888 synchronized (mValidationLogs) {
1889 pw.println("mValidationLogs (most recent first):");
1890 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1891 pw.println(p.first);
1892 pw.increaseIndent();
1893 p.second.dump(fd, pw, args);
1894 pw.decreaseIndent();
1895 }
1896 }
Erik Kline7523eb32015-07-09 18:24:03 +09001897
1898 pw.println();
1899 pw.println("mNetworkRequestInfoLogs (most recent first):");
1900 pw.increaseIndent();
1901 mNetworkRequestInfoLogs.reverseDump(fd, pw, args);
1902 pw.decreaseIndent();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001903 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001904 }
1905
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001906 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001907 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001908 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001909 if (officialNai != null && officialNai.equals(nai)) return true;
1910 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001911 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001912 " - " + nai);
1913 }
1914 return false;
1915 }
1916
Paul Jensenc8b9a742014-09-30 15:37:41 -04001917 private boolean isRequest(NetworkRequest request) {
1918 return mNetworkRequests.get(request).isRequest;
1919 }
1920
Robert Greenwalt42acef32009-08-12 16:08:25 -07001921 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001922 private class NetworkStateTrackerHandler extends Handler {
1923 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001924 super(looper);
1925 }
1926
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001927 @Override
1928 public void handleMessage(Message msg) {
1929 NetworkInfo info;
1930 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001931 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001932 handleAsyncChannelHalfConnect(msg);
1933 break;
1934 }
1935 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1936 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1937 if (nai != null) nai.asyncChannel.disconnect();
1938 break;
1939 }
1940 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1941 handleAsyncChannelDisconnected(msg);
1942 break;
1943 }
1944 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1945 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1946 if (nai == null) {
1947 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1948 } else {
Paul Jensen1c7ba022015-06-16 14:27:36 -04001949 final NetworkCapabilities networkCapabilities =
1950 (NetworkCapabilities)msg.obj;
1951 if (networkCapabilities.hasCapability(NET_CAPABILITY_CAPTIVE_PORTAL) ||
1952 networkCapabilities.hasCapability(NET_CAPABILITY_VALIDATED)) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09001953 Slog.wtf(TAG, "BUG: " + nai + " has CS-managed capability.");
Paul Jensen1c7ba022015-06-16 14:27:36 -04001954 }
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09001955 if (nai.created && !nai.networkCapabilities.equalImmutableCapabilities(
1956 networkCapabilities)) {
1957 Slog.wtf(TAG, "BUG: " + nai + " changed immutable capabilities: "
1958 + nai.networkCapabilities + " -> " + networkCapabilities);
1959 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04001960 updateCapabilities(nai, networkCapabilities);
Robert Greenwalte049c232014-04-11 15:53:27 -07001961 }
1962 break;
1963 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001964 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1965 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1966 if (nai == null) {
1967 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1968 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001969 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001970 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001971 "; created=" + nai.created);
1972 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001973 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001974 synchronized (nai) {
1975 nai.linkProperties = (LinkProperties)msg.obj;
1976 }
Paul Jenseneec75412014-08-04 12:21:19 -04001977 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001978 }
1979 break;
1980 }
1981 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1982 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1983 if (nai == null) {
1984 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1985 break;
1986 }
1987 info = (NetworkInfo) msg.obj;
1988 updateNetworkInfo(nai, info);
1989 break;
1990 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001991 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1992 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1993 if (nai == null) {
1994 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1995 break;
1996 }
1997 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001998 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001999 break;
2000 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002001 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
2002 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2003 if (nai == null) {
2004 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
2005 break;
2006 }
2007 try {
2008 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002009 } catch (Exception e) {
2010 // Never crash!
2011 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04002012 }
2013 break;
2014 }
2015 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
2016 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2017 if (nai == null) {
2018 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
2019 break;
2020 }
2021 try {
2022 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07002023 } catch (Exception e) {
2024 // Never crash!
2025 loge("Exception in removeVpnUidRanges: " + e);
2026 }
2027 break;
2028 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002029 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
2030 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2031 if (nai == null) {
2032 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
2033 break;
2034 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002035 if (nai.created && !nai.networkMisc.explicitlySelected) {
2036 loge("ERROR: created network explicitly selected.");
2037 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07002038 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002039 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07002040 break;
2041 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002042 case NetworkAgent.EVENT_PACKET_KEEPALIVE: {
2043 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2044 if (nai == null) {
2045 loge("EVENT_PACKET_KEEPALIVE from unknown NetworkAgent");
2046 break;
2047 }
2048 mKeepaliveTracker.handleEventPacketKeepalive(nai, msg);
2049 break;
2050 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04002051 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002052 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002053 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
2054 final boolean valid =
2055 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002056 if (DBG) log(nai.name() + " validation " + (valid ? " passed" : "failed"));
2057 if (valid != nai.lastValidated) {
2058 final int oldScore = nai.getCurrentScore();
Paul Jensen1c7ba022015-06-16 14:27:36 -04002059 nai.lastValidated = valid;
2060 nai.everValidated |= valid;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002061 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen1c7ba022015-06-16 14:27:36 -04002062 // If score has changed, rebroadcast to NetworkFactories. b/17726566
2063 if (oldScore != nai.getCurrentScore()) sendUpdatedScoreToFactories(nai);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002064 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002065 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002066 // Let the NetworkAgent know the state of its network
2067 nai.asyncChannel.sendMessage(
2068 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2069 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2070 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002071 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002072 break;
2073 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002074 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002075 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002076 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2077 handleLingerComplete(nai);
2078 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002079 break;
2080 }
Paul Jensen869868be2014-05-15 10:33:05 -04002081 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002082 final int netId = msg.arg2;
Paul Jensen3d194ea2015-06-16 14:27:36 -04002083 final boolean visible = (msg.arg1 != 0);
2084 final NetworkAgentInfo nai;
2085 synchronized (mNetworkForNetId) {
2086 nai = mNetworkForNetId.get(netId);
2087 }
2088 // If captive portal status has changed, update capabilities.
2089 if (nai != null && (visible != nai.lastCaptivePortalDetected)) {
2090 nai.lastCaptivePortalDetected = visible;
2091 nai.everCaptivePortalDetected |= visible;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002092 updateCapabilities(nai, nai.networkCapabilities);
Paul Jensen3d194ea2015-06-16 14:27:36 -04002093 }
2094 if (!visible) {
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002095 setProvNotificationVisibleIntent(false, netId, null, 0, null, null, false);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002096 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04002097 if (nai == null) {
2098 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2099 break;
2100 }
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002101 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002102 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(),
2103 (PendingIntent)msg.obj, nai.networkMisc.explicitlySelected);
Paul Jensen869868be2014-05-15 10:33:05 -04002104 }
Paul Jensen869868be2014-05-15 10:33:05 -04002105 break;
2106 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002107 }
2108 }
2109 }
2110
Paul Jensen85cf78e2015-06-25 13:25:07 -04002111 private void linger(NetworkAgentInfo nai) {
2112 nai.lingering = true;
2113 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
2114 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
2115 }
2116
Paul Jensen0cc17322014-11-25 15:26:53 -05002117 // Cancel any lingering so the linger timeout doesn't teardown a network.
2118 // This should be called when a network begins satisfying a NetworkRequest.
2119 // Note: depending on what state the NetworkMonitor is in (e.g.,
2120 // if it's awaiting captive portal login, or if validation failed), this
2121 // may trigger a re-evaluation of the network.
2122 private void unlinger(NetworkAgentInfo nai) {
Paul Jensene0988542015-06-25 15:30:08 -04002123 nai.networkLingered.clear();
2124 if (!nai.lingering) return;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002125 nai.lingering = false;
Paul Jensen0cc17322014-11-25 15:26:53 -05002126 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002127 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2128 }
2129
Robert Greenwalt7b816022014-04-18 15:25:25 -07002130 private void handleAsyncChannelHalfConnect(Message msg) {
2131 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002132 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2134 if (VDBG) log("NetworkFactory connected");
2135 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002136 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002137 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002138 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002139 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002140 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002141 }
2142 } else {
2143 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002144 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002145 }
2146 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2147 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2148 if (VDBG) log("NetworkAgent connected");
2149 // A network agent has requested a connection. Establish the connection.
2150 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2151 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2152 } else {
2153 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002154 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002155 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002156 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002157 synchronized (mNetworkForNetId) {
2158 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002159 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002160 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002161 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002162 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002163 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002164 }
2165 }
2166 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002167
Robert Greenwalt7b816022014-04-18 15:25:25 -07002168 private void handleAsyncChannelDisconnected(Message msg) {
2169 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2170 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002171 if (DBG) {
2172 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2173 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002174 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002175 // TODO - if we move the logic to the network agent (have them disconnect
2176 // because they lost all their requests or because their score isn't good)
2177 // then they would disconnect organically, report their new state and then
2178 // disconnect the channel.
2179 if (nai.networkInfo.isConnected()) {
2180 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2181 null, null);
2182 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002183 final boolean wasDefault = isDefaultNetwork(nai);
2184 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002185 mDefaultInetConditionPublished = 0;
2186 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002187 notifyIfacesChanged();
Paul Jensencf4c2c62015-07-01 14:16:32 -04002188 // TODO - we shouldn't send CALLBACK_LOST to requests that can be satisfied
2189 // by other networks that are already connected. Perhaps that can be done by
2190 // sending all CALLBACK_LOST messages (for requests, not listens) at the end
2191 // of rematchAllNetworksAndRequests
Robert Greenwalt9258c642014-03-26 16:47:06 -07002192 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002193 mKeepaliveTracker.handleStopAllKeepalives(nai,
2194 ConnectivityManager.PacketKeepalive.ERROR_INVALID_NETWORK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002195 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002196 mNetworkAgentInfos.remove(msg.replyTo);
2197 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002198 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002199 // Remove the NetworkAgent, but don't mark the netId as
2200 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002201 mNetworkForNetId.remove(nai.network.netId);
2202 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002203 // Remove all previously satisfied requests.
Robert Greenwalt7b816022014-04-18 15:25:25 -07002204 for (int i = 0; i < nai.networkRequests.size(); i++) {
2205 NetworkRequest request = nai.networkRequests.valueAt(i);
2206 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2207 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
2208 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002209 sendUpdatedScoreToFactories(request, 0);
2210 }
2211 }
2212 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2213 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002214 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002215 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002216 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002217 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensen85cf78e2015-06-25 13:25:07 -04002218 rematchAllNetworksAndRequests(null, 0);
Paul Jensen62d30802015-06-17 14:42:30 -04002219 if (nai.created) {
2220 // Tell netd to clean up the configuration for this network
2221 // (routing rules, DNS, etc).
2222 // This may be slow as it requires a lot of netd shelling out to ip and
2223 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2224 // after we've rematched networks with requests which should make a potential
2225 // fallback network the default or requested a new network from the
2226 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2227 // long time.
2228 try {
2229 mNetd.removeNetwork(nai.network.netId);
2230 } catch (Exception e) {
2231 loge("Exception removing network: " + e);
2232 }
2233 }
2234 synchronized (mNetworkForNetId) {
2235 mNetIdInUse.delete(nai.network.netId);
2236 }
2237 } else {
2238 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2239 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002240 }
2241 }
2242
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002243 // If this method proves to be too slow then we can maintain a separate
2244 // pendingIntent => NetworkRequestInfo map.
2245 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2246 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2247 Intent intent = pendingIntent.getIntent();
2248 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2249 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2250 if (existingPendingIntent != null &&
2251 existingPendingIntent.getIntent().filterEquals(intent)) {
2252 return entry.getValue();
2253 }
2254 }
2255 return null;
2256 }
2257
2258 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2259 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2260
2261 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2262 if (existingRequest != null) { // remove the existing request.
2263 if (DBG) log("Replacing " + existingRequest.request + " with "
2264 + nri.request + " because their intents matched.");
2265 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2266 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002267 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002268 }
2269
Erik Klineda4bfa82015-04-30 12:58:40 +09002270 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002271 mNetworkRequests.put(nri.request, nri);
Erik Kline7523eb32015-07-09 18:24:03 +09002272 mNetworkRequestInfoLogs.log("REGISTER " + nri);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002273 if (!nri.isRequest) {
2274 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002275 if (nri.request.networkCapabilities.hasSignalStrength() &&
2276 network.satisfiesImmutableCapabilitiesOf(nri.request)) {
2277 updateSignalStrengthThresholds(network, "REGISTER", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002278 }
2279 }
2280 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04002281 rematchAllNetworksAndRequests(null, 0);
2282 if (nri.isRequest && mNetworkForRequestId.get(nri.request.requestId) == null) {
2283 sendUpdatedScoreToFactories(nri.request, 0);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002284 }
2285 }
2286
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002287 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2288 int callingUid) {
2289 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2290 if (nri != null) {
2291 handleReleaseNetworkRequest(nri.request, callingUid);
2292 }
2293 }
2294
Paul Jensen99364842014-12-09 11:43:45 -05002295 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
Paul Jensene0988542015-06-25 15:30:08 -04002296 // This is whether it is satisfying any NetworkRequests or were it to become validated,
2297 // would it have a chance of satisfying any NetworkRequests.
Paul Jensen99364842014-12-09 11:43:45 -05002298 private boolean unneeded(NetworkAgentInfo nai) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04002299 if (!nai.created || nai.isVPN() || nai.lingering) return false;
Paul Jensene0988542015-06-25 15:30:08 -04002300 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2301 // If this Network is already the highest scoring Network for a request, or if
2302 // there is hope for it to become one if it validated, then it is needed.
2303 if (nri.isRequest && nai.satisfies(nri.request) &&
2304 (nai.networkRequests.get(nri.request.requestId) != null ||
2305 // Note that this catches two important cases:
2306 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2307 // is currently satisfying the request. This is desirable when
2308 // cellular ends up validating but WiFi does not.
2309 // 2. Unvalidated WiFi will not be reaped when validated cellular
Paul Jensencf4c2c62015-07-01 14:16:32 -04002310 // is currently satisfying the request. This is desirable when
Paul Jensene0988542015-06-25 15:30:08 -04002311 // WiFi ends up validating and out scoring cellular.
2312 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2313 nai.getCurrentScoreAsValidated())) {
2314 return false;
Paul Jensen99364842014-12-09 11:43:45 -05002315 }
2316 }
Paul Jensene0988542015-06-25 15:30:08 -04002317 return true;
Paul Jensen99364842014-12-09 11:43:45 -05002318 }
2319
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002320 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2321 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002322 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002323 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002324 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2325 return;
2326 }
2327 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002328 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002329 mNetworkRequests.remove(request);
Erik Kline7523eb32015-07-09 18:24:03 +09002330 mNetworkRequestInfoLogs.log("RELEASE " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002331 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002332 // Find all networks that are satisfying this request and remove the request
2333 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002334 // TODO - it's my understanding that for a request there is only a single
2335 // network satisfying it, so this loop is wasteful
2336 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002337 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2338 if (nai.networkRequests.get(nri.request.requestId) != null) {
2339 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002340 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002341 log(" Removing from current network " + nai.name() +
2342 ", leaving " + nai.networkRequests.size() +
2343 " requests.");
2344 }
Paul Jensen99364842014-12-09 11:43:45 -05002345 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002346 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002347 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002348 } else {
2349 // suspect there should only be one pass through here
2350 // but if any were kept do the check below
2351 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002352 }
2353 }
2354 }
2355
Robert Greenwalt51481852015-01-08 14:43:31 -08002356 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2357 if (nai != null) {
2358 mNetworkForRequestId.remove(nri.request.requestId);
2359 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002360 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002361 // that a network connected to serve it, even though the network was already
2362 // connected. Now that this request has gone away, we might have to pretend
2363 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002364 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002365 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2366 boolean doRemove = true;
2367 if (wasKept) {
2368 // check if any of the remaining requests for this network are for the
2369 // same legacy type - if so, don't remove the nai
2370 for (int i = 0; i < nai.networkRequests.size(); i++) {
2371 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2372 if (otherRequest.legacyType == nri.request.legacyType &&
2373 isRequest(otherRequest)) {
2374 if (DBG) log(" still have other legacy request - leaving");
2375 doRemove = false;
2376 }
2377 }
2378 }
2379
2380 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002381 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002382 }
2383 }
2384
Robert Greenwalta67be032014-05-16 15:49:14 -07002385 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002386 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2387 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002388 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002389 } else {
2390 // listens don't have a singular affectedNetwork. Check all networks to see
2391 // if this listen request applies and remove it.
2392 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2393 nai.networkRequests.remove(nri.request.requestId);
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09002394 if (nri.request.networkCapabilities.hasSignalStrength() &&
2395 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
2396 updateSignalStrengthThresholds(nai, "RELEASE", nri.request);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09002397 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002398 }
2399 }
2400 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2401 }
2402 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002403
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002404 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2405 enforceConnectivityInternalPermission();
2406 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2407 accept ? 1 : 0, always ? 1: 0, network));
2408 }
2409
2410 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2411 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2412 " accept=" + accept + " always=" + always);
2413
2414 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2415 if (nai == null) {
2416 // Nothing to do.
2417 return;
2418 }
2419
2420 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002421 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002422 return;
2423 }
2424
2425 if (!nai.networkMisc.explicitlySelected) {
2426 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2427 }
2428
2429 if (accept != nai.networkMisc.acceptUnvalidated) {
2430 int oldScore = nai.getCurrentScore();
2431 nai.networkMisc.acceptUnvalidated = accept;
Paul Jensen85cf78e2015-06-25 13:25:07 -04002432 rematchAllNetworksAndRequests(nai, oldScore);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002433 sendUpdatedScoreToFactories(nai);
2434 }
2435
2436 if (always) {
2437 nai.asyncChannel.sendMessage(
2438 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2439 }
2440
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002441 if (!accept) {
Paul Jensenf95d2202015-07-13 15:19:51 -04002442 // Tell the NetworkAgent to not automatically reconnect to the network.
2443 nai.asyncChannel.sendMessage(NetworkAgent.CMD_PREVENT_AUTOMATIC_RECONNECT);
2444 // Teardown the nework.
2445 teardownUnneededNetwork(nai);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002446 }
2447
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002448 }
2449
2450 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002451 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002452 mHandler.sendMessageDelayed(
2453 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2454 PROMPT_UNVALIDATED_DELAY_MS);
2455 }
2456
2457 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002458 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002459 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2460
2461 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2462 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002463 // Also don't prompt on captive portals because we're already prompting the user to sign in.
Paul Jensen3d194ea2015-06-16 14:27:36 -04002464 if (nai == null || nai.everValidated || nai.everCaptivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002465 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2466 return;
2467 }
2468
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002469 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002470 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002471 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2472 intent.setClassName("com.android.settings",
2473 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002474
2475 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2476 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2477 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09002478 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent, true);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002479 }
2480
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002481 private class InternalHandler extends Handler {
2482 public InternalHandler(Looper looper) {
2483 super(looper);
2484 }
2485
2486 @Override
2487 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002488 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002489 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002490 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002491 String causedBy = null;
2492 synchronized (ConnectivityService.this) {
2493 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2494 mNetTransitionWakeLock.isHeld()) {
2495 mNetTransitionWakeLock.release();
2496 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002497 } else {
2498 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002499 }
2500 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002501 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2502 log("Failed to find a new network - expiring NetTransition Wakelock");
2503 } else {
2504 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2505 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002506 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002507 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002508 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002509 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002510 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002511 break;
2512 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002513 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002514 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002515 sendStickyBroadcast(intent);
2516 break;
2517 }
Jason Monkdecd2952013-10-10 14:02:51 -04002518 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002519 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002520 break;
2521 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002522 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002523 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2524 break;
2525 }
2526 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2527 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002528 break;
2529 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002530 case EVENT_REGISTER_NETWORK_AGENT: {
2531 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2532 break;
2533 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002534 case EVENT_REGISTER_NETWORK_REQUEST:
2535 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002536 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002537 break;
2538 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002539 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2540 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002541 handleRegisterNetworkRequestWithIntent(msg);
2542 break;
2543 }
2544 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2545 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2546 break;
2547 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002548 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002549 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002550 break;
2551 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002552 case EVENT_SET_ACCEPT_UNVALIDATED: {
2553 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2554 break;
2555 }
2556 case EVENT_PROMPT_UNVALIDATED: {
2557 handlePromptUnvalidated((Network) msg.obj);
2558 break;
2559 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002560 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2561 handleMobileDataAlwaysOn();
2562 break;
2563 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002564 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2565 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2566 mKeepaliveTracker.handleStartKeepalive(msg);
2567 break;
2568 }
2569 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2570 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2571 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2572 int slot = msg.arg1;
2573 int reason = msg.arg2;
2574 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2575 break;
2576 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002577 case EVENT_SYSTEM_READY: {
2578 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2579 nai.networkMonitor.systemReady = true;
2580 }
2581 break;
2582 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002583 }
2584 }
2585 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002586
2587 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002588 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002589 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002590 if (isTetheringSupported()) {
2591 return mTethering.tether(iface);
2592 } else {
2593 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2594 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002595 }
2596
2597 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002598 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002599 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002600
2601 if (isTetheringSupported()) {
2602 return mTethering.untether(iface);
2603 } else {
2604 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2605 }
2606 }
2607
2608 // javadoc from interface
2609 public int getLastTetherError(String iface) {
2610 enforceTetherAccessPermission();
2611
2612 if (isTetheringSupported()) {
2613 return mTethering.getLastTetherError(iface);
2614 } else {
2615 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2616 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002617 }
2618
2619 // TODO - proper iface API for selection by property, inspection, etc
2620 public String[] getTetherableUsbRegexs() {
2621 enforceTetherAccessPermission();
2622 if (isTetheringSupported()) {
2623 return mTethering.getTetherableUsbRegexs();
2624 } else {
2625 return new String[0];
2626 }
2627 }
2628
2629 public String[] getTetherableWifiRegexs() {
2630 enforceTetherAccessPermission();
2631 if (isTetheringSupported()) {
2632 return mTethering.getTetherableWifiRegexs();
2633 } else {
2634 return new String[0];
2635 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002636 }
2637
Danica Chang6fdd0c62010-08-11 14:54:43 -07002638 public String[] getTetherableBluetoothRegexs() {
2639 enforceTetherAccessPermission();
2640 if (isTetheringSupported()) {
2641 return mTethering.getTetherableBluetoothRegexs();
2642 } else {
2643 return new String[0];
2644 }
2645 }
2646
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002647 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002648 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002649 if (isTetheringSupported()) {
2650 return mTethering.setUsbTethering(enable);
2651 } else {
2652 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2653 }
2654 }
2655
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002656 // TODO - move iface listing, queries, etc to new module
2657 // javadoc from interface
2658 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002659 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002660 return mTethering.getTetherableIfaces();
2661 }
2662
2663 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002664 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002665 return mTethering.getTetheredIfaces();
2666 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002667
Robert Greenwalt5a735062010-03-02 17:25:02 -08002668 public String[] getTetheringErroredIfaces() {
2669 enforceTetherAccessPermission();
2670 return mTethering.getErroredIfaces();
2671 }
2672
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002673 public String[] getTetheredDhcpRanges() {
2674 enforceConnectivityInternalPermission();
2675 return mTethering.getTetheredDhcpRanges();
2676 }
2677
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002678 // if ro.tether.denied = true we default to no tethering
2679 // gservices could set the secure setting to 1 though to enable it on a build where it
2680 // had previously been turned off.
2681 public boolean isTetheringSupported() {
2682 enforceTetherAccessPermission();
2683 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002684 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002685 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2686 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002687 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2688 mTethering.getTetherableWifiRegexs().length != 0 ||
2689 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2690 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002691 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002692
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002693 // Called when we lose the default network and have no replacement yet.
2694 // This will automatically be cleared after X seconds or a new default network
2695 // becomes CONNECTED, whichever happens first. The timer is started by the
2696 // first caller and not restarted by subsequent callers.
2697 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002698 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002699 synchronized (this) {
2700 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002701 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002702 mNetTransitionWakeLock.acquire();
2703 mNetTransitionWakeLockCausedBy = forWhom;
2704 }
2705 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002706 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002707 mNetTransitionWakeLockTimeout);
2708 return;
2709 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002710
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002711 // 100 percent is full good, 0 is full bad.
2712 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002713 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002714 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002715 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002716 }
2717
Paul Jensenbfd17b72015-04-07 12:43:13 -04002718 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002719 enforceAccessPermission();
2720 enforceInternetPermission();
2721
Paul Jensenbfd17b72015-04-07 12:43:13 -04002722 NetworkAgentInfo nai;
2723 if (network == null) {
2724 nai = getDefaultNetwork();
2725 } else {
2726 nai = getNetworkAgentInfoForNetwork(network);
2727 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002728 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2729 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2730 return;
2731 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002732 // Revalidate if the app report does not match our current validated state.
2733 if (hasConnectivity == nai.lastValidated) return;
2734 final int uid = Binder.getCallingUid();
2735 if (DBG) {
2736 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2737 ") by " + uid);
2738 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002739 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002740 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2741 // which isn't meant to work on uncreated networks.
2742 if (!nai.created) return;
2743
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002744 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002745
2746 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2747 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002748 }
2749
Paul Jensencee9b512015-05-06 07:32:40 -04002750 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002751 // this information is already available as a world read/writable jvm property
2752 // so this API change wouldn't have a benifit. It also breaks the passing
2753 // of proxy info to all the JVMs.
2754 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002755 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002756 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002757 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2758 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002759 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002760 }
2761
Paul Jensencee9b512015-05-06 07:32:40 -04002762 public ProxyInfo getProxyForNetwork(Network network) {
2763 if (network == null) return getDefaultProxy();
2764 final ProxyInfo globalProxy = getGlobalProxy();
2765 if (globalProxy != null) return globalProxy;
2766 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2767 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2768 // caller may not have.
2769 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2770 if (nai == null) return null;
2771 synchronized (nai) {
2772 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2773 if (proxyInfo == null) return null;
2774 return new ProxyInfo(proxyInfo);
2775 }
2776 }
2777
Paul Jensene0bef712014-12-10 15:12:18 -05002778 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2779 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2780 // proxy is null then there is no proxy in place).
2781 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2782 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2783 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2784 proxy = null;
2785 }
2786 return proxy;
2787 }
2788
2789 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2790 // better for determining if a new proxy broadcast is necessary:
2791 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2792 // avoid unnecessary broadcasts.
2793 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2794 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2795 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2796 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2797 // all set.
2798 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2799 a = canonicalizeProxyInfo(a);
2800 b = canonicalizeProxyInfo(b);
2801 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2802 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2803 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2804 }
2805
Jason Monk207900c2014-04-25 15:00:09 -04002806 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002807 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002808
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002809 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002810 if (proxyProperties == mGlobalProxy) return;
2811 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2812 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2813
2814 String host = "";
2815 int port = 0;
2816 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002817 String pacFileUrl = "";
2818 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002819 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002820 if (!proxyProperties.isValid()) {
2821 if (DBG)
2822 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2823 return;
2824 }
Jason Monk207900c2014-04-25 15:00:09 -04002825 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002826 host = mGlobalProxy.getHost();
2827 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002828 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002829 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002830 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002831 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002832 } else {
2833 mGlobalProxy = null;
2834 }
2835 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002836 final long token = Binder.clearCallingIdentity();
2837 try {
2838 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2839 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2840 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2841 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002842 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002843 } finally {
2844 Binder.restoreCallingIdentity(token);
2845 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002846
Jason Monkcf0f97a2014-10-02 15:39:38 -04002847 if (mGlobalProxy == null) {
2848 proxyProperties = mDefaultProxy;
2849 }
2850 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002851 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002852 }
2853
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002854 private void loadGlobalProxy() {
2855 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002856 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2857 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2858 String exclList = Settings.Global.getString(res,
2859 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002860 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2861 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002862 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002863 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002864 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002865 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002866 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002867 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002868 if (!proxyProperties.isValid()) {
2869 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2870 return;
2871 }
2872
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002873 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002874 mGlobalProxy = proxyProperties;
2875 }
2876 }
2877 }
2878
Jason Monk207900c2014-04-25 15:00:09 -04002879 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002880 // this information is already available as a world read/writable jvm property
2881 // so this API change wouldn't have a benifit. It also breaks the passing
2882 // of proxy info to all the JVMs.
2883 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002884 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002885 return mGlobalProxy;
2886 }
2887 }
2888
Jason Monk207900c2014-04-25 15:00:09 -04002889 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002890 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002891 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002892 proxy = null;
2893 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002894 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002895 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002896 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002897 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002898 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2899 return;
2900 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002901
2902 // This call could be coming from the PacManager, containing the port of the local
2903 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2904 // global (to get the correct local port), and send a broadcast.
2905 // TODO: Switch PacManager to have its own message to send back rather than
2906 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002907 if ((mGlobalProxy != null) && (proxy != null)
2908 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002909 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2910 mGlobalProxy = proxy;
2911 sendProxyBroadcast(mGlobalProxy);
2912 return;
2913 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002914 mDefaultProxy = proxy;
2915
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002916 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002917 if (!mDefaultProxyDisabled) {
2918 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002919 }
2920 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002921 }
2922
Paul Jensene0bef712014-12-10 15:12:18 -05002923 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2924 // This method gets called when any network changes proxy, but the broadcast only ever contains
2925 // the default proxy (even if it hasn't changed).
2926 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2927 // world where an app might be bound to a non-default network.
2928 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2929 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2930 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2931
2932 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2933 sendProxyBroadcast(getDefaultProxy());
2934 }
2935 }
2936
Robert Greenwalt434203a2010-10-11 16:00:27 -07002937 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002938 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2939 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002940 if (!TextUtils.isEmpty(proxy)) {
2941 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002942 if (data.length == 0) {
2943 return;
2944 }
2945
Robert Greenwalt434203a2010-10-11 16:00:27 -07002946 String proxyHost = data[0];
2947 int proxyPort = 8080;
2948 if (data.length > 1) {
2949 try {
2950 proxyPort = Integer.parseInt(data[1]);
2951 } catch (NumberFormatException e) {
2952 return;
2953 }
2954 }
Jason Monk207900c2014-04-25 15:00:09 -04002955 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002956 setGlobalProxy(p);
2957 }
2958 }
2959
Jason Monk207900c2014-04-25 15:00:09 -04002960 private void sendProxyBroadcast(ProxyInfo proxy) {
2961 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002962 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002963 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002964 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002965 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2966 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002967 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002968 final long ident = Binder.clearCallingIdentity();
2969 try {
2970 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2971 } finally {
2972 Binder.restoreCallingIdentity(ident);
2973 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002974 }
2975
2976 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002977 final private HashMap<Uri, Integer> mUriEventMap;
2978 final private Context mContext;
2979 final private Handler mHandler;
2980
2981 SettingsObserver(Context context, Handler handler) {
2982 super(null);
2983 mUriEventMap = new HashMap<Uri, Integer>();
2984 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002985 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002986 }
2987
Erik Klineda4bfa82015-04-30 12:58:40 +09002988 void observe(Uri uri, int what) {
2989 mUriEventMap.put(uri, what);
2990 final ContentResolver resolver = mContext.getContentResolver();
2991 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002992 }
2993
2994 @Override
2995 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002996 Slog.wtf(TAG, "Should never be reached.");
2997 }
2998
2999 @Override
3000 public void onChange(boolean selfChange, Uri uri) {
3001 final Integer what = mUriEventMap.get(uri);
3002 if (what != null) {
3003 mHandler.obtainMessage(what.intValue()).sendToTarget();
3004 } else {
3005 loge("No matching event to send for URI=" + uri);
3006 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003007 }
3008 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003009
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003010 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003011 Slog.d(TAG, s);
3012 }
3013
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003014 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003015 Slog.e(TAG, s);
3016 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003017
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003018 private static <T> T checkNotNull(T value, String message) {
3019 if (value == null) {
3020 throw new NullPointerException(message);
3021 }
3022 return value;
3023 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003024
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003025 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003026 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003027 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3028 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3029 *
3030 * @param oldPackage Package name of the application which currently controls VPN, which will
3031 * be replaced. If there is no such application, this should should either be
3032 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3033 * @param newPackage Package name of the application which should gain control of VPN, or
3034 * {@code null} to disable.
3035 * @param userId User for whom to prepare the new VPN.
3036 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003037 * @hide
3038 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003039 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003040 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3041 int userId) {
3042 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003043 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003044
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003045 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003046 Vpn vpn = mVpns.get(userId);
3047 if (vpn != null) {
3048 return vpn.prepare(oldPackage, newPackage);
3049 } else {
3050 return false;
3051 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003052 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003053 }
3054
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003055 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003056 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3057 * This method is used by system-privileged apps.
3058 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3059 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3060 *
3061 * @param packageName The package for which authorization state should change.
3062 * @param userId User for whom {@code packageName} is installed.
3063 * @param authorized {@code true} if this app should be able to start a VPN connection without
3064 * explicit user approval, {@code false} if not.
3065 *
Jeff Davidson05542602014-08-11 14:07:27 -07003066 * @hide
3067 */
3068 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003069 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3070 enforceCrossUserPermission(userId);
3071
Jeff Davidson05542602014-08-11 14:07:27 -07003072 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003073 Vpn vpn = mVpns.get(userId);
3074 if (vpn != null) {
3075 vpn.setPackageAuthorization(packageName, authorized);
3076 }
Jeff Davidson05542602014-08-11 14:07:27 -07003077 }
3078 }
3079
3080 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003081 * Configure a TUN interface and return its file descriptor. Parameters
3082 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003083 * and not available in ConnectivityManager. Permissions are checked in
3084 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003085 * @hide
3086 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003087 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003088 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003089 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003090 int user = UserHandle.getUserId(Binder.getCallingUid());
3091 synchronized(mVpns) {
3092 return mVpns.get(user).establish(config);
3093 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003094 }
3095
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003096 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003097 * Start legacy VPN, controlling native daemons as needed. Creates a
3098 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003099 */
3100 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003101 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003102 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003103 final LinkProperties egress = getActiveLinkProperties();
3104 if (egress == null) {
3105 throw new IllegalStateException("Missing active network connection");
3106 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003107 int user = UserHandle.getUserId(Binder.getCallingUid());
3108 synchronized(mVpns) {
3109 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3110 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003111 }
3112
3113 /**
3114 * Return the information of the ongoing legacy VPN. This method is used
3115 * by VpnSettings and not available in ConnectivityManager. Permissions
3116 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003117 */
3118 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003119 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3120 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003121 if (mLockdownEnabled) {
3122 return null;
3123 }
3124
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003125 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003126 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003127 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003128 }
3129
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003130 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003131 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3132 * and not available in ConnectivityManager.
3133 */
3134 @Override
3135 public VpnInfo[] getAllVpnInfo() {
3136 enforceConnectivityInternalPermission();
3137 if (mLockdownEnabled) {
3138 return new VpnInfo[0];
3139 }
3140
3141 synchronized(mVpns) {
3142 List<VpnInfo> infoList = new ArrayList<>();
3143 for (int i = 0; i < mVpns.size(); i++) {
3144 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3145 if (info != null) {
3146 infoList.add(info);
3147 }
3148 }
3149 return infoList.toArray(new VpnInfo[infoList.size()]);
3150 }
3151 }
3152
3153 /**
3154 * @return VPN information for accounting, or null if we can't retrieve all required
3155 * information, e.g primary underlying iface.
3156 */
3157 @Nullable
3158 private VpnInfo createVpnInfo(Vpn vpn) {
3159 VpnInfo info = vpn.getVpnInfo();
3160 if (info == null) {
3161 return null;
3162 }
3163 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3164 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3165 // the underlyingNetworks list.
3166 if (underlyingNetworks == null) {
3167 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3168 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3169 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3170 }
3171 } else if (underlyingNetworks.length > 0) {
3172 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3173 if (linkProperties != null) {
3174 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3175 }
3176 }
3177 return info.primaryUnderlyingIface == null ? null : info;
3178 }
3179
3180 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003181 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3182 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003183 * Permissions are checked in Vpn class.
3184 * @hide
3185 */
3186 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003187 public VpnConfig getVpnConfig(int userId) {
3188 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003189 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003190 Vpn vpn = mVpns.get(userId);
3191 if (vpn != null) {
3192 return vpn.getVpnConfig();
3193 } else {
3194 return null;
3195 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003196 }
3197 }
3198
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003199 @Override
3200 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003201 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3202 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3203 return false;
3204 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003205
3206 // Tear down existing lockdown if profile was removed
3207 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3208 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003209 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003210 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3211 return false;
3212 }
3213
3214 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3215 final VpnProfile profile = VpnProfile.decode(
3216 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003217 int user = UserHandle.getUserId(Binder.getCallingUid());
3218 synchronized(mVpns) {
3219 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3220 profile));
3221 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003222 } else {
3223 setLockdownTracker(null);
3224 }
3225
3226 return true;
3227 }
3228
3229 /**
3230 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3231 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3232 */
3233 private void setLockdownTracker(LockdownVpnTracker tracker) {
3234 // Shutdown any existing tracker
3235 final LockdownVpnTracker existing = mLockdownTracker;
3236 mLockdownTracker = null;
3237 if (existing != null) {
3238 existing.shutdown();
3239 }
3240
3241 try {
3242 if (tracker != null) {
3243 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003244 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003245 mLockdownTracker = tracker;
3246 mLockdownTracker.init();
3247 } else {
3248 mNetd.setFirewallEnabled(false);
3249 }
3250 } catch (RemoteException e) {
3251 // ignored; NMS lives inside system_server
3252 }
3253 }
3254
3255 private void throwIfLockdownEnabled() {
3256 if (mLockdownEnabled) {
3257 throw new IllegalStateException("Unavailable in lockdown mode");
3258 }
3259 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003260
Wink Savilleab9321d2013-06-29 21:10:57 -07003261 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003262 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003263 // TODO: Remove? Any reason to trigger a provisioning check?
3264 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003265 }
3266
3267 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003268 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003269
Paul Jensen89e0f092014-09-15 15:59:36 -04003270 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003271 if (DBG) {
3272 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003273 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003274 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003275 Intent intent = new Intent(action);
3276 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003277 // Concatenate the range of types onto the range of NetIDs.
3278 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003279 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003280 networkType, null, pendingIntent, false);
Paul Jensen869868be2014-05-15 10:33:05 -04003281 }
3282
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003283 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003284 * Show or hide network provisioning notifications.
3285 *
3286 * We use notifications for two purposes: to notify that a network requires sign in
3287 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3288 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3289 * particular network we can display the notification type that was most recently requested.
3290 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3291 * might first display NO_INTERNET, and then when the captive portal check completes, display
3292 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003293 *
3294 * @param id an identifier that uniquely identifies this notification. This must match
3295 * between show and hide calls. We use the NetID value but for legacy callers
3296 * we concatenate the range of types with the range of NetIDs.
3297 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003298 private void setProvNotificationVisibleIntent(boolean visible, int id,
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003299 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent,
3300 boolean highPriority) {
Paul Jensen869868be2014-05-15 10:33:05 -04003301 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003302 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3303 + " networkType=" + getNetworkTypeName(networkType)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003304 + " extraInfo=" + extraInfo + " highPriority=" + highPriority);
Paul Jensen869868be2014-05-15 10:33:05 -04003305 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003306
3307 Resources r = Resources.getSystem();
3308 NotificationManager notificationManager = (NotificationManager) mContext
3309 .getSystemService(Context.NOTIFICATION_SERVICE);
3310
3311 if (visible) {
3312 CharSequence title;
3313 CharSequence details;
3314 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003315 if (notifyType == NotificationType.NO_INTERNET &&
3316 networkType == ConnectivityManager.TYPE_WIFI) {
3317 title = r.getString(R.string.wifi_no_internet, 0);
3318 details = r.getString(R.string.wifi_no_internet_detailed);
3319 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3320 } else if (notifyType == NotificationType.SIGN_IN) {
3321 switch (networkType) {
3322 case ConnectivityManager.TYPE_WIFI:
3323 title = r.getString(R.string.wifi_available_sign_in, 0);
3324 details = r.getString(R.string.network_available_sign_in_detailed,
3325 extraInfo);
3326 icon = R.drawable.stat_notify_wifi_in_range;
3327 break;
3328 case ConnectivityManager.TYPE_MOBILE:
3329 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3330 title = r.getString(R.string.network_available_sign_in, 0);
3331 // TODO: Change this to pull from NetworkInfo once a printable
3332 // name has been added to it
3333 details = mTelephonyManager.getNetworkOperatorName();
3334 icon = R.drawable.stat_notify_rssi_in_range;
3335 break;
3336 default:
3337 title = r.getString(R.string.network_available_sign_in, 0);
3338 details = r.getString(R.string.network_available_sign_in_detailed,
3339 extraInfo);
3340 icon = R.drawable.stat_notify_rssi_in_range;
3341 break;
3342 }
3343 } else {
3344 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3345 + getNetworkTypeName(networkType));
3346 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003347 }
3348
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003349 Notification notification = new Notification.Builder(mContext)
3350 .setWhen(0)
3351 .setSmallIcon(icon)
3352 .setAutoCancel(true)
3353 .setTicker(title)
3354 .setColor(mContext.getColor(
3355 com.android.internal.R.color.system_notification_accent_color))
3356 .setContentTitle(title)
3357 .setContentText(details)
3358 .setContentIntent(intent)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003359 .setLocalOnly(true)
3360 .setPriority(highPriority ?
3361 Notification.PRIORITY_HIGH :
3362 Notification.PRIORITY_DEFAULT)
3363 .setDefaults(Notification.DEFAULT_ALL)
3364 .setOnlyAlertOnce(true)
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003365 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003366
Wink Saville948282b2013-08-29 08:55:16 -07003367 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003368 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003369 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003370 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003371 npe.printStackTrace();
3372 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003373 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003374 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003375 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003376 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003377 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003378 npe.printStackTrace();
3379 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003380 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003381 }
3382
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003383 /** Location to an updatable file listing carrier provisioning urls.
3384 * An example:
3385 *
3386 * <?xml version="1.0" encoding="utf-8"?>
3387 * <provisioningUrls>
3388 * <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 -07003389 * </provisioningUrls>
3390 */
3391 private static final String PROVISIONING_URL_PATH =
3392 "/data/misc/radio/provisioning_urls.xml";
3393 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003394
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003395 /** XML tag for root element. */
3396 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3397 /** XML tag for individual url */
3398 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003399 /** XML attribute for mcc */
3400 private static final String ATTR_MCC = "mcc";
3401 /** XML attribute for mnc */
3402 private static final String ATTR_MNC = "mnc";
3403
Paul Jensen434dde82015-06-11 09:43:30 -04003404 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003405 FileReader fileReader = null;
3406 XmlPullParser parser = null;
3407 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003408
3409 try {
3410 fileReader = new FileReader(mProvisioningUrlFile);
3411 parser = Xml.newPullParser();
3412 parser.setInput(fileReader);
3413 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3414
3415 while (true) {
3416 XmlUtils.nextElement(parser);
3417
3418 String element = parser.getName();
3419 if (element == null) break;
3420
Paul Jensen434dde82015-06-11 09:43:30 -04003421 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003422 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3423 try {
3424 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3425 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3426 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3427 parser.next();
3428 if (parser.getEventType() == XmlPullParser.TEXT) {
3429 return parser.getText();
3430 }
3431 }
3432 }
3433 } catch (NumberFormatException e) {
3434 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3435 }
3436 }
3437 }
3438 return null;
3439 } catch (FileNotFoundException e) {
3440 loge("Carrier Provisioning Urls file not found");
3441 } catch (XmlPullParserException e) {
3442 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3443 } catch (IOException e) {
3444 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3445 } finally {
3446 if (fileReader != null) {
3447 try {
3448 fileReader.close();
3449 } catch (IOException e) {}
3450 }
3451 }
3452 return null;
3453 }
3454
Wink Saville42d4f082013-07-20 20:31:59 -07003455 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003456 public String getMobileProvisioningUrl() {
3457 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003458 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003459 if (TextUtils.isEmpty(url)) {
3460 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003461 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003462 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003463 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003464 }
Wink Saville8cf35602013-07-10 23:00:07 -07003465 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003466 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003467 String phoneNumber = mTelephonyManager.getLine1Number();
3468 if (TextUtils.isEmpty(phoneNumber)) {
3469 phoneNumber = "0000000000";
3470 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003471 url = String.format(url,
3472 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3473 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003474 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003475 }
3476
Wink Savilleab9321d2013-06-29 21:10:57 -07003477 return url;
3478 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003479
Wink Saville948282b2013-08-29 08:55:16 -07003480 @Override
3481 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003482 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003483 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003484 final long ident = Binder.clearCallingIdentity();
3485 try {
3486 setProvNotificationVisible(visible, networkType, action);
3487 } finally {
3488 Binder.restoreCallingIdentity(ident);
3489 }
Wink Saville948282b2013-08-29 08:55:16 -07003490 }
Wink Saville7788c612013-08-29 14:57:08 -07003491
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003492 @Override
3493 public void setAirplaneMode(boolean enable) {
3494 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003495 final long ident = Binder.clearCallingIdentity();
3496 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003497 final ContentResolver cr = mContext.getContentResolver();
3498 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3499 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3500 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003501 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003502 } finally {
3503 Binder.restoreCallingIdentity(ident);
3504 }
3505 }
3506
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003507 private void onUserStart(int userId) {
3508 synchronized(mVpns) {
3509 Vpn userVpn = mVpns.get(userId);
3510 if (userVpn != null) {
3511 loge("Starting user already has a VPN");
3512 return;
3513 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003514 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003515 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003516 }
3517 }
3518
3519 private void onUserStop(int userId) {
3520 synchronized(mVpns) {
3521 Vpn userVpn = mVpns.get(userId);
3522 if (userVpn == null) {
3523 loge("Stopping user has no VPN");
3524 return;
3525 }
3526 mVpns.delete(userId);
3527 }
3528 }
3529
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003530 private void onUserAdded(int userId) {
3531 synchronized(mVpns) {
3532 final int vpnsSize = mVpns.size();
3533 for (int i = 0; i < vpnsSize; i++) {
3534 Vpn vpn = mVpns.valueAt(i);
3535 vpn.onUserAdded(userId);
3536 }
3537 }
3538 }
3539
3540 private void onUserRemoved(int userId) {
3541 synchronized(mVpns) {
3542 final int vpnsSize = mVpns.size();
3543 for (int i = 0; i < vpnsSize; i++) {
3544 Vpn vpn = mVpns.valueAt(i);
3545 vpn.onUserRemoved(userId);
3546 }
3547 }
3548 }
3549
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003550 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3551 @Override
3552 public void onReceive(Context context, Intent intent) {
3553 final String action = intent.getAction();
3554 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3555 if (userId == UserHandle.USER_NULL) return;
3556
3557 if (Intent.ACTION_USER_STARTING.equals(action)) {
3558 onUserStart(userId);
3559 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3560 onUserStop(userId);
Fyodor Kupolov1c363152015-09-02 13:27:21 -07003561 } else if (Intent.ACTION_USER_ADDED.equals(action)) {
3562 onUserAdded(userId);
3563 } else if (Intent.ACTION_USER_REMOVED.equals(action)) {
3564 onUserRemoved(userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003565 }
3566 }
3567 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003568
Robert Greenwalta67be032014-05-16 15:49:14 -07003569 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3570 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003571 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3572 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003573
Robert Greenwalta67be032014-05-16 15:49:14 -07003574 private static class NetworkFactoryInfo {
3575 public final String name;
3576 public final Messenger messenger;
3577 public final AsyncChannel asyncChannel;
3578
3579 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3580 this.name = name;
3581 this.messenger = messenger;
3582 this.asyncChannel = asyncChannel;
3583 }
3584 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003585
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003586 /**
3587 * Tracks info about the requester.
3588 * Also used to notice when the calling process dies so we can self-expire
3589 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003590 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3591 static final boolean REQUEST = true;
3592 static final boolean LISTEN = false;
3593
3594 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003595 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003596 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003597 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003598 final int mPid;
3599 final int mUid;
3600 final Messenger messenger;
3601 final boolean isRequest;
3602
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003603 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3604 request = r;
3605 mPendingIntent = pi;
3606 messenger = null;
3607 mBinder = null;
3608 mPid = getCallingPid();
3609 mUid = getCallingUid();
3610 this.isRequest = isRequest;
3611 }
3612
Robert Greenwalt9258c642014-03-26 16:47:06 -07003613 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3614 super();
3615 messenger = m;
3616 request = r;
3617 mBinder = binder;
3618 mPid = getCallingPid();
3619 mUid = getCallingUid();
3620 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003621 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003622
3623 try {
3624 mBinder.linkToDeath(this, 0);
3625 } catch (RemoteException e) {
3626 binderDied();
3627 }
3628 }
3629
3630 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003631 if (mBinder != null) {
3632 mBinder.unlinkToDeath(this, 0);
3633 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003634 }
3635
3636 public void binderDied() {
3637 log("ConnectivityService NetworkRequestInfo binderDied(" +
3638 request + ", " + mBinder + ")");
3639 releaseNetworkRequest(request);
3640 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003641
3642 public String toString() {
Erik Kline7523eb32015-07-09 18:24:03 +09003643 return (isRequest ? "Request" : "Listen") +
3644 " from uid/pid:" + mUid + "/" + mPid +
3645 " for " + request +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003646 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003647 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003648 }
3649
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003650 private void ensureRequestableCapabilities(NetworkCapabilities networkCapabilities) {
3651 final String badCapability = networkCapabilities.describeFirstNonRequestableCapability();
3652 if (badCapability != null) {
3653 throw new IllegalArgumentException("Cannot request network with " + badCapability);
Paul Jensenbb2e0e92015-06-16 15:11:58 -04003654 }
3655 }
3656
Erik Kline9d598e12015-07-13 16:37:51 +09003657 private ArrayList<Integer> getSignalStrengthThresholds(NetworkAgentInfo nai) {
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003658 final SortedSet<Integer> thresholds = new TreeSet();
3659 synchronized (nai) {
3660 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
3661 if (nri.request.networkCapabilities.hasSignalStrength() &&
3662 nai.satisfiesImmutableCapabilitiesOf(nri.request)) {
3663 thresholds.add(nri.request.networkCapabilities.getSignalStrength());
3664 }
3665 }
3666 }
Erik Kline9d598e12015-07-13 16:37:51 +09003667 return new ArrayList<Integer>(thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003668 }
3669
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003670 private void updateSignalStrengthThresholds(
3671 NetworkAgentInfo nai, String reason, NetworkRequest request) {
3672 ArrayList<Integer> thresholdsArray = getSignalStrengthThresholds(nai);
Erik Kline9d598e12015-07-13 16:37:51 +09003673 Bundle thresholds = new Bundle();
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09003674 thresholds.putIntegerArrayList("thresholds", thresholdsArray);
3675
3676 // TODO: Switch to VDBG.
3677 if (DBG) {
3678 String detail;
3679 if (request != null && request.networkCapabilities.hasSignalStrength()) {
3680 detail = reason + " " + request.networkCapabilities.getSignalStrength();
3681 } else {
3682 detail = reason;
3683 }
3684 log(String.format("updateSignalStrengthThresholds: %s, sending %s to %s",
3685 detail, Arrays.toString(thresholdsArray.toArray()), nai.name()));
3686 }
3687
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003688 nai.asyncChannel.sendMessage(
3689 android.net.NetworkAgent.CMD_SET_SIGNAL_STRENGTH_THRESHOLDS,
Erik Kline9d598e12015-07-13 16:37:51 +09003690 0, 0, thresholds);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09003691 }
3692
Robert Greenwalt9258c642014-03-26 16:47:06 -07003693 @Override
3694 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003695 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003696 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003697 enforceNetworkRequestPermissions(networkCapabilities);
3698 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003699 ensureRequestableCapabilities(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003700
Robert Greenwalt6078b502014-06-11 16:05:07 -07003701 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003702 throw new IllegalArgumentException("Bad timeout specified");
3703 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003704
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003705 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3706 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003707 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3708 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003709 if (DBG) log("requestNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003710
3711 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003712 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003713 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003714 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003715 }
3716 return networkRequest;
3717 }
3718
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003719 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003720 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003721 enforceConnectivityInternalPermission();
3722 } else {
3723 enforceChangePermission();
3724 }
3725 }
3726
fenglub15e72b2015-03-20 11:29:56 -07003727 @Override
fengludb571472015-04-21 17:12:05 -07003728 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003729 enforceAccessPermission();
3730 NetworkAgentInfo nai = null;
3731 if (network == null) {
3732 return false;
3733 }
3734 synchronized (mNetworkForNetId) {
3735 nai = mNetworkForNetId.get(network.netId);
3736 }
3737 if (nai != null) {
3738 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3739 return true;
3740 }
3741 return false;
3742 }
3743
3744
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003745 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3746 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003747 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003748 final int uidRules;
3749 final int uid = Binder.getCallingUid();
3750 synchronized(mRulesLock) {
3751 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3752 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003753 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003754 // we could silently fail or we can filter the available nets to only give
3755 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003756 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003757 }
3758 }
3759 }
3760
Robert Greenwalt9258c642014-03-26 16:47:06 -07003761 @Override
3762 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3763 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003764 checkNotNull(operation, "PendingIntent cannot be null.");
3765 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3766 enforceNetworkRequestPermissions(networkCapabilities);
3767 enforceMeteredApnPolicy(networkCapabilities);
Lorenzo Colitti260a36d2015-07-08 12:49:04 +09003768 ensureRequestableCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003769
3770 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3771 nextNetworkRequestId());
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003772 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3773 NetworkRequestInfo.REQUEST);
Erik Kline7523eb32015-07-09 18:24:03 +09003774 if (DBG) log("pendingRequest for " + nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003775 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3776 nri));
3777 return networkRequest;
3778 }
3779
Jeremy Joslin79294842014-12-03 17:15:28 -08003780 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3781 mHandler.sendMessageDelayed(
3782 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3783 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3784 }
3785
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003786 @Override
3787 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003788 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003789 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3790 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003791 }
3792
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003793 // In order to implement the compatibility measure for pre-M apps that call
3794 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3795 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3796 // This ensures it has permission to do so.
3797 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3798 if (nc == null) {
3799 return false;
3800 }
3801 int[] transportTypes = nc.getTransportTypes();
3802 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3803 return false;
3804 }
3805 try {
3806 mContext.enforceCallingOrSelfPermission(
3807 android.Manifest.permission.ACCESS_WIFI_STATE,
3808 "ConnectivityService");
3809 } catch (SecurityException e) {
3810 return false;
3811 }
3812 return true;
3813 }
3814
Robert Greenwalt9258c642014-03-26 16:47:06 -07003815 @Override
3816 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3817 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003818 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3819 enforceAccessPermission();
3820 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003821
Erik Kline7523eb32015-07-09 18:24:03 +09003822 NetworkRequest networkRequest = new NetworkRequest(
3823 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003824 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3825 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003826 if (DBG) log("listenForNetwork for " + nri);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003827
3828 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3829 return networkRequest;
3830 }
3831
3832 @Override
3833 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3834 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003835 checkNotNull(operation, "PendingIntent cannot be null.");
3836 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3837 enforceAccessPermission();
3838 }
3839
Erik Kline7523eb32015-07-09 18:24:03 +09003840 NetworkRequest networkRequest = new NetworkRequest(
3841 new NetworkCapabilities(networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Paul Jensen694f2b82015-06-17 14:15:39 -04003842 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3843 NetworkRequestInfo.LISTEN);
Erik Kline7523eb32015-07-09 18:24:03 +09003844 if (DBG) log("pendingListenForNetwork for " + nri);
Paul Jensen694f2b82015-06-17 14:15:39 -04003845
3846 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003847 }
3848
3849 @Override
3850 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003851 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3852 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003853 }
3854
3855 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003856 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003857 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003858 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3859 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003860 }
3861
Robert Greenwalta67be032014-05-16 15:49:14 -07003862 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003863 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003864 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3865 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3866 }
3867
3868 @Override
3869 public void unregisterNetworkFactory(Messenger messenger) {
3870 enforceConnectivityInternalPermission();
3871 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3872 }
3873
3874 private void handleUnregisterNetworkFactory(Messenger messenger) {
3875 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3876 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003877 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003878 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003879 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003880 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003881 }
3882
Robert Greenwalt7b816022014-04-18 15:25:25 -07003883 /**
3884 * NetworkAgentInfo supporting a request by requestId.
3885 * These have already been vetted (their Capabilities satisfy the request)
3886 * and the are the highest scored network available.
3887 * the are keyed off the Requests requestId.
3888 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003889 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003890 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3891 new SparseArray<NetworkAgentInfo>();
3892
Paul Jensen31a94f42015-02-13 14:18:39 -05003893 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3894 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003895 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3896 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003897 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3898 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3899 // there may not be a strict 1:1 correlation between the two.
3900 @GuardedBy("mNetworkForNetId")
3901 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003902
Robert Greenwalt7b816022014-04-18 15:25:25 -07003903 // NetworkAgentInfo keyed off its connecting messenger
3904 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003905 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003906 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3907 new HashMap<Messenger, NetworkAgentInfo>();
3908
Paul Jensen2c311d62014-11-17 12:34:51 -05003909 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003910 private final NetworkRequest mDefaultRequest;
3911
Erik Klineda4bfa82015-04-30 12:58:40 +09003912 // Request used to optionally keep mobile data active even when higher
3913 // priority networks like Wi-Fi are active.
3914 private final NetworkRequest mDefaultMobileDataRequest;
3915
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003916 private NetworkAgentInfo getDefaultNetwork() {
3917 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3918 }
3919
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003920 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003921 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003922 }
3923
Paul Jensen31a94f42015-02-13 14:18:39 -05003924 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003925 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003926 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003927 enforceConnectivityInternalPermission();
3928
Paul Jensen2c311d62014-11-17 12:34:51 -05003929 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3930 // satisfies mDefaultRequest.
Paul Jensencf4c2c62015-07-01 14:16:32 -04003931 final NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003932 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3933 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
Paul Jensencf4c2c62015-07-01 14:16:32 -04003934 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest, this);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003935 synchronized (this) {
3936 nai.networkMonitor.systemReady = mSystemReady;
3937 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003938 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003939 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003940 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003941 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003942 }
3943
3944 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3945 if (VDBG) log("Got NetworkAgent Messenger");
3946 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003947 synchronized (mNetworkForNetId) {
3948 mNetworkForNetId.put(na.network.netId, na);
3949 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003950 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3951 NetworkInfo networkInfo = na.networkInfo;
3952 na.networkInfo = null;
3953 updateNetworkInfo(na, networkInfo);
3954 }
3955
3956 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3957 LinkProperties newLp = networkAgent.linkProperties;
3958 int netId = networkAgent.network.netId;
3959
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003960 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3961 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003962 if (networkAgent.clatd != null) {
3963 networkAgent.clatd.fixupLinkProperties(oldLp);
3964 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003965
Paul Jensen992f2522014-04-28 10:33:11 -04003966 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003967 updateMtu(newLp, oldLp);
3968 // TODO - figure out what to do for clat
3969// for (LinkProperties lp : newLp.getStackedLinks()) {
3970// updateMtu(lp, null);
3971// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003972 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003973
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003974 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3975 // In L, we used it only when the network had Internet access but provided no DNS servers.
3976 // For now, just disable it, and if disabling it doesn't break things, remove it.
3977 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3978 // NET_CAPABILITY_INTERNET);
3979 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003980 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003981 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3982
Paul Jensen3b759822014-05-13 11:44:01 -04003983 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003984 if (isDefaultNetwork(networkAgent)) {
3985 handleApplyDefaultProxy(newLp.getHttpProxy());
3986 } else {
3987 updateProxy(newLp, oldLp, networkAgent);
3988 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003989 // TODO - move this check to cover the whole function
3990 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003991 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003992 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3993 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09003994
3995 mKeepaliveTracker.handleCheckKeepalivesStillValid(networkAgent);
Paul Jensen3b759822014-05-13 11:44:01 -04003996 }
3997
Lorenzo Colitti95439462014-10-09 13:44:48 +09003998 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3999 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
4000 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04004001
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004002 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004003 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
4004 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09004005 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09004006 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04004007 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004008 }
Paul Jensen992f2522014-04-28 10:33:11 -04004009
4010 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
4011 CompareResult<String> interfaceDiff = new CompareResult<String>();
4012 if (oldLp != null) {
4013 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
4014 } else if (newLp != null) {
4015 interfaceDiff.added = newLp.getAllInterfaceNames();
4016 }
4017 for (String iface : interfaceDiff.added) {
4018 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004019 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004020 mNetd.addInterfaceToNetwork(iface, netId);
4021 } catch (Exception e) {
4022 loge("Exception adding interface: " + e);
4023 }
4024 }
4025 for (String iface : interfaceDiff.removed) {
4026 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004027 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04004028 mNetd.removeInterfaceFromNetwork(iface, netId);
4029 } catch (Exception e) {
4030 loge("Exception removing interface: " + e);
4031 }
4032 }
4033 }
4034
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004035 /**
4036 * Have netd update routes from oldLp to newLp.
4037 * @return true if routes changed between oldLp and newLp
4038 */
4039 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004040 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
4041 if (oldLp != null) {
4042 routeDiff = oldLp.compareAllRoutes(newLp);
4043 } else if (newLp != null) {
4044 routeDiff.added = newLp.getAllRoutes();
4045 }
4046
4047 // add routes before removing old in case it helps with continuous connectivity
4048
4049 // do this twice, adding non-nexthop routes first, then routes they are dependent on
4050 for (RouteInfo route : routeDiff.added) {
4051 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004052 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004053 try {
4054 mNetd.addRoute(netId, route);
4055 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004056 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
4057 loge("Exception in addRoute for non-gateway: " + e);
4058 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004059 }
4060 }
4061 for (RouteInfo route : routeDiff.added) {
4062 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004063 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004064 try {
4065 mNetd.addRoute(netId, route);
4066 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004067 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
4068 loge("Exception in addRoute for gateway: " + e);
4069 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004070 }
4071 }
4072
4073 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004074 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004075 try {
4076 mNetd.removeRoute(netId, route);
4077 } catch (Exception e) {
4078 loge("Exception in removeRoute: " + e);
4079 }
4080 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004081 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004082 }
Erik Kline41368502015-06-17 13:19:54 +09004083
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004084 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4085 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004086 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Klineb36a3132015-06-26 19:21:34 +09004087 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004088 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004089 dnses = new ArrayList();
4090 dnses.add(mDefaultDns);
4091 if (DBG) {
4092 loge("no dns provided for netId " + netId + ", so using defaults");
4093 }
4094 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004095 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004096 try {
4097 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4098 newLp.getDomains());
4099 } catch (Exception e) {
4100 loge("Exception in setDnsServersForNetwork: " + e);
4101 }
Paul Jensen85cf78e2015-06-25 13:25:07 -04004102 final NetworkAgentInfo defaultNai = getDefaultNetwork();
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004103 if (defaultNai != null && defaultNai.network.netId == netId) {
4104 setDefaultDnsSystemProperties(dnses);
4105 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004106 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004107 } else if (flush) {
4108 try {
4109 mNetd.flushNetworkDnsCache(netId);
4110 } catch (Exception e) {
4111 loge("Exception in flushNetworkDnsCache: " + e);
4112 }
4113 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004114 }
4115 }
4116
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004117 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4118 int last = 0;
4119 for (InetAddress dns : dnses) {
4120 ++last;
4121 String key = "net.dns" + last;
4122 String value = dns.getHostAddress();
4123 SystemProperties.set(key, value);
4124 }
4125 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4126 String key = "net.dns" + i;
4127 SystemProperties.set(key, "");
4128 }
4129 mNumDnsEntries = last;
4130 }
4131
Paul Jensen3d194ea2015-06-16 14:27:36 -04004132 /**
4133 * Update the NetworkCapabilities for {@code networkAgent} to {@code networkCapabilities}
4134 * augmented with any stateful capabilities implied from {@code networkAgent}
4135 * (e.g., validated status and captive portal status).
4136 *
Paul Jensene0988542015-06-25 15:30:08 -04004137 * @param nai the network having its capabilities updated.
Paul Jensen3d194ea2015-06-16 14:27:36 -04004138 * @param networkCapabilities the new network capabilities.
4139 */
Paul Jensene0988542015-06-25 15:30:08 -04004140 private void updateCapabilities(NetworkAgentInfo nai, NetworkCapabilities networkCapabilities) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004141 // Don't modify caller's NetworkCapabilities.
4142 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Paul Jensene0988542015-06-25 15:30:08 -04004143 if (nai.lastValidated) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004144 networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4145 } else {
4146 networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
4147 }
Paul Jensene0988542015-06-25 15:30:08 -04004148 if (nai.lastCaptivePortalDetected) {
Paul Jensen3d194ea2015-06-16 14:27:36 -04004149 networkCapabilities.addCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4150 } else {
4151 networkCapabilities.removeCapability(NET_CAPABILITY_CAPTIVE_PORTAL);
4152 }
Paul Jensene0988542015-06-25 15:30:08 -04004153 if (!Objects.equals(nai.networkCapabilities, networkCapabilities)) {
4154 final int oldScore = nai.getCurrentScore();
Paul Jensen487ffe72015-07-24 15:57:11 -04004155 if (nai.networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) !=
4156 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED)) {
4157 try {
4158 mNetd.setNetworkPermission(nai.network.netId,
4159 networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) ?
4160 null : NetworkManagementService.PERMISSION_SYSTEM);
4161 } catch (RemoteException e) {
4162 loge("Exception in setNetworkPermission: " + e);
4163 }
4164 }
Paul Jensene0988542015-06-25 15:30:08 -04004165 synchronized (nai) {
4166 nai.networkCapabilities = networkCapabilities;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004167 }
Paul Jensene0988542015-06-25 15:30:08 -04004168 rematchAllNetworksAndRequests(nai, oldScore);
4169 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004170 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004171 }
4172
Paul Jensenc8b9a742014-09-30 15:37:41 -04004173 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4174 for (int i = 0; i < nai.networkRequests.size(); i++) {
4175 NetworkRequest nr = nai.networkRequests.valueAt(i);
4176 // Don't send listening requests to factories. b/17393458
4177 if (!isRequest(nr)) continue;
4178 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4179 }
4180 }
4181
Robert Greenwalt7b816022014-04-18 15:25:25 -07004182 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4183 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004184 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004185 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4186 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004187 }
4188 }
4189
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004190 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4191 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004192 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004193 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004194 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4195 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004196 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004197 sendIntent(nri.mPendingIntent, intent);
4198 }
4199 // else not handled
4200 }
4201
4202 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4203 mPendingIntentWakeLock.acquire();
4204 try {
4205 if (DBG) log("Sending " + pendingIntent);
4206 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4207 } catch (PendingIntent.CanceledException e) {
4208 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4209 mPendingIntentWakeLock.release();
4210 releasePendingNetworkRequest(pendingIntent);
4211 }
4212 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4213 }
4214
4215 @Override
4216 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4217 String resultData, Bundle resultExtras) {
4218 if (DBG) log("Finished sending " + pendingIntent);
4219 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004220 // Release with a delay so the receiving client has an opportunity to put in its
4221 // own request.
4222 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004223 }
4224
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004226 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004227 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004228 Bundle bundle = new Bundle();
4229 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4230 new NetworkRequest(nri.request));
4231 Message msg = Message.obtain();
4232 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4233 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4234 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4235 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004236 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004237 case ConnectivityManager.CALLBACK_LOSING: {
4238 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4239 break;
4240 }
4241 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4242 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4243 new NetworkCapabilities(networkAgent.networkCapabilities));
4244 break;
4245 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004246 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004247 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4248 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004249 break;
4250 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004251 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004252 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004253 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004254 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004255 if (VDBG) {
4256 log("sending notification " + notifyTypeToName(notificationType) +
4257 " for " + nri.request);
4258 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004259 nri.messenger.send(msg);
4260 } catch (RemoteException e) {
4261 // may occur naturally in the race of binder death.
4262 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4263 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004264 }
4265
Paul Jensenc8b9a742014-09-30 15:37:41 -04004266 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4267 for (int i = 0; i < nai.networkRequests.size(); i++) {
4268 NetworkRequest nr = nai.networkRequests.valueAt(i);
4269 // Ignore listening requests.
4270 if (!isRequest(nr)) continue;
4271 loge("Dead network still had at least " + nr);
4272 break;
4273 }
4274 nai.asyncChannel.disconnect();
4275 }
4276
Robert Greenwalt7b816022014-04-18 15:25:25 -07004277 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4278 if (oldNetwork == null) {
4279 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4280 return;
4281 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004282 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4283 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004284 }
4285
Paul Jensen27b02b72014-07-14 12:03:33 -04004286 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004287 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004288 setupDataActivityTracking(newNetwork);
4289 try {
4290 mNetd.setDefaultNetId(newNetwork.network.netId);
4291 } catch (Exception e) {
4292 loge("Exception setting default network :" + e);
4293 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004294 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004295 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004296 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004297 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004298 }
4299
Paul Jensen2161a8e2014-09-11 11:00:39 -04004300 // Handles a network appearing or improving its score.
4301 //
4302 // - Evaluates all current NetworkRequests that can be
4303 // satisfied by newNetwork, and reassigns to newNetwork
4304 // any such requests for which newNetwork is the best.
4305 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004306 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004307 // needed. A network is needed if it is the best network for
4308 // one or more NetworkRequests, or if it is a VPN.
4309 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004310 // - Tears down newNetwork if it just became validated
Paul Jensen85cf78e2015-06-25 13:25:07 -04004311 // but turns out to be unneeded.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004312 //
4313 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4314 // networks that have no chance (i.e. even if validated)
4315 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004316 //
4317 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4318 // it does not remove NetworkRequests that other Networks could better satisfy.
4319 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4320 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4321 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004322 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004323 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004324 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4325 // performed to tear down unvalidated networks that have no chance (i.e. even if
4326 // validated) of becoming the highest scoring network.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004327 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004328 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004329 if (!newNetwork.created) return;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004330 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004332 NetworkAgentInfo oldDefaultNetwork = null;
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004333 if (VDBG) log("rematching " + newNetwork.name());
Paul Jensen2161a8e2014-09-11 11:00:39 -04004334 // Find and migrate to this Network any NetworkRequests for
4335 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004336 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004337 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004338 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004339 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Paul Jensencf4c2c62015-07-01 14:16:32 -04004340 final NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4341 final boolean satisfies = newNetwork.satisfies(nri.request);
4342 if (newNetwork == currentNetwork && satisfies) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004343 if (VDBG) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004344 log("Network " + newNetwork.name() + " was already satisfying" +
4345 " request " + nri.request.requestId + ". No change.");
4346 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004347 keep = true;
4348 continue;
4349 }
4350
4351 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004352 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensencf4c2c62015-07-01 14:16:32 -04004353 if (satisfies) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004354 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004355 // This is not a request, it's a callback listener.
4356 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004357 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004358 continue;
4359 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004360
Robert Greenwalt7b816022014-04-18 15:25:25 -07004361 // next check if it's better than any current network we're using for
4362 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004363 if (VDBG) {
4364 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004365 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4366 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004367 }
4368 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004369 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalta9ebeef2015-09-03 16:41:45 -07004370 if (DBG) log("rematch for " + newNetwork.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004371 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004372 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004373 currentNetwork.networkRequests.remove(nri.request.requestId);
4374 currentNetwork.networkLingered.add(nri.request);
4375 affectedNetworks.add(currentNetwork);
4376 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004377 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004378 }
Paul Jensen573a0352015-01-08 10:49:34 -05004379 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004380 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004381 if (!newNetwork.addRequest(nri.request)) {
4382 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4383 }
4384 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004385 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004386 // Tell NetworkFactories about the new score, so they can stop
4387 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004388 // TODO - this could get expensive if we have alot of requests for this
4389 // network. Think about if there is a way to reduce this. Push
4390 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004391 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004392 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004393 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004394 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004395 }
4396 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004397 } else if (newNetwork.networkRequests.get(nri.request.requestId) != null) {
4398 // If "newNetwork" is listed as satisfying "nri" but no longer satisfies "nri",
4399 // mark it as no longer satisfying "nri". Because networks are processed by
4400 // rematchAllNetworkAndRequests() in descending score order, "currentNetwork" will
4401 // match "newNetwork" before this loop will encounter a "currentNetwork" with higher
4402 // score than "newNetwork" and where "currentNetwork" no longer satisfies "nri".
4403 // This means this code doesn't have to handle the case where "currentNetwork" no
4404 // longer satisfies "nri" when "currentNetwork" does not equal "newNetwork".
4405 if (DBG) {
4406 log("Network " + newNetwork.name() + " stopped satisfying" +
4407 " request " + nri.request.requestId);
4408 }
4409 newNetwork.networkRequests.remove(nri.request.requestId);
4410 if (currentNetwork == newNetwork) {
4411 mNetworkForRequestId.remove(nri.request.requestId);
4412 sendUpdatedScoreToFactories(nri.request, 0);
4413 } else {
4414 if (nri.isRequest == true) {
4415 Slog.wtf(TAG, "BUG: Removing request " + nri.request.requestId + " from " +
4416 newNetwork.name() +
4417 " without updating mNetworkForRequestId or factories!");
4418 }
4419 }
4420 // TODO: technically, sending CALLBACK_LOST here is
4421 // incorrect if nri is a request (not a listen) and there
4422 // is a replacement network currently connected that can
4423 // satisfy it. However, the only capability that can both
4424 // a) be requested and b) change is NET_CAPABILITY_TRUSTED,
4425 // so this code is only incorrect for a network that loses
4426 // the TRUSTED capability, which is a rare case.
4427 callCallbackForRequest(nri, newNetwork, ConnectivityManager.CALLBACK_LOST);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004428 }
4429 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004430 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004431 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensene0988542015-06-25 15:30:08 -04004432 if (nai.lingering) {
4433 // Already lingered. Nothing to do. This can only happen if "nai" is in
4434 // "affectedNetworks" twice. The reasoning being that to get added to
4435 // "affectedNetworks", "nai" must have been satisfying a NetworkRequest
4436 // (i.e. not lingered) so it could have only been lingered by this loop.
4437 // unneeded(nai) will be false and we'll call unlinger() below which would
4438 // be bad, so handle it here.
4439 } else if (unneeded(nai)) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004440 linger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004441 } else {
Paul Jensene0988542015-06-25 15:30:08 -04004442 // Clear nai.networkLingered we might have added above.
Paul Jensen0cc17322014-11-25 15:26:53 -05004443 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004444 }
4445 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004446 if (isNewDefault) {
4447 // Notify system services that this network is up.
4448 makeDefault(newNetwork);
4449 synchronized (ConnectivityService.this) {
4450 // have a new default network, release the transition wakelock in
4451 // a second if it's held. The second pause is to allow apps
4452 // to reconnect over the new network
4453 if (mNetTransitionWakeLock.isHeld()) {
4454 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4455 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4456 mNetTransitionWakeLockSerialNumber, 0),
4457 1000);
4458 }
4459 }
4460 }
4461
4462 // do this after the default net is switched, but
4463 // before LegacyTypeTracker sends legacy broadcasts
4464 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
4465
4466 if (isNewDefault) {
4467 // Maintain the illusion: since the legacy API only
4468 // understands one network at a time, we must pretend
4469 // that the current default network disconnected before
4470 // the new one connected.
4471 if (oldDefaultNetwork != null) {
4472 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4473 oldDefaultNetwork, true);
4474 }
4475 mDefaultInetConditionPublished = newNetwork.lastValidated ? 100 : 0;
4476 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4477 notifyLockdownVpn(newNetwork);
4478 }
4479
Robert Greenwalt7b816022014-04-18 15:25:25 -07004480 if (keep) {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004481 // Notify battery stats service about this network, both the normal
4482 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004483 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004484 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004485 final IBatteryStats bs = BatteryStatsService.getService();
4486 final int type = newNetwork.networkInfo.getType();
4487
4488 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4489 bs.noteNetworkInterfaceType(baseIface, type);
4490 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4491 final String stackedIface = stacked.getInterfaceName();
4492 bs.noteNetworkInterfaceType(stackedIface, type);
4493 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4494 }
4495 } catch (RemoteException ignored) {
4496 }
4497
Robert Greenwalt152ed372014-12-17 17:19:53 -08004498 // This has to happen after the notifyNetworkCallbacks as that tickles each
4499 // ConnectivityManager instance so that legacy requests correctly bind dns
4500 // requests to this network. The legacy users are listening for this bcast
4501 // and will generally do a dns request so they can ensureRouteToHost and if
4502 // they do that before the callbacks happen they'll use the default network.
4503 //
4504 // TODO: Is there still a race here? We send the broadcast
4505 // after sending the callback, but if the app can receive the
4506 // broadcast before the callback, it might still break.
4507 //
4508 // This *does* introduce a race where if the user uses the new api
4509 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4510 // they may get old info. Reverse this after the old startUsing api is removed.
4511 // This is on top of the multiple intent sequencing referenced in the todo above.
4512 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4513 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4514 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4515 // legacy type tracker filters out repeat adds
4516 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4517 }
4518 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004519
4520 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4521 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4522 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4523 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4524 if (newNetwork.isVPN()) {
4525 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4526 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004527 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004528 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4529 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004530 if (unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004531 if (DBG) log("Reaping " + nai.name());
4532 teardownUnneededNetwork(nai);
4533 }
4534 }
4535 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004536 }
4537
Paul Jensen1c7ba022015-06-16 14:27:36 -04004538 /**
4539 * Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4540 * being disconnected.
4541 * @param changed If only one Network's score or capabilities have been modified since the last
4542 * time this function was called, pass this Network in this argument, otherwise pass
4543 * null.
4544 * @param oldScore If only one Network has been changed but its NetworkCapabilities have not
4545 * changed, pass in the Network's score (from getCurrentScore()) prior to the change via
4546 * this argument, otherwise pass {@code changed.getCurrentScore()} or 0 if
4547 * {@code changed} is {@code null}. This is because NetworkCapabilities influence a
4548 * network's score.
Paul Jensen1c7ba022015-06-16 14:27:36 -04004549 */
Paul Jensen85cf78e2015-06-25 13:25:07 -04004550 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004551 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4552 // to avoid the slowness. It is not simply enough to process just "changed", for
4553 // example in the case where "changed"'s score decreases and another network should begin
4554 // satifying a NetworkRequest that "changed" currently satisfies.
4555
4556 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4557 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4558 // rematchNetworkAndRequests() handles.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004559 if (changed != null && oldScore < changed.getCurrentScore()) {
4560 rematchNetworkAndRequests(changed, ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004561 } else {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004562 final NetworkAgentInfo[] nais = mNetworkAgentInfos.values().toArray(
4563 new NetworkAgentInfo[mNetworkAgentInfos.size()]);
4564 // Rematch higher scoring networks first to prevent requests first matching a lower
4565 // scoring network and then a higher scoring network, which could produce multiple
4566 // callbacks and inadvertently unlinger networks.
4567 Arrays.sort(nais);
4568 for (NetworkAgentInfo nai : nais) {
4569 rematchNetworkAndRequests(nai,
Paul Jensenb10e37f2014-11-25 12:33:08 -05004570 // Only reap the last time through the loop. Reaping before all rematching
4571 // is complete could incorrectly teardown a network that hasn't yet been
4572 // rematched.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004573 (nai != nais[nais.length-1]) ? ReapUnvalidatedNetworks.DONT_REAP
Paul Jensenb10e37f2014-11-25 12:33:08 -05004574 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004575 }
4576 }
4577 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004578
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004579 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004580 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004581 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004582 // For now only update icons for default connection.
4583 // TODO: Update WiFi and cellular icons separately. b/17237507
4584 if (!isDefaultNetwork(nai)) return;
4585
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004586 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004587 // Don't repeat publish.
4588 if (newInetCondition == mDefaultInetConditionPublished) return;
4589
4590 mDefaultInetConditionPublished = newInetCondition;
4591 sendInetConditionBroadcast(nai.networkInfo);
4592 }
4593
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004594 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4595 if (mLockdownTracker != null) {
4596 if (nai != null && nai.isVPN()) {
4597 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4598 } else {
4599 mLockdownTracker.onNetworkInfoChanged();
4600 }
4601 }
4602 }
4603
Robert Greenwalt7b816022014-04-18 15:25:25 -07004604 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4605 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004606 NetworkInfo oldInfo = null;
Robert Greenwalt8d482522015-06-24 13:23:42 -07004607 final int oldScore = networkAgent.getCurrentScore();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004608 synchronized (networkAgent) {
4609 oldInfo = networkAgent.networkInfo;
4610 networkAgent.networkInfo = newInfo;
4611 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004612 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004613
4614 if (oldInfo != null && oldInfo.getState() == state) {
4615 if (VDBG) log("ignoring duplicate network state non-change");
4616 return;
4617 }
4618 if (DBG) {
4619 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4620 (oldInfo == null ? "null" : oldInfo.getState()) +
4621 " to " + state);
4622 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004623
Paul Jenseneec75412014-08-04 12:21:19 -04004624 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004625 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004626 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004627 if (networkAgent.isVPN()) {
4628 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004629 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4630 (networkAgent.networkMisc == null ||
4631 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004632 } else {
Paul Jensen487ffe72015-07-24 15:57:11 -04004633 mNetd.createPhysicalNetwork(networkAgent.network.netId,
4634 networkAgent.networkCapabilities.hasCapability(
4635 NET_CAPABILITY_NOT_RESTRICTED) ?
4636 null : NetworkManagementService.PERMISSION_SYSTEM);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004637 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004638 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004639 loge("Error creating network " + networkAgent.network.netId + ": "
4640 + e.getMessage());
4641 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004642 }
Paul Jenseneec75412014-08-04 12:21:19 -04004643 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004644 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004645 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004646
Paul Jensenca8f16a2014-05-09 12:47:55 -04004647 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004648 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004649
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004650 if (networkAgent.isVPN()) {
4651 // Temporarily disable the default proxy (not global).
4652 synchronized (mProxyLock) {
4653 if (!mDefaultProxyDisabled) {
4654 mDefaultProxyDisabled = true;
4655 if (mGlobalProxy == null && mDefaultProxy != null) {
4656 sendProxyBroadcast(null);
4657 }
4658 }
4659 }
4660 // TODO: support proxy per network.
4661 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004662
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004663 // Whether a particular NetworkRequest listen should cause signal strength thresholds to
4664 // be communicated to a particular NetworkAgent depends only on the network's immutable,
4665 // capabilities, so it only needs to be done once on initial connect, not every time the
4666 // network's capabilities change. Note that we do this before rematching the network,
4667 // so we could decide to tear it down immediately afterwards. That's fine though - on
4668 // disconnection NetworkAgents should stop any signal strength monitoring they have been
4669 // doing.
Lorenzo Colitti6bc0a2b2015-09-15 15:56:01 +09004670 updateSignalStrengthThresholds(networkAgent, "CONNECT", null);
Lorenzo Colittic3f21f32015-07-06 23:50:27 +09004671
Paul Jensen2161a8e2014-09-11 11:00:39 -04004672 // Consider network even though it is not yet validated.
Paul Jensen85cf78e2015-06-25 13:25:07 -04004673 rematchNetworkAndRequests(networkAgent, ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004674
4675 // This has to happen after matching the requests, because callbacks are just requests.
4676 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004677 } else if (state == NetworkInfo.State.DISCONNECTED) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004678 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004679 if (networkAgent.isVPN()) {
4680 synchronized (mProxyLock) {
4681 if (mDefaultProxyDisabled) {
4682 mDefaultProxyDisabled = false;
4683 if (mGlobalProxy == null && mDefaultProxy != null) {
4684 sendProxyBroadcast(mDefaultProxy);
4685 }
4686 }
4687 }
4688 }
Robert Greenwalt8d482522015-06-24 13:23:42 -07004689 } else if ((oldInfo != null && oldInfo.getState() == NetworkInfo.State.SUSPENDED) ||
4690 state == NetworkInfo.State.SUSPENDED) {
4691 // going into or coming out of SUSPEND: rescore and notify
4692 if (networkAgent.getCurrentScore() != oldScore) {
Paul Jensen3b9ce372015-07-10 12:19:38 -04004693 rematchAllNetworksAndRequests(networkAgent, oldScore);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004694 }
4695 notifyNetworkCallbacks(networkAgent, (state == NetworkInfo.State.SUSPENDED ?
4696 ConnectivityManager.CALLBACK_SUSPENDED :
4697 ConnectivityManager.CALLBACK_RESUMED));
4698 mLegacyTypeTracker.update(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004699 }
4700 }
4701
Robert Greenwaltac96c522014-06-03 16:43:57 -07004702 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4703 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004704 if (score < 0) {
4705 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4706 "). Bumping score to min of 0");
4707 score = 0;
4708 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004709
Paul Jensen2161a8e2014-09-11 11:00:39 -04004710 final int oldScore = nai.getCurrentScore();
4711 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004712
Paul Jensen85cf78e2015-06-25 13:25:07 -04004713 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004714
Paul Jensenc8b9a742014-09-30 15:37:41 -04004715 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004716 }
4717
Robert Greenwalt9258c642014-03-26 16:47:06 -07004718 // notify only this one new request of the current state
4719 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4720 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4721 // TODO - read state from monitor to decide what to send.
4722// if (nai.networkMonitor.isLingering()) {
4723// notifyType = NetworkCallbacks.LOSING;
4724// } else if (nai.networkMonitor.isEvaluating()) {
4725// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4726// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004727 if (nri.mPendingIntent == null) {
4728 callCallbackForRequest(nri, nai, notifyType);
4729 } else {
4730 sendPendingIntentForRequest(nri, nai, notifyType);
4731 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004732 }
4733
Robert Greenwalt8d482522015-06-24 13:23:42 -07004734 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, DetailedState state, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004735 // The NetworkInfo we actually send out has no bearing on the real
4736 // state of affairs. For example, if the default connection is mobile,
4737 // and a request for HIPRI has just gone away, we need to pretend that
4738 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4739 // the state to DISCONNECTED, even though the network is of type MOBILE
4740 // and is still connected.
4741 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4742 info.setType(type);
Robert Greenwalt8d482522015-06-24 13:23:42 -07004743 if (state != DetailedState.DISCONNECTED) {
4744 info.setDetailedState(state, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004745 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004746 } else {
Robert Greenwalt8d482522015-06-24 13:23:42 -07004747 info.setDetailedState(state, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004748 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4749 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4750 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4751 if (info.isFailover()) {
4752 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4753 nai.networkInfo.setFailover(false);
4754 }
4755 if (info.getReason() != null) {
4756 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4757 }
4758 if (info.getExtraInfo() != null) {
4759 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4760 }
4761 NetworkAgentInfo newDefaultAgent = null;
4762 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
Paul Jensen85cf78e2015-06-25 13:25:07 -04004763 newDefaultAgent = getDefaultNetwork();
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004764 if (newDefaultAgent != null) {
4765 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4766 newDefaultAgent.networkInfo);
4767 } else {
4768 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4769 }
4770 }
4771 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4772 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004773 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004774 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004775 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004776 }
4777 }
4778 }
4779
Robert Greenwalt7b816022014-04-18 15:25:25 -07004780 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004781 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004782 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004783 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4784 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4785 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004786 if (nri.mPendingIntent == null) {
4787 callCallbackForRequest(nri, networkAgent, notifyType);
4788 } else {
4789 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4790 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004791 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004792 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004793
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004794 private String notifyTypeToName(int notifyType) {
4795 switch (notifyType) {
4796 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4797 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4798 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4799 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4800 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4801 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4802 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4803 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4804 }
4805 return "UNKNOWN";
4806 }
4807
Jeff Sharkey69736342014-12-08 14:50:12 -08004808 /**
4809 * Notify other system services that set of active ifaces has changed.
4810 */
4811 private void notifyIfacesChanged() {
4812 try {
4813 mStatsService.forceUpdateIfaces();
4814 } catch (Exception ignored) {
4815 }
4816 }
4817
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004818 @Override
4819 public boolean addVpnAddress(String address, int prefixLength) {
4820 throwIfLockdownEnabled();
4821 int user = UserHandle.getUserId(Binder.getCallingUid());
4822 synchronized (mVpns) {
4823 return mVpns.get(user).addAddress(address, prefixLength);
4824 }
4825 }
4826
4827 @Override
4828 public boolean removeVpnAddress(String address, int prefixLength) {
4829 throwIfLockdownEnabled();
4830 int user = UserHandle.getUserId(Binder.getCallingUid());
4831 synchronized (mVpns) {
4832 return mVpns.get(user).removeAddress(address, prefixLength);
4833 }
4834 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004835
4836 @Override
4837 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4838 throwIfLockdownEnabled();
4839 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004840 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004841 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004842 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004843 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004844 if (success) {
4845 notifyIfacesChanged();
4846 }
4847 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004848 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004849
4850 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004851 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4852 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4853 enforceKeepalivePermission();
4854 mKeepaliveTracker.startNattKeepalive(
4855 getNetworkAgentInfoForNetwork(network),
4856 intervalSeconds, messenger, binder,
4857 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4858 }
4859
4860 @Override
4861 public void stopKeepalive(Network network, int slot) {
4862 mHandler.sendMessage(mHandler.obtainMessage(
4863 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4864 }
4865
4866 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07004867 public void factoryReset() {
4868 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004869
4870 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4871 return;
4872 }
4873
Robin Lee3b3dd942015-05-12 18:14:58 +01004874 final int userId = UserHandle.getCallingUserId();
4875
Stuart Scottf1fb3972015-04-02 18:00:02 -07004876 // Turn airplane mode off
4877 setAirplaneMode(false);
4878
Stuart Scotte3e314d2015-04-20 14:07:45 -07004879 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4880 // Untether
4881 for (String tether : getTetheredIfaces()) {
4882 untether(tether);
4883 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004884 }
4885
Stuart Scotte3e314d2015-04-20 14:07:45 -07004886 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4887 // Turn VPN off
4888 VpnConfig vpnConfig = getVpnConfig(userId);
4889 if (vpnConfig != null) {
4890 if (vpnConfig.legacy) {
4891 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4892 } else {
4893 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4894 // in the future without user intervention.
4895 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004896
Stuart Scotte3e314d2015-04-20 14:07:45 -07004897 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4898 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004899 }
4900 }
4901 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004902
4903 @VisibleForTesting
4904 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4905 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4906 return new NetworkMonitor(context, handler, nai, defaultRequest);
4907 }
4908
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004909}