blob: 37a6c02439969d1c09640b6c0ba9f705e73eccac [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;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080037import android.app.BroadcastOptions;
Wink Savilleab9321d2013-06-29 21:10:57 -070038import android.app.Notification;
39import android.app.NotificationManager;
40import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070041import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080042import android.content.ContentResolver;
43import android.content.Context;
44import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070045import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080046import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070047import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090048import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070049import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080050import android.net.ConnectivityManager;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +090051import android.net.ConnectivityManager.PacketKeepalive;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080052import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070053import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070054import android.net.INetworkPolicyListener;
55import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070056import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080057import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070058import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070059import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070060import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070061import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070062import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080063import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070064import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070065import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070066import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070067import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070068import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070069import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070070import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040071import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070072import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040073import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040074import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Binder;
Dianne Hackborne0e413e2015-12-09 17:22:26 -080076import android.os.Build;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070077import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040078import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070080import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070082import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.Looper;
84import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070085import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070086import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070087import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070088import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070090import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080091import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070092import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040093import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070095import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070096import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070097import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070098import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070099import android.util.LocalLog;
100import android.util.LocalLog.ReadOnlyLocalLog;
101import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -0800102import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700103import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500104import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700105import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700106import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800107
Wink Savilleab9321d2013-06-29 21:10:57 -0700108import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400109import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400110import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700111import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700112import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700113import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700114import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800115import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700116import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700117import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700118import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700119import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700120import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700121import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400122import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900123import com.android.server.connectivity.KeepaliveTracker;
Erik Kline379747a2015-06-05 17:47:34 +0900124import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900125import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700126import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400127import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400128import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700129import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800130import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700131import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700132import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700133import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700134import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700135import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700136
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700137import org.xmlpull.v1.XmlPullParser;
138import org.xmlpull.v1.XmlPullParserException;
139
140import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800141import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700142import java.io.FileNotFoundException;
143import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700144import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700146import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700147import java.net.InetAddress;
148import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700149import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700150import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700151import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700152import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700153import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700154import java.util.HashSet;
Lorenzo Colittic3f21f32015-07-06 23:50:27 +0900155import java.util.SortedSet;
156import java.util.TreeSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500157import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700158import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700159import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700160import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700161import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800162
163/**
164 * @hide
165 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800166public class ConnectivityService extends IConnectivityManager.Stub
167 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700168 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800169
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700170 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700171 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800172
Jake Hamby786e71a2014-02-06 14:43:50 -0800173 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700174
Jeff Sharkey899223b2012-08-04 15:24:58 -0700175 // TODO: create better separation between radio types and network types
176
Robert Greenwalt42acef32009-08-12 16:08:25 -0700177 // how long to wait before switching back to a radio's default network
178 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
179 // system property that can override the above value
180 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
181 "android.telephony.apn-restore";
182
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900183 // How long to wait before putting up a "This network doesn't have an Internet connection,
184 // connect anyway?" dialog after the user selects a network that doesn't validate.
185 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
186
Jeremy Joslin79294842014-12-03 17:15:28 -0800187 // How long to delay to removal of a pending intent based request.
188 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
189 private final int mReleasePendingIntentDelayMs;
190
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800191 private Tethering mTethering;
192
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700193 private final PermissionMonitor mPermissionMonitor;
194
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700195 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700196
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700197 @GuardedBy("mVpns")
198 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700199
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700200 private boolean mLockdownEnabled;
201 private LockdownVpnTracker mLockdownTracker;
202
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700203 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
204 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700205 /** Currently active network rules by UID. */
206 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700207 /** Set of ifaces that are costly. */
208 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700209
Erik Klineda4bfa82015-04-30 12:58:40 +0900210 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700212 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700213 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800215 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800216
217 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700218 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800219
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700220 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800221 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700222 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700223
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700224 private String mCurrentTcpBufferSizes;
225
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700226 private static final int ENABLED = 1;
227 private static final int DISABLED = 0;
228
Paul Jensenb10e37f2014-11-25 12:33:08 -0500229 private enum ReapUnvalidatedNetworks {
Paul Jensen85cf78e2015-06-25 13:25:07 -0400230 // Tear down networks that have no chance (e.g. even if validated) of becoming
231 // the highest scoring network satisfying a NetworkRequest. This should be passed when
Paul Jensenb10e37f2014-11-25 12:33:08 -0500232 // all networks have been rematched against all NetworkRequests.
233 REAP,
Paul Jensen85cf78e2015-06-25 13:25:07 -0400234 // Don't reap networks. This should be passed when some networks have not yet been
235 // rematched against all NetworkRequests.
Paul Jensenb10e37f2014-11-25 12:33:08 -0500236 DONT_REAP
237 };
238
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700239 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700240 * used internally to change our mobile data enabled flag
241 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700242 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700243
244 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700245 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700246 * from one net to another. Clear happens when we get a new
247 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
248 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700250 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700251
Robert Greenwalt434203a2010-10-11 16:00:27 -0700252 /**
253 * used internally to reload global proxy settings
254 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700255 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700256
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700257 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400258 * PAC manager has received new port.
259 */
260 private static final int EVENT_PROXY_HAS_CHANGED = 16;
261
Robert Greenwalte049c232014-04-11 15:53:27 -0700262 /**
263 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700264 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700265 */
266 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
267
Robert Greenwalt7b816022014-04-18 15:25:25 -0700268 /**
269 * used internally when registering NetworkAgents
270 * obj = Messenger
271 */
272 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
273
Robert Greenwalt9258c642014-03-26 16:47:06 -0700274 /**
275 * used to add a network request
276 * includes a NetworkRequestInfo
277 */
278 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
279
280 /**
281 * indicates a timeout period is over - check if we had a network yet or not
282 * and if not, call the timeout calback (but leave the request live until they
283 * cancel it.
284 * includes a NetworkRequestInfo
285 */
286 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
287
288 /**
289 * used to add a network listener - no request
290 * includes a NetworkRequestInfo
291 */
292 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
293
294 /**
295 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400296 * arg1 = UID of caller
297 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700298 */
299 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
300
Robert Greenwalta67be032014-05-16 15:49:14 -0700301 /**
302 * used internally when registering NetworkFactories
303 * obj = Messenger
304 */
305 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
306
Robert Greenwalt27711812014-06-25 16:45:57 -0700307 /**
308 * used internally to expire a wakelock when transitioning
309 * from one net to another. Expire happens when we fail to find
310 * a new network (typically after 1 minute) -
311 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
312 * a replacement network.
313 */
314 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
315
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700316 /**
317 * Used internally to indicate the system is ready.
318 */
319 private static final int EVENT_SYSTEM_READY = 25;
320
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800321 /**
322 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400323 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800324 */
325 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
326
327 /**
328 * used to remove a pending intent and its associated network request.
329 * arg1 = UID of caller
330 * obj = PendingIntent
331 */
332 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
333
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900334 /**
335 * used to specify whether a network should be used even if unvalidated.
336 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
337 * arg2 = whether to remember this choice in the future (1 or 0)
338 * obj = network
339 */
340 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
341
342 /**
343 * used to ask the user to confirm a connection to an unvalidated network.
344 * obj = network
345 */
346 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700347
Erik Klineda4bfa82015-04-30 12:58:40 +0900348 /**
349 * used internally to (re)configure mobile data always-on settings.
350 */
351 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
352
Paul Jensen694f2b82015-06-17 14:15:39 -0400353 /**
354 * used to add a network listener with a pending intent
355 * obj = NetworkRequestInfo
356 */
357 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
358
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900359 /** Handler thread used for both of the handlers below. */
360 @VisibleForTesting
361 protected final HandlerThread mHandlerThread;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700362 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700363 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700364 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700365 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700366
Mike Lockwood0f79b542009-08-14 14:18:49 -0400367 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800368 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400369
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700370 private PowerManager.WakeLock mNetTransitionWakeLock;
371 private String mNetTransitionWakeLockCausedBy = "";
372 private int mNetTransitionWakeLockSerialNumber;
373 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800374 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700375
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700376 private InetAddress mDefaultDns;
377
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700378 // used in DBG mode to track inet condition reports
379 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
380 private ArrayList mInetLog;
381
Robert Greenwalt434203a2010-10-11 16:00:27 -0700382 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400383 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700384 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700385 private boolean mDefaultProxyDisabled = false;
386
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400388 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389
Jason Monk602b2322013-07-03 17:04:33 -0400390 private PacManager mPacManager = null;
391
Erik Klineda4bfa82015-04-30 12:58:40 +0900392 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700393
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400394 private UserManager mUserManager;
395
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700396 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700397 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700398
Robert Greenwalt50393202011-06-21 17:26:14 -0700399 // the set of network types that can only be enabled by system/sig apps
400 List mProtectedNetworks;
401
John Spurlockbf991a82013-06-24 14:20:23 -0400402 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700403
Wink Savilleab9321d2013-06-29 21:10:57 -0700404 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400405
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900406 private KeepaliveTracker mKeepaliveTracker;
407
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700408 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
409 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700410 private final static int MAX_NET_ID = 65535;
411 private int mNextNetId = MIN_NET_ID;
412
Robert Greenwalt34524f02014-05-18 16:22:10 -0700413 // sequence number of NetworkRequests
414 private int mNextNetworkRequestId = 1;
415
Erik Kline7523eb32015-07-09 18:24:03 +0900416 // NetworkRequest activity String log entries.
417 private static final int MAX_NETWORK_REQUEST_LOGS = 20;
418 private final LocalLog mNetworkRequestInfoLogs = new LocalLog(MAX_NETWORK_REQUEST_LOGS);
419
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700420 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
421 private static final int MAX_VALIDATION_LOGS = 10;
422 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
423 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
424
425 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
426 synchronized(mValidationLogs) {
427 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
428 mValidationLogs.removeLast();
429 }
430 mValidationLogs.addFirst(new Pair(network, log));
431 }
432 }
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Implements support for the legacy "one network per network type" model.
436 *
437 * We used to have a static array of NetworkStateTrackers, one for each
438 * network type, but that doesn't work any more now that we can have,
439 * for example, more that one wifi network. This class stores all the
440 * NetworkAgentInfo objects that support a given type, but the legacy
441 * API will only see the first one.
442 *
443 * It serves two main purposes:
444 *
445 * 1. Provide information about "the network for a given type" (since this
446 * API only supports one).
447 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
448 * the first network for a given type changes, or if the default network
449 * changes.
450 */
451 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900452
453 private static final boolean DBG = true;
454 private static final boolean VDBG = false;
455 private static final String TAG = "CSLegacyTypeTracker";
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 /**
458 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
459 * Each list holds references to all NetworkAgentInfos that are used to
460 * satisfy requests for that network type.
461 *
462 * This array is built out at startup such that an unsupported network
463 * doesn't get an ArrayList instance, making this a tristate:
464 * unsupported, supported but not active and active.
465 *
466 * The actual lists are populated when we scan the network types that
467 * are supported on this device.
468 */
469 private ArrayList<NetworkAgentInfo> mTypeLists[];
470
471 public LegacyTypeTracker() {
472 mTypeLists = (ArrayList<NetworkAgentInfo>[])
473 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
474 }
475
476 public void addSupportedType(int type) {
477 if (mTypeLists[type] != null) {
478 throw new IllegalStateException(
479 "legacy list for type " + type + "already initialized");
480 }
481 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
482 }
483
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700484 public boolean isTypeSupported(int type) {
485 return isNetworkTypeValid(type) && mTypeLists[type] != null;
486 }
487
488 public NetworkAgentInfo getNetworkForType(int type) {
489 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
490 return mTypeLists[type].get(0);
491 } else {
492 return null;
493 }
494 }
495
Robert Greenwalt8d482522015-06-24 13:23:42 -0700496 private void maybeLogBroadcast(NetworkAgentInfo nai, DetailedState state, int type,
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900497 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 if (DBG) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700499 log("Sending " + state +
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900501 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 }
503 }
504
505 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700506 public void add(int type, NetworkAgentInfo nai) {
507 if (!isTypeSupported(type)) {
508 return; // Invalid network type.
509 }
510 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
511
512 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
513 if (list.contains(nai)) {
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700514 return;
515 }
516
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900517 list.add(nai);
518
519 // 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 +0900520 final boolean isDefaultNetwork = isDefaultNetwork(nai);
521 if (list.size() == 1 || isDefaultNetwork) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700522 maybeLogBroadcast(nai, DetailedState.CONNECTED, type, isDefaultNetwork);
523 sendLegacyNetworkBroadcast(nai, DetailedState.CONNECTED, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700524 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 }
526
Lorenzo Colittia793a672014-07-31 23:20:17 +0900527 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900528 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
530 if (list == null || list.isEmpty()) {
531 return;
532 }
533
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900534 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900535
536 if (!list.remove(nai)) {
537 return;
538 }
539
Robert Greenwalt8d482522015-06-24 13:23:42 -0700540 final DetailedState state = DetailedState.DISCONNECTED;
541
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900542 if (wasFirstNetwork || wasDefault) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700543 maybeLogBroadcast(nai, state, type, wasDefault);
544 sendLegacyNetworkBroadcast(nai, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900545 }
546
547 if (!list.isEmpty() && wasFirstNetwork) {
548 if (DBG) log("Other network available for type " + type +
549 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900550 final NetworkAgentInfo replacement = list.get(0);
Robert Greenwalt8d482522015-06-24 13:23:42 -0700551 maybeLogBroadcast(replacement, state, type, isDefaultNetwork(replacement));
552 sendLegacyNetworkBroadcast(replacement, state, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553 }
554 }
555
556 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900557 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
558 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900560 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
562 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700563
Robert Greenwalt8d482522015-06-24 13:23:42 -0700564 // send out another legacy broadcast - currently only used for suspend/unsuspend
565 // toggle
566 public void update(NetworkAgentInfo nai) {
567 final boolean isDefault = isDefaultNetwork(nai);
568 final DetailedState state = nai.networkInfo.getDetailedState();
569 for (int type = 0; type < mTypeLists.length; type++) {
570 final ArrayList<NetworkAgentInfo> list = mTypeLists[type];
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700571 final boolean contains = (list != null && list.contains(nai));
Robert Greenwalt8d482522015-06-24 13:23:42 -0700572 final boolean isFirst = (list != null && list.size() > 0 && nai == list.get(0));
Robert Greenwalt3ac71b72015-07-10 16:00:36 -0700573 if (isFirst || (contains && isDefault)) {
Robert Greenwalt8d482522015-06-24 13:23:42 -0700574 maybeLogBroadcast(nai, state, type, isDefault);
575 sendLegacyNetworkBroadcast(nai, state, type);
576 }
577 }
578 }
579
Lorenzo Colittia793a672014-07-31 23:20:17 +0900580 private String naiToString(NetworkAgentInfo nai) {
581 String name = (nai != null) ? nai.name() : "null";
582 String state = (nai.networkInfo != null) ?
583 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
584 "???/???";
585 return name + " " + state;
586 }
587
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700588 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900589 pw.println("mLegacyTypeTracker:");
590 pw.increaseIndent();
591 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700592 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900593 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700594 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900595 pw.println();
596 pw.println("Current state:");
597 pw.increaseIndent();
598 for (int type = 0; type < mTypeLists.length; type++) {
599 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
600 for (NetworkAgentInfo nai : mTypeLists[type]) {
601 pw.println(type + " " + naiToString(nai));
602 }
603 }
604 pw.decreaseIndent();
605 pw.decreaseIndent();
606 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700607 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900608
609 // This class needs its own log method because it has a different TAG.
610 private void log(String s) {
611 Slog.d(TAG, s);
612 }
613
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700614 }
615 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
616
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900617 @VisibleForTesting
618 protected HandlerThread createHandlerThread() {
619 return new HandlerThread("ConnectivityServiceThread");
620 }
621
Jeff Sharkey899223b2012-08-04 15:24:58 -0700622 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700623 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800624 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800625
Erik Klineda4bfa82015-04-30 12:58:40 +0900626 mDefaultRequest = createInternetRequestForTransport(-1);
Erik Kline7523eb32015-07-09 18:24:03 +0900627 NetworkRequestInfo defaultNRI = new NetworkRequestInfo(null, mDefaultRequest,
628 new Binder(), NetworkRequestInfo.REQUEST);
629 mNetworkRequests.put(mDefaultRequest, defaultNRI);
630 mNetworkRequestInfoLogs.log("REGISTER " + defaultNRI);
Erik Klineda4bfa82015-04-30 12:58:40 +0900631
632 mDefaultMobileDataRequest = createInternetRequestForTransport(
633 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700634
Lorenzo Colittie58961a2015-08-07 20:17:27 +0900635 mHandlerThread = createHandlerThread();
636 mHandlerThread.start();
637 mHandler = new InternalHandler(mHandlerThread.getLooper());
638 mTrackerHandler = new NetworkStateTrackerHandler(mHandlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700639
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800640 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800641 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
642 String id = Settings.Secure.getString(context.getContentResolver(),
643 Settings.Secure.ANDROID_ID);
644 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700645 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800646 SystemProperties.set("net.hostname", name);
647 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800648 }
649
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700650 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700651 String dns = Settings.Global.getString(context.getContentResolver(),
652 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700653 if (dns == null || dns.length() == 0) {
654 dns = context.getResources().getString(
655 com.android.internal.R.string.config_default_dns_server);
656 }
657 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800658 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
659 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800660 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700661 }
662
Jeremy Joslin79294842014-12-03 17:15:28 -0800663 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
664 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
665
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700666 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700667 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800668 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700669 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700670 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700671 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700672
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700673 try {
674 mPolicyManager.registerListener(mPolicyListener);
675 } catch (RemoteException e) {
676 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700677 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700678 }
679
680 final PowerManager powerManager = (PowerManager) context.getSystemService(
681 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700682 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
683 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
684 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800685 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700686
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700687 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700688
Wink Saville51f456f2013-04-23 14:26:51 -0700689 // TODO: What is the "correct" way to do determine if this is a wifi only device?
690 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
691 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700692 String[] naStrings = context.getResources().getStringArray(
693 com.android.internal.R.array.networkAttributes);
694 for (String naString : naStrings) {
695 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700696 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700697 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700698 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800699 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700700 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700701 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700702 }
Wink Saville51f456f2013-04-23 14:26:51 -0700703 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
704 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
705 n.type);
706 continue;
707 }
Wink Saville975c8482011-04-07 14:23:45 -0700708 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800709 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700710 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700711 continue;
712 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700713 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700714
Wink Saville975c8482011-04-07 14:23:45 -0700715 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700716 mNetworksDefined++;
717 } catch(Exception e) {
718 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700719 }
720 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700721
722 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
723 if (mNetConfigs[TYPE_VPN] == null) {
724 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
725 // don't need to add TYPE_VPN to mNetConfigs.
726 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
727 mNetworksDefined++; // used only in the log() statement below.
728 }
729
Wink Saville5e56bc52013-07-29 15:00:57 -0700730 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700731
Robert Greenwalt50393202011-06-21 17:26:14 -0700732 mProtectedNetworks = new ArrayList<Integer>();
733 int[] protectedNetworks = context.getResources().getIntArray(
734 com.android.internal.R.array.config_protectedNetworks);
735 for (int p : protectedNetworks) {
736 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
737 mProtectedNetworks.add(p);
738 } else {
739 if (DBG) loge("Ignoring protectedNetwork " + p);
740 }
741 }
742
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700743 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
744 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700745
Robert Greenwaltfab501672014-07-23 11:44:01 -0700746 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800747
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700748 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
749
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700750 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700751 IntentFilter intentFilter = new IntentFilter();
752 intentFilter.addAction(Intent.ACTION_USER_STARTING);
753 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
Fyodor Kupolov1c363152015-09-02 13:27:21 -0700754 intentFilter.addAction(Intent.ACTION_USER_ADDED);
755 intentFilter.addAction(Intent.ACTION_USER_REMOVED);
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700756 mContext.registerReceiverAsUser(
757 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900758
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700759 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700760 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700761 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700762 } catch (RemoteException e) {
763 loge("Error registering observer :" + e);
764 }
765
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700766 if (DBG) {
767 mInetLog = new ArrayList();
768 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700769
Erik Klineda4bfa82015-04-30 12:58:40 +0900770 mSettingsObserver = new SettingsObserver(mContext, mHandler);
771 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800772
John Spurlockbf991a82013-06-24 14:20:23 -0400773 mDataConnectionStats = new DataConnectionStats(mContext);
774 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400775
Jason Monkdecd2952013-10-10 14:02:51 -0400776 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700777
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400778 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +0900779
780 mKeepaliveTracker = new KeepaliveTracker(mHandler);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800781 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700782
Erik Klineda4bfa82015-04-30 12:58:40 +0900783 private NetworkRequest createInternetRequestForTransport(int transportType) {
784 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900785 netCap.addCapability(NET_CAPABILITY_INTERNET);
786 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900787 if (transportType > -1) {
788 netCap.addTransportType(transportType);
789 }
790 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
791 }
792
793 private void handleMobileDataAlwaysOn() {
794 final boolean enable = (Settings.Global.getInt(
795 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
796 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
797 if (enable == isEnabled) {
798 return; // Nothing to do.
799 }
800
801 if (enable) {
802 handleRegisterNetworkRequest(new NetworkRequestInfo(
803 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
804 } else {
805 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
806 }
807 }
808
809 private void registerSettingsCallbacks() {
810 // Watch for global HTTP proxy changes.
811 mSettingsObserver.observe(
812 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
813 EVENT_APPLY_GLOBAL_HTTP_PROXY);
814
815 // Watch for whether or not to keep mobile data always on.
816 mSettingsObserver.observe(
817 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
818 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
819 }
820
Robert Greenwalt34524f02014-05-18 16:22:10 -0700821 private synchronized int nextNetworkRequestId() {
822 return mNextNetworkRequestId++;
823 }
824
Paul Jensen67b0b072015-06-10 11:22:17 -0400825 @VisibleForTesting
826 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400827 synchronized (mNetworkForNetId) {
828 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
829 int netId = mNextNetId;
830 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
831 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500832 if (!mNetIdInUse.get(netId)) {
833 mNetIdInUse.put(netId, true);
834 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400835 }
836 }
837 }
838 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700839 }
840
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841 private NetworkState getFilteredNetworkState(int networkType, int uid) {
842 NetworkInfo info = null;
843 LinkProperties lp = null;
844 NetworkCapabilities nc = null;
845 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800846 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847
848 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
849 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
850 if (nai != null) {
851 synchronized (nai) {
852 info = new NetworkInfo(nai.networkInfo);
853 lp = new LinkProperties(nai.linkProperties);
854 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400855 // Network objects are outwardly immutable so there is no point to duplicating.
856 // Duplicating also precludes sharing socket factories and connection pools.
857 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800858 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859 }
860 info.setType(networkType);
861 } else {
862 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
863 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
864 info.setIsAvailable(true);
865 lp = new LinkProperties();
866 nc = new NetworkCapabilities();
867 network = null;
868 }
869 info = getFilteredNetworkInfo(info, lp, uid);
870 }
871
Jeff Sharkey32566012014-12-02 18:30:14 -0800872 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400873 }
874
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800875 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
876 if (network == null) {
877 return null;
878 }
879 synchronized (mNetworkForNetId) {
880 return mNetworkForNetId.get(network.netId);
881 }
882 };
883
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900884 private Network[] getVpnUnderlyingNetworks(int uid) {
885 if (!mLockdownEnabled) {
886 int user = UserHandle.getUserId(uid);
887 synchronized (mVpns) {
888 Vpn vpn = mVpns.get(user);
889 if (vpn != null && vpn.appliesToUid(uid)) {
890 return vpn.getUnderlyingNetworks();
891 }
892 }
893 }
894 return null;
895 }
896
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800897 private NetworkState getUnfilteredActiveNetworkState(int uid) {
898 NetworkInfo info = null;
899 LinkProperties lp = null;
900 NetworkCapabilities nc = null;
901 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800902 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800903
Paul Jensen85cf78e2015-06-25 13:25:07 -0400904 NetworkAgentInfo nai = getDefaultNetwork();
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800905
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900906 final Network[] networks = getVpnUnderlyingNetworks(uid);
907 if (networks != null) {
908 // getUnderlyingNetworks() returns:
909 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
910 // empty array => the VPN explicitly said "no default network".
911 // non-empty array => the VPN specified one or more default networks; we use the
912 // first one.
913 if (networks.length > 0) {
914 nai = getNetworkAgentInfoForNetwork(networks[0]);
915 } else {
916 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800917 }
918 }
919
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800920 if (nai != null) {
921 synchronized (nai) {
922 info = new NetworkInfo(nai.networkInfo);
923 lp = new LinkProperties(nai.linkProperties);
924 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400925 // Network objects are outwardly immutable so there is no point to duplicating.
926 // Duplicating also precludes sharing socket factories and connection pools.
927 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800928 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800929 }
930 }
931
Jeff Sharkey32566012014-12-02 18:30:14 -0800932 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400933 }
934
935 /**
936 * Check if UID should be blocked from using the network with the given LinkProperties.
937 */
938 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700939 final boolean networkCostly;
940 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700941
Robert Greenwalt12e67352014-05-13 21:41:06 -0700942 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700943 synchronized (mRulesLock) {
944 networkCostly = mMeteredIfaces.contains(iface);
945 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700946 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700947
Jeff Sharkeydc988062015-09-14 10:09:47 -0700948 if (uidRules == RULE_REJECT_ALL) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700949 return true;
Jeff Sharkeydc988062015-09-14 10:09:47 -0700950 } else if ((uidRules == RULE_REJECT_METERED) && networkCostly) {
951 return true;
952 } else {
953 return false;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700954 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700955 }
956
957 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700958 * Return a filtered {@link NetworkInfo}, potentially marked
959 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800960 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700961 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800962 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
963 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400964 // network is blocked; clone and override state
965 info = new NetworkInfo(info);
966 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900967 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900968 log("returning Blocked NetworkInfo for ifname=" +
969 lp.getInterfaceName() + ", uid=" + uid);
970 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700971 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800972 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700973 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900974 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700975 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700976 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700977 }
978
979 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 * Return NetworkInfo for the active (i.e., connected) network interface.
981 * It is assumed that at most one network is active at a time. If more
982 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700983 * @return the info for the active network, or {@code null} if none is
984 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800985 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700986 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700988 enforceAccessPermission();
989 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800990 NetworkState state = getUnfilteredActiveNetworkState(uid);
991 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800992 }
993
Paul Jensen31a94f42015-02-13 14:18:39 -0500994 @Override
995 public Network getActiveNetwork() {
996 enforceAccessPermission();
997 final int uid = Binder.getCallingUid();
998 final int user = UserHandle.getUserId(uid);
999 int vpnNetId = NETID_UNSET;
1000 synchronized (mVpns) {
1001 final Vpn vpn = mVpns.get(user);
1002 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
1003 }
1004 NetworkAgentInfo nai;
1005 if (vpnNetId != NETID_UNSET) {
1006 synchronized (mNetworkForNetId) {
1007 nai = mNetworkForNetId.get(vpnNetId);
1008 }
1009 if (nai != null) return nai.network;
1010 }
1011 nai = getDefaultNetwork();
1012 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
1013 return nai != null ? nai.network : null;
1014 }
1015
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001016 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1017 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 final int uid = Binder.getCallingUid();
1019 NetworkState state = getUnfilteredActiveNetworkState(uid);
1020 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001021 }
1022
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001023 @Override
1024 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1025 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001026 NetworkState state = getUnfilteredActiveNetworkState(uid);
1027 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001028 }
1029
1030 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001031 public NetworkInfo getNetworkInfo(int networkType) {
1032 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001034 if (getVpnUnderlyingNetworks(uid) != null) {
1035 // A VPN is active, so we may need to return one of its underlying networks. This
1036 // information is not available in LegacyTypeTracker, so we have to get it from
1037 // getUnfilteredActiveNetworkState.
1038 NetworkState state = getUnfilteredActiveNetworkState(uid);
1039 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1040 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1041 }
1042 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001043 NetworkState state = getFilteredNetworkState(networkType, uid);
1044 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001047 @Override
1048 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1049 enforceAccessPermission();
1050 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001051 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001052 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1053 if (nai != null) {
1054 synchronized (nai) {
1055 info = new NetworkInfo(nai.networkInfo);
1056 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001057 }
1058 }
1059 return info;
1060 }
1061
1062 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001063 public NetworkInfo[] getAllNetworkInfo() {
1064 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001065 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001066 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1067 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001068 NetworkInfo info = getNetworkInfo(networkType);
1069 if (info != null) {
1070 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001071 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001072 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001073 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001074 }
1075
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001076 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001077 public Network getNetworkForType(int networkType) {
1078 enforceAccessPermission();
1079 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001080 NetworkState state = getFilteredNetworkState(networkType, uid);
1081 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1082 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001083 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001084 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001085 }
1086
1087 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001088 public Network[] getAllNetworks() {
1089 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001090 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001091 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001092 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001093 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001094 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001095 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001096 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001097 }
1098
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001099 @Override
1100 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1101 // The basic principle is: if an app's traffic could possibly go over a
1102 // network, without the app doing anything multinetwork-specific,
1103 // (hence, by "default"), then include that network's capabilities in
1104 // the array.
1105 //
1106 // In the normal case, app traffic only goes over the system's default
1107 // network connection, so that's the only network returned.
1108 //
1109 // With a VPN in force, some app traffic may go into the VPN, and thus
1110 // over whatever underlying networks the VPN specifies, while other app
1111 // traffic may go over the system default network (e.g.: a split-tunnel
1112 // VPN, or an app disallowed by the VPN), so the set of networks
1113 // returned includes the VPN's underlying networks and the system
1114 // default.
1115 enforceAccessPermission();
1116
1117 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1118
1119 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001120 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001121 if (nc != null) {
1122 result.put(nai.network, nc);
1123 }
1124
1125 if (!mLockdownEnabled) {
1126 synchronized (mVpns) {
1127 Vpn vpn = mVpns.get(userId);
1128 if (vpn != null) {
1129 Network[] networks = vpn.getUnderlyingNetworks();
1130 if (networks != null) {
1131 for (Network network : networks) {
1132 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001133 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001134 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001135 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001136 }
1137 }
1138 }
1139 }
1140 }
1141 }
1142
1143 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1144 out = result.values().toArray(out);
1145 return out;
1146 }
1147
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001148 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001149 public boolean isNetworkSupported(int networkType) {
1150 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001151 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001152 }
1153
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001154 /**
1155 * Return LinkProperties for the active (i.e., connected) default
1156 * network interface. It is assumed that at most one default network
1157 * is active at a time. If more than one is active, it is indeterminate
1158 * which will be returned.
1159 * @return the ip properties for the active network, or {@code null} if
1160 * none is active
1161 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001162 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001163 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001164 enforceAccessPermission();
1165 final int uid = Binder.getCallingUid();
1166 NetworkState state = getUnfilteredActiveNetworkState(uid);
1167 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001168 }
1169
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001170 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001171 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001172 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001173 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1174 if (nai != null) {
1175 synchronized (nai) {
1176 return new LinkProperties(nai.linkProperties);
1177 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001178 }
1179 return null;
1180 }
1181
Robert Greenwalt12e67352014-05-13 21:41:06 -07001182 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001183 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001184 public LinkProperties getLinkProperties(Network network) {
1185 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 if (nai != null) {
1188 synchronized (nai) {
1189 return new LinkProperties(nai.linkProperties);
1190 }
1191 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001192 return null;
1193 }
1194
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001195 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001196 if (nai != null) {
1197 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001198 if (nai.networkCapabilities != null) {
1199 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001200 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001201 }
1202 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001203 return null;
1204 }
1205
1206 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001207 public NetworkCapabilities getNetworkCapabilities(Network network) {
1208 enforceAccessPermission();
1209 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1210 }
1211
1212 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001213 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001214 // Require internal since we're handing out IMSI details
1215 enforceConnectivityInternalPermission();
1216
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001217 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001218 for (Network network : getAllNetworks()) {
1219 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1220 if (nai != null) {
1221 synchronized (nai) {
1222 final String subscriberId = (nai.networkMisc != null)
1223 ? nai.networkMisc.subscriberId : null;
1224 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1225 nai.networkCapabilities, network, subscriberId, null));
1226 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001227 }
1228 }
1229 return result.toArray(new NetworkState[result.size()]);
1230 }
1231
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001232 @Override
1233 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1234 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001235 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001236 final long token = Binder.clearCallingIdentity();
1237 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001238 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1239 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001240 try {
1241 return mPolicyManager.getNetworkQuotaInfo(state);
1242 } catch (RemoteException e) {
1243 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001244 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001245 return null;
1246 } finally {
1247 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001248 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001249 }
1250
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001251 @Override
1252 public boolean isActiveNetworkMetered() {
1253 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001254 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001255 final long token = Binder.clearCallingIdentity();
1256 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001257 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001258 } finally {
1259 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001260 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001261 }
1262
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001263 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1264 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1265 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001266 try {
1267 return mPolicyManager.isNetworkMetered(state);
1268 } catch (RemoteException e) {
1269 }
1270 }
1271 return false;
1272 }
1273
Jeff Sharkey216c1812012-08-05 14:29:23 -07001274 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1275 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001276 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001277 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001278 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001279 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001280 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001281
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001282 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001283 * Ensure that a network route exists to deliver traffic to the specified
1284 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001285 * @param networkType the type of the network over which traffic to the
1286 * specified host is to be routed
1287 * @param hostAddress the IP address of the host to which the route is
1288 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 * @return {@code true} on success, {@code false} on failure
1290 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001291 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001292 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001293 if (mProtectedNetworks.contains(networkType)) {
1294 enforceConnectivityInternalPermission();
1295 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001296
Chad Brubakerc0234532014-02-14 13:24:29 -08001297 InetAddress addr;
1298 try {
1299 addr = InetAddress.getByAddress(hostAddress);
1300 } catch (UnknownHostException e) {
1301 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1302 return false;
1303 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001304
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001306 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 return false;
1308 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001309
1310 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1311 if (nai == null) {
1312 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1313 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1314 } else {
1315 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1316 }
1317 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001318 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001319
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001320 DetailedState netState;
1321 synchronized (nai) {
1322 netState = nai.networkInfo.getDetailedState();
1323 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001324
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001325 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001326 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001327 log("requestRouteToHostAddress on down network "
1328 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001329 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001330 }
1331 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001332 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001333
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001334 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001335 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001336 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001337 LinkProperties lp;
1338 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001339 synchronized (nai) {
1340 lp = nai.linkProperties;
1341 netId = nai.network.netId;
1342 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001343 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001344 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1345 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001346 } finally {
1347 Binder.restoreCallingIdentity(token);
1348 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001349 }
1350
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001351 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001352 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001353 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001354 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001355 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001356 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001357 if (bestRoute.getGateway().equals(addr)) {
1358 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001359 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001360 } else {
1361 // if we will connect to this through another route, add a direct route
1362 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001363 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001364 }
1365 }
Lorenzo Colittiaa281e22015-09-04 13:12:42 +09001366 if (DBG) log("Adding legacy route " + bestRoute +
1367 " for UID/PID " + uid + "/" + Binder.getCallingPid());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001368 try {
1369 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1370 } catch (Exception e) {
1371 // never crash - catch them all
1372 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001373 return false;
1374 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001375 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001376 }
1377
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001378 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1379 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001380 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001381 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001382 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001383 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001384 }
1385
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001386 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001387 // skip update when we've already applied rules
1388 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1389 if (oldRules == uidRules) return;
1390
1391 mUidRules.put(uid, uidRules);
1392 }
1393
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001394 // TODO: notify UID when it has requested targeted updates
1395 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001396
1397 @Override
1398 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001399 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001400 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001401 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001402 }
1403
1404 synchronized (mRulesLock) {
1405 mMeteredIfaces.clear();
1406 for (String iface : meteredIfaces) {
1407 mMeteredIfaces.add(iface);
1408 }
1409 }
1410 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001411
1412 @Override
1413 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1414 // caller is NPMS, since we only register with them
1415 if (LOGD_RULES) {
1416 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1417 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001418 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001419 };
1420
Robin Lee3b3dd942015-05-12 18:14:58 +01001421 /**
1422 * Require that the caller is either in the same user or has appropriate permission to interact
1423 * across users.
1424 *
1425 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1426 */
1427 private void enforceCrossUserPermission(int userId) {
1428 if (userId == UserHandle.getCallingUserId()) {
1429 // Not a cross-user call.
1430 return;
1431 }
1432 mContext.enforceCallingOrSelfPermission(
1433 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1434 "ConnectivityService");
1435 }
1436
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001437 private void enforceInternetPermission() {
1438 mContext.enforceCallingOrSelfPermission(
1439 android.Manifest.permission.INTERNET,
1440 "ConnectivityService");
1441 }
1442
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001443 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001444 mContext.enforceCallingOrSelfPermission(
1445 android.Manifest.permission.ACCESS_NETWORK_STATE,
1446 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001447 }
1448
1449 private void enforceChangePermission() {
Lorenzo Colittid5427052015-10-15 16:29:00 +09001450 ConnectivityManager.enforceChangePermission(mContext);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001451 }
1452
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001453 private void enforceTetherAccessPermission() {
1454 mContext.enforceCallingOrSelfPermission(
1455 android.Manifest.permission.ACCESS_NETWORK_STATE,
1456 "ConnectivityService");
1457 }
1458
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001459 private void enforceConnectivityInternalPermission() {
1460 mContext.enforceCallingOrSelfPermission(
1461 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1462 "ConnectivityService");
1463 }
1464
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001465 private void enforceKeepalivePermission() {
Lorenzo Colitti7914ce52015-09-08 13:21:48 +09001466 mContext.enforceCallingOrSelfPermission(KeepaliveTracker.PERMISSION, "ConnectivityService");
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09001467 }
1468
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001469 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001470 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001471 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001472 }
1473
1474 private void sendInetConditionBroadcast(NetworkInfo info) {
1475 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1476 }
1477
Wink Saville628b0852011-08-04 15:01:58 -07001478 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001479 if (mLockdownTracker != null) {
1480 info = mLockdownTracker.augmentNetworkInfo(info);
1481 }
1482
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001483 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001484 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001485 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001486 if (info.isFailover()) {
1487 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1488 info.setFailover(false);
1489 }
1490 if (info.getReason() != null) {
1491 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1492 }
1493 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001494 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1495 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001496 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001497 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001498 return intent;
1499 }
1500
1501 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1502 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1503 }
1504
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001505 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001506 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1507 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1508 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001509 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001510 final long ident = Binder.clearCallingIdentity();
1511 try {
1512 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1513 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1514 } finally {
1515 Binder.restoreCallingIdentity(ident);
1516 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001517 }
1518
Mike Lockwood0f79b542009-08-14 14:18:49 -04001519 private void sendStickyBroadcast(Intent intent) {
1520 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001521 if (!mSystemReady) {
1522 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001523 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001524 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001525 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001526 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001527 }
1528
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001529 Bundle options = null;
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001530 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001531 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001532 final NetworkInfo ni = intent.getParcelableExtra(
1533 ConnectivityManager.EXTRA_NETWORK_INFO);
1534 if (ni.getType() == ConnectivityManager.TYPE_MOBILE_SUPL) {
1535 intent.setAction(ConnectivityManager.CONNECTIVITY_ACTION_SUPL);
1536 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY);
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001537 } else {
1538 BroadcastOptions opts = BroadcastOptions.makeBasic();
1539 opts.setMaxManifestReceiverApiLevel(Build.VERSION_CODES.M);
1540 options = opts.toBundle();
Robert Greenwalte94a6ff2015-09-01 08:23:04 -07001541 }
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 {
Dianne Hackborne0e413e2015-12-09 17:22:26 -08001551 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL, options);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001552 } 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 }
Jason Monkdecd2952013-10-10 14:02:51 -04002513 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002514 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002515 break;
2516 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002517 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002518 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2519 break;
2520 }
2521 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2522 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002523 break;
2524 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002525 case EVENT_REGISTER_NETWORK_AGENT: {
2526 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2527 break;
2528 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002529 case EVENT_REGISTER_NETWORK_REQUEST:
2530 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002531 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002532 break;
2533 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002534 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2535 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002536 handleRegisterNetworkRequestWithIntent(msg);
2537 break;
2538 }
2539 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2540 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2541 break;
2542 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002543 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002544 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002545 break;
2546 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002547 case EVENT_SET_ACCEPT_UNVALIDATED: {
2548 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2549 break;
2550 }
2551 case EVENT_PROMPT_UNVALIDATED: {
2552 handlePromptUnvalidated((Network) msg.obj);
2553 break;
2554 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002555 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2556 handleMobileDataAlwaysOn();
2557 break;
2558 }
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09002559 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2560 case NetworkAgent.CMD_START_PACKET_KEEPALIVE: {
2561 mKeepaliveTracker.handleStartKeepalive(msg);
2562 break;
2563 }
2564 // Sent by KeepaliveTracker to process an app request on the state machine thread.
2565 case NetworkAgent.CMD_STOP_PACKET_KEEPALIVE: {
2566 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork((Network) msg.obj);
2567 int slot = msg.arg1;
2568 int reason = msg.arg2;
2569 mKeepaliveTracker.handleStopKeepalive(nai, slot, reason);
2570 break;
2571 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002572 case EVENT_SYSTEM_READY: {
2573 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2574 nai.networkMonitor.systemReady = true;
2575 }
2576 break;
2577 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002578 }
2579 }
2580 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002581
2582 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002583 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002584 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002585 if (isTetheringSupported()) {
2586 return mTethering.tether(iface);
2587 } else {
2588 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2589 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002590 }
2591
2592 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002593 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002594 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002595
2596 if (isTetheringSupported()) {
2597 return mTethering.untether(iface);
2598 } else {
2599 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2600 }
2601 }
2602
2603 // javadoc from interface
2604 public int getLastTetherError(String iface) {
2605 enforceTetherAccessPermission();
2606
2607 if (isTetheringSupported()) {
2608 return mTethering.getLastTetherError(iface);
2609 } else {
2610 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2611 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002612 }
2613
2614 // TODO - proper iface API for selection by property, inspection, etc
2615 public String[] getTetherableUsbRegexs() {
2616 enforceTetherAccessPermission();
2617 if (isTetheringSupported()) {
2618 return mTethering.getTetherableUsbRegexs();
2619 } else {
2620 return new String[0];
2621 }
2622 }
2623
2624 public String[] getTetherableWifiRegexs() {
2625 enforceTetherAccessPermission();
2626 if (isTetheringSupported()) {
2627 return mTethering.getTetherableWifiRegexs();
2628 } else {
2629 return new String[0];
2630 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002631 }
2632
Danica Chang6fdd0c62010-08-11 14:54:43 -07002633 public String[] getTetherableBluetoothRegexs() {
2634 enforceTetherAccessPermission();
2635 if (isTetheringSupported()) {
2636 return mTethering.getTetherableBluetoothRegexs();
2637 } else {
2638 return new String[0];
2639 }
2640 }
2641
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002642 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002643 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002644 if (isTetheringSupported()) {
2645 return mTethering.setUsbTethering(enable);
2646 } else {
2647 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2648 }
2649 }
2650
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002651 // TODO - move iface listing, queries, etc to new module
2652 // javadoc from interface
2653 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002654 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002655 return mTethering.getTetherableIfaces();
2656 }
2657
2658 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002659 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002660 return mTethering.getTetheredIfaces();
2661 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002662
Robert Greenwalt5a735062010-03-02 17:25:02 -08002663 public String[] getTetheringErroredIfaces() {
2664 enforceTetherAccessPermission();
2665 return mTethering.getErroredIfaces();
2666 }
2667
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002668 public String[] getTetheredDhcpRanges() {
2669 enforceConnectivityInternalPermission();
2670 return mTethering.getTetheredDhcpRanges();
2671 }
2672
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002673 // if ro.tether.denied = true we default to no tethering
2674 // gservices could set the secure setting to 1 though to enable it on a build where it
2675 // had previously been turned off.
2676 public boolean isTetheringSupported() {
2677 enforceTetherAccessPermission();
2678 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002679 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002680 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2681 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002682 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2683 mTethering.getTetherableWifiRegexs().length != 0 ||
2684 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2685 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002686 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002687
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002688 // Called when we lose the default network and have no replacement yet.
2689 // This will automatically be cleared after X seconds or a new default network
2690 // becomes CONNECTED, whichever happens first. The timer is started by the
2691 // first caller and not restarted by subsequent callers.
2692 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002693 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002694 synchronized (this) {
2695 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002696 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002697 mNetTransitionWakeLock.acquire();
2698 mNetTransitionWakeLockCausedBy = forWhom;
2699 }
2700 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002701 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002702 mNetTransitionWakeLockTimeout);
2703 return;
2704 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002705
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002706 // 100 percent is full good, 0 is full bad.
2707 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002708 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002709 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002710 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002711 }
2712
Paul Jensenbfd17b72015-04-07 12:43:13 -04002713 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002714 enforceAccessPermission();
2715 enforceInternetPermission();
2716
Paul Jensenbfd17b72015-04-07 12:43:13 -04002717 NetworkAgentInfo nai;
2718 if (network == null) {
2719 nai = getDefaultNetwork();
2720 } else {
2721 nai = getNetworkAgentInfoForNetwork(network);
2722 }
Paul Jensen4e8050e2015-06-25 10:28:34 -04002723 if (nai == null || nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTING ||
2724 nai.networkInfo.getState() == NetworkInfo.State.DISCONNECTED) {
2725 return;
2726 }
Paul Jensenbfd17b72015-04-07 12:43:13 -04002727 // Revalidate if the app report does not match our current validated state.
2728 if (hasConnectivity == nai.lastValidated) return;
2729 final int uid = Binder.getCallingUid();
2730 if (DBG) {
2731 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2732 ") by " + uid);
2733 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002734 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002735 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2736 // which isn't meant to work on uncreated networks.
2737 if (!nai.created) return;
2738
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002739 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002740
2741 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2742 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002743 }
2744
Paul Jensencee9b512015-05-06 07:32:40 -04002745 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002746 // this information is already available as a world read/writable jvm property
2747 // so this API change wouldn't have a benifit. It also breaks the passing
2748 // of proxy info to all the JVMs.
2749 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002750 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002751 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002752 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2753 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002754 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002755 }
2756
Paul Jensencee9b512015-05-06 07:32:40 -04002757 public ProxyInfo getProxyForNetwork(Network network) {
2758 if (network == null) return getDefaultProxy();
2759 final ProxyInfo globalProxy = getGlobalProxy();
2760 if (globalProxy != null) return globalProxy;
2761 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2762 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2763 // caller may not have.
2764 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2765 if (nai == null) return null;
2766 synchronized (nai) {
2767 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2768 if (proxyInfo == null) return null;
2769 return new ProxyInfo(proxyInfo);
2770 }
2771 }
2772
Paul Jensene0bef712014-12-10 15:12:18 -05002773 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2774 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2775 // proxy is null then there is no proxy in place).
2776 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2777 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2778 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2779 proxy = null;
2780 }
2781 return proxy;
2782 }
2783
2784 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2785 // better for determining if a new proxy broadcast is necessary:
2786 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2787 // avoid unnecessary broadcasts.
2788 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2789 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2790 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2791 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2792 // all set.
2793 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2794 a = canonicalizeProxyInfo(a);
2795 b = canonicalizeProxyInfo(b);
2796 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2797 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2798 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2799 }
2800
Jason Monk207900c2014-04-25 15:00:09 -04002801 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002802 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002803
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002804 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002805 if (proxyProperties == mGlobalProxy) return;
2806 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2807 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2808
2809 String host = "";
2810 int port = 0;
2811 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002812 String pacFileUrl = "";
2813 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002814 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002815 if (!proxyProperties.isValid()) {
2816 if (DBG)
2817 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2818 return;
2819 }
Jason Monk207900c2014-04-25 15:00:09 -04002820 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002821 host = mGlobalProxy.getHost();
2822 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002823 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002824 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002825 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002826 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002827 } else {
2828 mGlobalProxy = null;
2829 }
2830 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002831 final long token = Binder.clearCallingIdentity();
2832 try {
2833 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2834 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2835 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2836 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002837 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002838 } finally {
2839 Binder.restoreCallingIdentity(token);
2840 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002841
Jason Monkcf0f97a2014-10-02 15:39:38 -04002842 if (mGlobalProxy == null) {
2843 proxyProperties = mDefaultProxy;
2844 }
2845 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002846 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002847 }
2848
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002849 private void loadGlobalProxy() {
2850 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002851 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2852 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2853 String exclList = Settings.Global.getString(res,
2854 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002855 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2856 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002857 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002858 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002859 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002860 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002861 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002862 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002863 if (!proxyProperties.isValid()) {
2864 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2865 return;
2866 }
2867
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002868 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002869 mGlobalProxy = proxyProperties;
2870 }
2871 }
2872 }
2873
Jason Monk207900c2014-04-25 15:00:09 -04002874 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002875 // this information is already available as a world read/writable jvm property
2876 // so this API change wouldn't have a benifit. It also breaks the passing
2877 // of proxy info to all the JVMs.
2878 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002879 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002880 return mGlobalProxy;
2881 }
2882 }
2883
Jason Monk207900c2014-04-25 15:00:09 -04002884 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002885 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002886 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002887 proxy = null;
2888 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002889 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002890 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002891 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002892 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002893 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2894 return;
2895 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002896
2897 // This call could be coming from the PacManager, containing the port of the local
2898 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2899 // global (to get the correct local port), and send a broadcast.
2900 // TODO: Switch PacManager to have its own message to send back rather than
2901 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002902 if ((mGlobalProxy != null) && (proxy != null)
2903 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002904 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2905 mGlobalProxy = proxy;
2906 sendProxyBroadcast(mGlobalProxy);
2907 return;
2908 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002909 mDefaultProxy = proxy;
2910
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002911 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002912 if (!mDefaultProxyDisabled) {
2913 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002914 }
2915 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002916 }
2917
Paul Jensene0bef712014-12-10 15:12:18 -05002918 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2919 // This method gets called when any network changes proxy, but the broadcast only ever contains
2920 // the default proxy (even if it hasn't changed).
2921 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2922 // world where an app might be bound to a non-default network.
2923 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2924 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2925 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2926
2927 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2928 sendProxyBroadcast(getDefaultProxy());
2929 }
2930 }
2931
Robert Greenwalt434203a2010-10-11 16:00:27 -07002932 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002933 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2934 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002935 if (!TextUtils.isEmpty(proxy)) {
2936 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002937 if (data.length == 0) {
2938 return;
2939 }
2940
Robert Greenwalt434203a2010-10-11 16:00:27 -07002941 String proxyHost = data[0];
2942 int proxyPort = 8080;
2943 if (data.length > 1) {
2944 try {
2945 proxyPort = Integer.parseInt(data[1]);
2946 } catch (NumberFormatException e) {
2947 return;
2948 }
2949 }
Jason Monk207900c2014-04-25 15:00:09 -04002950 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002951 setGlobalProxy(p);
2952 }
2953 }
2954
Jason Monk207900c2014-04-25 15:00:09 -04002955 private void sendProxyBroadcast(ProxyInfo proxy) {
2956 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002957 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002958 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002959 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002960 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2961 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002962 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002963 final long ident = Binder.clearCallingIdentity();
2964 try {
2965 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2966 } finally {
2967 Binder.restoreCallingIdentity(ident);
2968 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002969 }
2970
2971 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002972 final private HashMap<Uri, Integer> mUriEventMap;
2973 final private Context mContext;
2974 final private Handler mHandler;
2975
2976 SettingsObserver(Context context, Handler handler) {
2977 super(null);
2978 mUriEventMap = new HashMap<Uri, Integer>();
2979 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002980 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002981 }
2982
Erik Klineda4bfa82015-04-30 12:58:40 +09002983 void observe(Uri uri, int what) {
2984 mUriEventMap.put(uri, what);
2985 final ContentResolver resolver = mContext.getContentResolver();
2986 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002987 }
2988
2989 @Override
2990 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002991 Slog.wtf(TAG, "Should never be reached.");
2992 }
2993
2994 @Override
2995 public void onChange(boolean selfChange, Uri uri) {
2996 final Integer what = mUriEventMap.get(uri);
2997 if (what != null) {
2998 mHandler.obtainMessage(what.intValue()).sendToTarget();
2999 } else {
3000 loge("No matching event to send for URI=" + uri);
3001 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07003002 }
3003 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08003004
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003005 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003006 Slog.d(TAG, s);
3007 }
3008
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003009 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003010 Slog.e(TAG, s);
3011 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003012
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003013 private static <T> T checkNotNull(T value, String message) {
3014 if (value == null) {
3015 throw new NullPointerException(message);
3016 }
3017 return value;
3018 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003019
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003020 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003021 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003022 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3023 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3024 *
3025 * @param oldPackage Package name of the application which currently controls VPN, which will
3026 * be replaced. If there is no such application, this should should either be
3027 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3028 * @param newPackage Package name of the application which should gain control of VPN, or
3029 * {@code null} to disable.
3030 * @param userId User for whom to prepare the new VPN.
3031 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003032 * @hide
3033 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003034 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003035 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3036 int userId) {
3037 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003038 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003039
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003040 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003041 Vpn vpn = mVpns.get(userId);
3042 if (vpn != null) {
3043 return vpn.prepare(oldPackage, newPackage);
3044 } else {
3045 return false;
3046 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003047 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003048 }
3049
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003050 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003051 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3052 * This method is used by system-privileged apps.
3053 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3054 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3055 *
3056 * @param packageName The package for which authorization state should change.
3057 * @param userId User for whom {@code packageName} is installed.
3058 * @param authorized {@code true} if this app should be able to start a VPN connection without
3059 * explicit user approval, {@code false} if not.
3060 *
Jeff Davidson05542602014-08-11 14:07:27 -07003061 * @hide
3062 */
3063 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003064 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3065 enforceCrossUserPermission(userId);
3066
Jeff Davidson05542602014-08-11 14:07:27 -07003067 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003068 Vpn vpn = mVpns.get(userId);
3069 if (vpn != null) {
3070 vpn.setPackageAuthorization(packageName, authorized);
3071 }
Jeff Davidson05542602014-08-11 14:07:27 -07003072 }
3073 }
3074
3075 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003076 * Configure a TUN interface and return its file descriptor. Parameters
3077 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003078 * and not available in ConnectivityManager. Permissions are checked in
3079 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003080 * @hide
3081 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003082 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003083 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003084 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003085 int user = UserHandle.getUserId(Binder.getCallingUid());
3086 synchronized(mVpns) {
3087 return mVpns.get(user).establish(config);
3088 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003089 }
3090
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003091 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003092 * Start legacy VPN, controlling native daemons as needed. Creates a
3093 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003094 */
3095 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003096 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003097 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003098 final LinkProperties egress = getActiveLinkProperties();
3099 if (egress == null) {
3100 throw new IllegalStateException("Missing active network connection");
3101 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003102 int user = UserHandle.getUserId(Binder.getCallingUid());
3103 synchronized(mVpns) {
3104 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3105 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003106 }
3107
3108 /**
3109 * Return the information of the ongoing legacy VPN. This method is used
3110 * by VpnSettings and not available in ConnectivityManager. Permissions
3111 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003112 */
3113 @Override
Robin Lee3eed5ec2015-07-07 12:28:13 -07003114 public LegacyVpnInfo getLegacyVpnInfo(int userId) {
3115 enforceCrossUserPermission(userId);
Hung-ying Tyan44c8c5c2015-07-29 12:39:21 +08003116 if (mLockdownEnabled) {
3117 return null;
3118 }
3119
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003120 synchronized(mVpns) {
Robin Lee3eed5ec2015-07-07 12:28:13 -07003121 return mVpns.get(userId).getLegacyVpnInfo();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003122 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003123 }
3124
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003125 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003126 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3127 * and not available in ConnectivityManager.
3128 */
3129 @Override
3130 public VpnInfo[] getAllVpnInfo() {
3131 enforceConnectivityInternalPermission();
3132 if (mLockdownEnabled) {
3133 return new VpnInfo[0];
3134 }
3135
3136 synchronized(mVpns) {
3137 List<VpnInfo> infoList = new ArrayList<>();
3138 for (int i = 0; i < mVpns.size(); i++) {
3139 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3140 if (info != null) {
3141 infoList.add(info);
3142 }
3143 }
3144 return infoList.toArray(new VpnInfo[infoList.size()]);
3145 }
3146 }
3147
3148 /**
3149 * @return VPN information for accounting, or null if we can't retrieve all required
3150 * information, e.g primary underlying iface.
3151 */
3152 @Nullable
3153 private VpnInfo createVpnInfo(Vpn vpn) {
3154 VpnInfo info = vpn.getVpnInfo();
3155 if (info == null) {
3156 return null;
3157 }
3158 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3159 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3160 // the underlyingNetworks list.
3161 if (underlyingNetworks == null) {
3162 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3163 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3164 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3165 }
3166 } else if (underlyingNetworks.length > 0) {
3167 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3168 if (linkProperties != null) {
3169 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3170 }
3171 }
3172 return info.primaryUnderlyingIface == null ? null : info;
3173 }
3174
3175 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003176 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3177 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003178 * Permissions are checked in Vpn class.
3179 * @hide
3180 */
3181 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003182 public VpnConfig getVpnConfig(int userId) {
3183 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003184 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003185 Vpn vpn = mVpns.get(userId);
3186 if (vpn != null) {
3187 return vpn.getVpnConfig();
3188 } else {
3189 return null;
3190 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003191 }
3192 }
3193
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003194 @Override
3195 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003196 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3197 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3198 return false;
3199 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003200
3201 // Tear down existing lockdown if profile was removed
3202 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3203 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003204 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003205 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3206 return false;
3207 }
3208
3209 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3210 final VpnProfile profile = VpnProfile.decode(
3211 profileName, mKeyStore.get(Credentials.VPN + profileName));
Lorenzo Colitti9b23f882015-10-13 15:21:21 +09003212 if (profile == null) {
3213 Slog.e(TAG, "Lockdown VPN configured invalid profile " + profileName);
3214 setLockdownTracker(null);
3215 return true;
3216 }
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)
Lorenzo Colitti46d50b72015-10-21 09:15:41 +09003363 .setDefaults(highPriority ? Notification.DEFAULT_ALL : 0)
Lorenzo Colitti9ce8a9d2015-06-24 17:13:08 +09003364 .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 }
Jeff Sharkeydc988062015-09-14 10:09:47 -07003753 if (uidRules != RULE_ALLOW_ALL) {
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
Udam Sainib7c24872016-01-04 12:16:14 -08004851 public String getCaptivePortalServerUrl() {
4852 return NetworkMonitor.getCaptivePortalServerUrl(mContext);
4853 }
4854
4855 @Override
Lorenzo Colitti8bf977d2015-06-15 14:29:22 +09004856 public void startNattKeepalive(Network network, int intervalSeconds, Messenger messenger,
4857 IBinder binder, String srcAddr, int srcPort, String dstAddr) {
4858 enforceKeepalivePermission();
4859 mKeepaliveTracker.startNattKeepalive(
4860 getNetworkAgentInfoForNetwork(network),
4861 intervalSeconds, messenger, binder,
4862 srcAddr, srcPort, dstAddr, ConnectivityManager.PacketKeepalive.NATT_PORT);
4863 }
4864
4865 @Override
4866 public void stopKeepalive(Network network, int slot) {
4867 mHandler.sendMessage(mHandler.obtainMessage(
4868 NetworkAgent.CMD_STOP_PACKET_KEEPALIVE, slot, PacketKeepalive.SUCCESS, network));
4869 }
4870
4871 @Override
Stuart Scottf1fb3972015-04-02 18:00:02 -07004872 public void factoryReset() {
4873 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004874
4875 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4876 return;
4877 }
4878
Robin Lee3b3dd942015-05-12 18:14:58 +01004879 final int userId = UserHandle.getCallingUserId();
4880
Stuart Scottf1fb3972015-04-02 18:00:02 -07004881 // Turn airplane mode off
4882 setAirplaneMode(false);
4883
Stuart Scotte3e314d2015-04-20 14:07:45 -07004884 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4885 // Untether
4886 for (String tether : getTetheredIfaces()) {
4887 untether(tether);
4888 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004889 }
4890
Stuart Scotte3e314d2015-04-20 14:07:45 -07004891 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4892 // Turn VPN off
4893 VpnConfig vpnConfig = getVpnConfig(userId);
4894 if (vpnConfig != null) {
4895 if (vpnConfig.legacy) {
4896 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4897 } else {
4898 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4899 // in the future without user intervention.
4900 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004901
Stuart Scotte3e314d2015-04-20 14:07:45 -07004902 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4903 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004904 }
4905 }
4906 }
Paul Jensencf4c2c62015-07-01 14:16:32 -04004907
4908 @VisibleForTesting
4909 public NetworkMonitor createNetworkMonitor(Context context, Handler handler,
4910 NetworkAgentInfo nai, NetworkRequest defaultRequest) {
4911 return new NetworkMonitor(context, handler, nai, defaultRequest);
4912 }
4913
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004914}