blob: 98f0b454e05e400df19ea2978194ddafe66d6f7a [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;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090026import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
27import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070030import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070031import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070033
Wenchao Tongf5ea3402015-03-04 13:26:38 -080034import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070035import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
49import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070050import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070051import android.net.INetworkPolicyListener;
52import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070053import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080054import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070055import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070056import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070057import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070058import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070062import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070063import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070065import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070066import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070067import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040068import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070069import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040071import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070073import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040074import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070076import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070077import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070078import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Looper;
80import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070081import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070082import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070083import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070084import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070085import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070086import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070088import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040089import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070091import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070092import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070093import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070094import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080095import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070096import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -050097import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070098import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070099import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Wink Savilleab9321d2013-06-29 21:10:57 -0700101import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400102import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400103import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700104import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700105import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700106import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700107import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800108import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700109import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700110import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700111import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700112import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700113import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700114import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400115import com.android.server.connectivity.DataConnectionStats;
Erik Kline379747a2015-06-05 17:47:34 +0900116import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900117import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700118import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400119import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400120import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700121import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800122import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700123import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700124import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700125import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700126import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700127import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700128
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700129import org.xmlpull.v1.XmlPullParser;
130import org.xmlpull.v1.XmlPullParserException;
131
132import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800133import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700134import java.io.FileNotFoundException;
135import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700136import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800137import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700138import java.net.Inet4Address;
Erik Kline41368502015-06-17 13:19:54 +0900139import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700140import java.net.InetAddress;
141import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700142import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700143import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700144import java.util.Collection;
Erik Kline41368502015-06-17 13:19:54 +0900145import java.util.Collections;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700146import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700147import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500148import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700149import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700150import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700151import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700152import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800153
154/**
155 * @hide
156 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800157public class ConnectivityService extends IConnectivityManager.Stub
158 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700159 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700161 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700162 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800163
Jake Hamby786e71a2014-02-06 14:43:50 -0800164 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700165
Jeff Sharkey899223b2012-08-04 15:24:58 -0700166 // TODO: create better separation between radio types and network types
167
Robert Greenwalt42acef32009-08-12 16:08:25 -0700168 // how long to wait before switching back to a radio's default network
169 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
170 // system property that can override the above value
171 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
172 "android.telephony.apn-restore";
173
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900174 // How long to wait before putting up a "This network doesn't have an Internet connection,
175 // connect anyway?" dialog after the user selects a network that doesn't validate.
176 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
177
Jeremy Joslin79294842014-12-03 17:15:28 -0800178 // How long to delay to removal of a pending intent based request.
179 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
180 private final int mReleasePendingIntentDelayMs;
181
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800182 private Tethering mTethering;
183
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700184 private final PermissionMonitor mPermissionMonitor;
185
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700186 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700187
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700188 @GuardedBy("mVpns")
189 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700190
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700191 private boolean mLockdownEnabled;
192 private LockdownVpnTracker mLockdownTracker;
193
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700194 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
195 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700196 /** Currently active network rules by UID. */
197 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700198 /** Set of ifaces that are costly. */
199 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700200
Erik Klineda4bfa82015-04-30 12:58:40 +0900201 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700203 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700204 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800205
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800206 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
208 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700209 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800210
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700211 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800212 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700213 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700214
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700215 private String mCurrentTcpBufferSizes;
216
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700217 private static final int ENABLED = 1;
218 private static final int DISABLED = 0;
219
Paul Jensenb10e37f2014-11-25 12:33:08 -0500220 // Arguments to rematchNetworkAndRequests()
221 private enum NascentState {
222 // Indicates a network was just validated for the first time. If the network is found to
223 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
224 JUST_VALIDATED,
225 // Indicates a network was not validated for the first time immediately prior to this call.
226 NOT_JUST_VALIDATED
227 };
228 private enum ReapUnvalidatedNetworks {
229 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
230 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
231 // known that there may be unvalidated networks that could potentially be reaped, and when
232 // all networks have been rematched against all NetworkRequests.
233 REAP,
234 // Don't reap unvalidated networks. This should be passed when it's known that there are
235 // no unvalidated networks that could potentially be reaped, and when some networks have
236 // not yet been rematched against all NetworkRequests.
237 DONT_REAP
238 };
239
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700240 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241 * used internally to change our mobile data enabled flag
242 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700243 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700244
245 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700246 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700247 * from one net to another. Clear happens when we get a new
248 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
249 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700250 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700251 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700252
Robert Greenwalt434203a2010-10-11 16:00:27 -0700253 /**
254 * used internally to reload global proxy settings
255 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700256 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700257
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700258 /**
Wink Saville628b0852011-08-04 15:01:58 -0700259 * used internally to send a sticky broadcast delayed.
260 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700261 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700262
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700263 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400264 * PAC manager has received new port.
265 */
266 private static final int EVENT_PROXY_HAS_CHANGED = 16;
267
Robert Greenwalte049c232014-04-11 15:53:27 -0700268 /**
269 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700270 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700271 */
272 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
273
Robert Greenwalt7b816022014-04-18 15:25:25 -0700274 /**
275 * used internally when registering NetworkAgents
276 * obj = Messenger
277 */
278 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
279
Robert Greenwalt9258c642014-03-26 16:47:06 -0700280 /**
281 * used to add a network request
282 * includes a NetworkRequestInfo
283 */
284 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
285
286 /**
287 * indicates a timeout period is over - check if we had a network yet or not
288 * and if not, call the timeout calback (but leave the request live until they
289 * cancel it.
290 * includes a NetworkRequestInfo
291 */
292 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
293
294 /**
295 * used to add a network listener - no request
296 * includes a NetworkRequestInfo
297 */
298 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
299
300 /**
301 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400302 * arg1 = UID of caller
303 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700304 */
305 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
306
Robert Greenwalta67be032014-05-16 15:49:14 -0700307 /**
308 * used internally when registering NetworkFactories
309 * obj = Messenger
310 */
311 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
312
Robert Greenwalt27711812014-06-25 16:45:57 -0700313 /**
314 * used internally to expire a wakelock when transitioning
315 * from one net to another. Expire happens when we fail to find
316 * a new network (typically after 1 minute) -
317 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
318 * a replacement network.
319 */
320 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
321
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700322 /**
323 * Used internally to indicate the system is ready.
324 */
325 private static final int EVENT_SYSTEM_READY = 25;
326
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800327 /**
328 * used to add a network request with a pending intent
329 * includes a NetworkRequestInfo
330 */
331 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
332
333 /**
334 * used to remove a pending intent and its associated network request.
335 * arg1 = UID of caller
336 * obj = PendingIntent
337 */
338 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
339
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900340 /**
341 * used to specify whether a network should be used even if unvalidated.
342 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
343 * arg2 = whether to remember this choice in the future (1 or 0)
344 * obj = network
345 */
346 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
347
348 /**
349 * used to ask the user to confirm a connection to an unvalidated network.
350 * obj = network
351 */
352 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700353
Erik Klineda4bfa82015-04-30 12:58:40 +0900354 /**
355 * used internally to (re)configure mobile data always-on settings.
356 */
357 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
358
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700359 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700360 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700361 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700362 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700363
Mike Lockwood0f79b542009-08-14 14:18:49 -0400364 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800365 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400366
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700367 private PowerManager.WakeLock mNetTransitionWakeLock;
368 private String mNetTransitionWakeLockCausedBy = "";
369 private int mNetTransitionWakeLockSerialNumber;
370 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800371 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700372
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700373 private InetAddress mDefaultDns;
374
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700375 // used in DBG mode to track inet condition reports
376 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
377 private ArrayList mInetLog;
378
Robert Greenwalt434203a2010-10-11 16:00:27 -0700379 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400380 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700381 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700382 private boolean mDefaultProxyDisabled = false;
383
Robert Greenwalt434203a2010-10-11 16:00:27 -0700384 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400385 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700386
Jason Monk602b2322013-07-03 17:04:33 -0400387 private PacManager mPacManager = null;
388
Erik Klineda4bfa82015-04-30 12:58:40 +0900389 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700390
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400391 private UserManager mUserManager;
392
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700393 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700394 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700395
Robert Greenwalt50393202011-06-21 17:26:14 -0700396 // the set of network types that can only be enabled by system/sig apps
397 List mProtectedNetworks;
398
John Spurlockbf991a82013-06-24 14:20:23 -0400399 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700400
Wink Savilleab9321d2013-06-29 21:10:57 -0700401 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400402
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700403 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
404 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700405 private final static int MAX_NET_ID = 65535;
406 private int mNextNetId = MIN_NET_ID;
407
Robert Greenwalt34524f02014-05-18 16:22:10 -0700408 // sequence number of NetworkRequests
409 private int mNextNetworkRequestId = 1;
410
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700411 /**
412 * Implements support for the legacy "one network per network type" model.
413 *
414 * We used to have a static array of NetworkStateTrackers, one for each
415 * network type, but that doesn't work any more now that we can have,
416 * for example, more that one wifi network. This class stores all the
417 * NetworkAgentInfo objects that support a given type, but the legacy
418 * API will only see the first one.
419 *
420 * It serves two main purposes:
421 *
422 * 1. Provide information about "the network for a given type" (since this
423 * API only supports one).
424 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
425 * the first network for a given type changes, or if the default network
426 * changes.
427 */
428 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900429
430 private static final boolean DBG = true;
431 private static final boolean VDBG = false;
432 private static final String TAG = "CSLegacyTypeTracker";
433
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700434 /**
435 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
436 * Each list holds references to all NetworkAgentInfos that are used to
437 * satisfy requests for that network type.
438 *
439 * This array is built out at startup such that an unsupported network
440 * doesn't get an ArrayList instance, making this a tristate:
441 * unsupported, supported but not active and active.
442 *
443 * The actual lists are populated when we scan the network types that
444 * are supported on this device.
445 */
446 private ArrayList<NetworkAgentInfo> mTypeLists[];
447
448 public LegacyTypeTracker() {
449 mTypeLists = (ArrayList<NetworkAgentInfo>[])
450 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
451 }
452
453 public void addSupportedType(int type) {
454 if (mTypeLists[type] != null) {
455 throw new IllegalStateException(
456 "legacy list for type " + type + "already initialized");
457 }
458 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
459 }
460
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700461 public boolean isTypeSupported(int type) {
462 return isNetworkTypeValid(type) && mTypeLists[type] != null;
463 }
464
465 public NetworkAgentInfo getNetworkForType(int type) {
466 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
467 return mTypeLists[type].get(0);
468 } else {
469 return null;
470 }
471 }
472
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900473 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
474 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900475 if (DBG) {
476 log("Sending " + (connected ? "connected" : "disconnected") +
477 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900478 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900479 }
480 }
481
482 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700483 public void add(int type, NetworkAgentInfo nai) {
484 if (!isTypeSupported(type)) {
485 return; // Invalid network type.
486 }
487 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
488
489 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
490 if (list.contains(nai)) {
491 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
492 return;
493 }
494
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900495 list.add(nai);
496
497 // 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 +0900498 final boolean isDefaultNetwork = isDefaultNetwork(nai);
499 if (list.size() == 1 || isDefaultNetwork) {
500 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700501 sendLegacyNetworkBroadcast(nai, true, type);
502 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700503 }
504
Lorenzo Colittia793a672014-07-31 23:20:17 +0900505 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900506 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900507 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
508 if (list == null || list.isEmpty()) {
509 return;
510 }
511
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900512 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513
514 if (!list.remove(nai)) {
515 return;
516 }
517
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900518 if (wasFirstNetwork || wasDefault) {
519 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900520 sendLegacyNetworkBroadcast(nai, false, type);
521 }
522
523 if (!list.isEmpty() && wasFirstNetwork) {
524 if (DBG) log("Other network available for type " + type +
525 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900526 final NetworkAgentInfo replacement = list.get(0);
527 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
528 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529 }
530 }
531
532 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
534 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700535 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900536 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700537 }
538 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700539
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540 private String naiToString(NetworkAgentInfo nai) {
541 String name = (nai != null) ? nai.name() : "null";
542 String state = (nai.networkInfo != null) ?
543 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
544 "???/???";
545 return name + " " + state;
546 }
547
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700548 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900549 pw.println("mLegacyTypeTracker:");
550 pw.increaseIndent();
551 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700552 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900553 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700554 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900555 pw.println();
556 pw.println("Current state:");
557 pw.increaseIndent();
558 for (int type = 0; type < mTypeLists.length; type++) {
559 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
560 for (NetworkAgentInfo nai : mTypeLists[type]) {
561 pw.println(type + " " + naiToString(nai));
562 }
563 }
564 pw.decreaseIndent();
565 pw.decreaseIndent();
566 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700567 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900568
569 // This class needs its own log method because it has a different TAG.
570 private void log(String s) {
571 Slog.d(TAG, s);
572 }
573
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700574 }
575 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
576
Jeff Sharkey899223b2012-08-04 15:24:58 -0700577 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700578 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800579 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800580
Erik Klineda4bfa82015-04-30 12:58:40 +0900581 mDefaultRequest = createInternetRequestForTransport(-1);
582 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
583 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
584
585 mDefaultMobileDataRequest = createInternetRequestForTransport(
586 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700587
Wink Savillebb08caf2010-09-02 19:23:52 -0700588 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
589 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700590 mHandler = new InternalHandler(handlerThread.getLooper());
591 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700592
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800593 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800594 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
595 String id = Settings.Secure.getString(context.getContentResolver(),
596 Settings.Secure.ANDROID_ID);
597 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700598 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800599 SystemProperties.set("net.hostname", name);
600 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800601 }
602
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700603 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700604 String dns = Settings.Global.getString(context.getContentResolver(),
605 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700606 if (dns == null || dns.length() == 0) {
607 dns = context.getResources().getString(
608 com.android.internal.R.string.config_default_dns_server);
609 }
610 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800611 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
612 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800613 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700614 }
615
Jeremy Joslin79294842014-12-03 17:15:28 -0800616 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
617 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
618
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700619 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700620 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800621 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700622 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700623 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700624 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700625
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700626 try {
627 mPolicyManager.registerListener(mPolicyListener);
628 } catch (RemoteException e) {
629 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700630 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700631 }
632
633 final PowerManager powerManager = (PowerManager) context.getSystemService(
634 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700635 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
636 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
637 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800638 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700639
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700640 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700641
Wink Saville51f456f2013-04-23 14:26:51 -0700642 // TODO: What is the "correct" way to do determine if this is a wifi only device?
643 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
644 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700645 String[] naStrings = context.getResources().getStringArray(
646 com.android.internal.R.array.networkAttributes);
647 for (String naString : naStrings) {
648 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700649 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700650 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700651 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800652 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700653 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700654 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700655 }
Wink Saville51f456f2013-04-23 14:26:51 -0700656 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
657 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
658 n.type);
659 continue;
660 }
Wink Saville975c8482011-04-07 14:23:45 -0700661 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800662 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700663 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700664 continue;
665 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700666 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700667
Wink Saville975c8482011-04-07 14:23:45 -0700668 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700669 mNetworksDefined++;
670 } catch(Exception e) {
671 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700672 }
673 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700674
675 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
676 if (mNetConfigs[TYPE_VPN] == null) {
677 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
678 // don't need to add TYPE_VPN to mNetConfigs.
679 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
680 mNetworksDefined++; // used only in the log() statement below.
681 }
682
Wink Saville5e56bc52013-07-29 15:00:57 -0700683 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700684
Robert Greenwalt50393202011-06-21 17:26:14 -0700685 mProtectedNetworks = new ArrayList<Integer>();
686 int[] protectedNetworks = context.getResources().getIntArray(
687 com.android.internal.R.array.config_protectedNetworks);
688 for (int p : protectedNetworks) {
689 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
690 mProtectedNetworks.add(p);
691 } else {
692 if (DBG) loge("Ignoring protectedNetwork " + p);
693 }
694 }
695
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700696 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
697 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700698
Robert Greenwaltfab501672014-07-23 11:44:01 -0700699 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800700
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700701 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
702
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700703 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700704 IntentFilter intentFilter = new IntentFilter();
705 intentFilter.addAction(Intent.ACTION_USER_STARTING);
706 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
707 mContext.registerReceiverAsUser(
708 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900709
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700710 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700711 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700712 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700713 } catch (RemoteException e) {
714 loge("Error registering observer :" + e);
715 }
716
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700717 if (DBG) {
718 mInetLog = new ArrayList();
719 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700720
Erik Klineda4bfa82015-04-30 12:58:40 +0900721 mSettingsObserver = new SettingsObserver(mContext, mHandler);
722 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800723
John Spurlockbf991a82013-06-24 14:20:23 -0400724 mDataConnectionStats = new DataConnectionStats(mContext);
725 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400726
Jason Monkdecd2952013-10-10 14:02:51 -0400727 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700728
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400729 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800730 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700731
Erik Klineda4bfa82015-04-30 12:58:40 +0900732 private NetworkRequest createInternetRequestForTransport(int transportType) {
733 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900734 netCap.addCapability(NET_CAPABILITY_INTERNET);
735 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900736 if (transportType > -1) {
737 netCap.addTransportType(transportType);
738 }
739 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
740 }
741
742 private void handleMobileDataAlwaysOn() {
743 final boolean enable = (Settings.Global.getInt(
744 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
745 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
746 if (enable == isEnabled) {
747 return; // Nothing to do.
748 }
749
750 if (enable) {
751 handleRegisterNetworkRequest(new NetworkRequestInfo(
752 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
753 } else {
754 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
755 }
756 }
757
758 private void registerSettingsCallbacks() {
759 // Watch for global HTTP proxy changes.
760 mSettingsObserver.observe(
761 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
762 EVENT_APPLY_GLOBAL_HTTP_PROXY);
763
764 // Watch for whether or not to keep mobile data always on.
765 mSettingsObserver.observe(
766 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
767 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
768 }
769
Robert Greenwalt34524f02014-05-18 16:22:10 -0700770 private synchronized int nextNetworkRequestId() {
771 return mNextNetworkRequestId++;
772 }
773
Paul Jensen67b0b072015-06-10 11:22:17 -0400774 @VisibleForTesting
775 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400776 synchronized (mNetworkForNetId) {
777 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
778 int netId = mNextNetId;
779 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
780 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500781 if (!mNetIdInUse.get(netId)) {
782 mNetIdInUse.put(netId, true);
783 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400784 }
785 }
786 }
787 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700788 }
789
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800790 private NetworkState getFilteredNetworkState(int networkType, int uid) {
791 NetworkInfo info = null;
792 LinkProperties lp = null;
793 NetworkCapabilities nc = null;
794 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800795 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800796
797 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
798 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
799 if (nai != null) {
800 synchronized (nai) {
801 info = new NetworkInfo(nai.networkInfo);
802 lp = new LinkProperties(nai.linkProperties);
803 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400804 // Network objects are outwardly immutable so there is no point to duplicating.
805 // Duplicating also precludes sharing socket factories and connection pools.
806 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800807 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800808 }
809 info.setType(networkType);
810 } else {
811 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
812 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
813 info.setIsAvailable(true);
814 lp = new LinkProperties();
815 nc = new NetworkCapabilities();
816 network = null;
817 }
818 info = getFilteredNetworkInfo(info, lp, uid);
819 }
820
Jeff Sharkey32566012014-12-02 18:30:14 -0800821 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400822 }
823
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800824 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
825 if (network == null) {
826 return null;
827 }
828 synchronized (mNetworkForNetId) {
829 return mNetworkForNetId.get(network.netId);
830 }
831 };
832
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900833 private Network[] getVpnUnderlyingNetworks(int uid) {
834 if (!mLockdownEnabled) {
835 int user = UserHandle.getUserId(uid);
836 synchronized (mVpns) {
837 Vpn vpn = mVpns.get(user);
838 if (vpn != null && vpn.appliesToUid(uid)) {
839 return vpn.getUnderlyingNetworks();
840 }
841 }
842 }
843 return null;
844 }
845
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800846 private NetworkState getUnfilteredActiveNetworkState(int uid) {
847 NetworkInfo info = null;
848 LinkProperties lp = null;
849 NetworkCapabilities nc = null;
850 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800851 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800852
853 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800854
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900855 final Network[] networks = getVpnUnderlyingNetworks(uid);
856 if (networks != null) {
857 // getUnderlyingNetworks() returns:
858 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
859 // empty array => the VPN explicitly said "no default network".
860 // non-empty array => the VPN specified one or more default networks; we use the
861 // first one.
862 if (networks.length > 0) {
863 nai = getNetworkAgentInfoForNetwork(networks[0]);
864 } else {
865 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800866 }
867 }
868
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800869 if (nai != null) {
870 synchronized (nai) {
871 info = new NetworkInfo(nai.networkInfo);
872 lp = new LinkProperties(nai.linkProperties);
873 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400874 // Network objects are outwardly immutable so there is no point to duplicating.
875 // Duplicating also precludes sharing socket factories and connection pools.
876 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800877 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800878 }
879 }
880
Jeff Sharkey32566012014-12-02 18:30:14 -0800881 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400882 }
883
884 /**
885 * Check if UID should be blocked from using the network with the given LinkProperties.
886 */
887 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700888 final boolean networkCostly;
889 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700890
Robert Greenwalt12e67352014-05-13 21:41:06 -0700891 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700892 synchronized (mRulesLock) {
893 networkCostly = mMeteredIfaces.contains(iface);
894 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700895 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700896
Amith Yamasani15e472352015-04-24 19:06:07 -0700897 if ((uidRules & RULE_REJECT_ALL) != 0
898 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700899 return true;
900 }
901
902 // no restrictive rules; network is visible
903 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700904 }
905
906 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700907 * Return a filtered {@link NetworkInfo}, potentially marked
908 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800909 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700910 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800911 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
912 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400913 // network is blocked; clone and override state
914 info = new NetworkInfo(info);
915 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900916 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900917 log("returning Blocked NetworkInfo for ifname=" +
918 lp.getInterfaceName() + ", uid=" + uid);
919 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700920 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800921 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700922 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900923 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700924 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700925 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700926 }
927
928 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 * Return NetworkInfo for the active (i.e., connected) network interface.
930 * It is assumed that at most one network is active at a time. If more
931 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700932 * @return the info for the active network, or {@code null} if none is
933 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800934 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700935 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700937 enforceAccessPermission();
938 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800939 NetworkState state = getUnfilteredActiveNetworkState(uid);
940 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800941 }
942
Paul Jensen31a94f42015-02-13 14:18:39 -0500943 @Override
944 public Network getActiveNetwork() {
945 enforceAccessPermission();
946 final int uid = Binder.getCallingUid();
947 final int user = UserHandle.getUserId(uid);
948 int vpnNetId = NETID_UNSET;
949 synchronized (mVpns) {
950 final Vpn vpn = mVpns.get(user);
951 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
952 }
953 NetworkAgentInfo nai;
954 if (vpnNetId != NETID_UNSET) {
955 synchronized (mNetworkForNetId) {
956 nai = mNetworkForNetId.get(vpnNetId);
957 }
958 if (nai != null) return nai.network;
959 }
960 nai = getDefaultNetwork();
961 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
962 return nai != null ? nai.network : null;
963 }
964
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700965 public NetworkInfo getActiveNetworkInfoUnfiltered() {
966 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967 final int uid = Binder.getCallingUid();
968 NetworkState state = getUnfilteredActiveNetworkState(uid);
969 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700970 }
971
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700972 @Override
973 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
974 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800975 NetworkState state = getUnfilteredActiveNetworkState(uid);
976 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700977 }
978
979 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800980 public NetworkInfo getNetworkInfo(int networkType) {
981 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700982 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900983 if (getVpnUnderlyingNetworks(uid) != null) {
984 // A VPN is active, so we may need to return one of its underlying networks. This
985 // information is not available in LegacyTypeTracker, so we have to get it from
986 // getUnfilteredActiveNetworkState.
987 NetworkState state = getUnfilteredActiveNetworkState(uid);
988 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
989 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
990 }
991 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800992 NetworkState state = getFilteredNetworkState(networkType, uid);
993 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800994 }
995
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800996 @Override
997 public NetworkInfo getNetworkInfoForNetwork(Network network) {
998 enforceAccessPermission();
999 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001000 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001001 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1002 if (nai != null) {
1003 synchronized (nai) {
1004 info = new NetworkInfo(nai.networkInfo);
1005 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001006 }
1007 }
1008 return info;
1009 }
1010
1011 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001012 public NetworkInfo[] getAllNetworkInfo() {
1013 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001014 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001015 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1016 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001017 NetworkInfo info = getNetworkInfo(networkType);
1018 if (info != null) {
1019 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001020 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001021 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001022 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001023 }
1024
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001025 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001026 public Network getNetworkForType(int networkType) {
1027 enforceAccessPermission();
1028 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 NetworkState state = getFilteredNetworkState(networkType, uid);
1030 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1031 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001032 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001033 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001034 }
1035
1036 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001037 public Network[] getAllNetworks() {
1038 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001039 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001040 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001041 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001042 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001043 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001044 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001045 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001046 }
1047
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001048 @Override
1049 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1050 // The basic principle is: if an app's traffic could possibly go over a
1051 // network, without the app doing anything multinetwork-specific,
1052 // (hence, by "default"), then include that network's capabilities in
1053 // the array.
1054 //
1055 // In the normal case, app traffic only goes over the system's default
1056 // network connection, so that's the only network returned.
1057 //
1058 // With a VPN in force, some app traffic may go into the VPN, and thus
1059 // over whatever underlying networks the VPN specifies, while other app
1060 // traffic may go over the system default network (e.g.: a split-tunnel
1061 // VPN, or an app disallowed by the VPN), so the set of networks
1062 // returned includes the VPN's underlying networks and the system
1063 // default.
1064 enforceAccessPermission();
1065
1066 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1067
1068 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001069 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001070 if (nc != null) {
1071 result.put(nai.network, nc);
1072 }
1073
1074 if (!mLockdownEnabled) {
1075 synchronized (mVpns) {
1076 Vpn vpn = mVpns.get(userId);
1077 if (vpn != null) {
1078 Network[] networks = vpn.getUnderlyingNetworks();
1079 if (networks != null) {
1080 for (Network network : networks) {
1081 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001082 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001083 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001084 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001085 }
1086 }
1087 }
1088 }
1089 }
1090 }
1091
1092 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1093 out = result.values().toArray(out);
1094 return out;
1095 }
1096
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001097 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001098 public boolean isNetworkSupported(int networkType) {
1099 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001100 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001101 }
1102
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001103 /**
1104 * Return LinkProperties for the active (i.e., connected) default
1105 * network interface. It is assumed that at most one default network
1106 * is active at a time. If more than one is active, it is indeterminate
1107 * which will be returned.
1108 * @return the ip properties for the active network, or {@code null} if
1109 * none is active
1110 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001112 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001113 enforceAccessPermission();
1114 final int uid = Binder.getCallingUid();
1115 NetworkState state = getUnfilteredActiveNetworkState(uid);
1116 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001117 }
1118
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001119 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001120 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001121 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001122 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1123 if (nai != null) {
1124 synchronized (nai) {
1125 return new LinkProperties(nai.linkProperties);
1126 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001127 }
1128 return null;
1129 }
1130
Robert Greenwalt12e67352014-05-13 21:41:06 -07001131 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001132 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001133 public LinkProperties getLinkProperties(Network network) {
1134 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001135 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001136 if (nai != null) {
1137 synchronized (nai) {
1138 return new LinkProperties(nai.linkProperties);
1139 }
1140 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001141 return null;
1142 }
1143
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001144 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001145 if (nai != null) {
1146 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001147 if (nai.networkCapabilities != null) {
1148 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001149 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001150 }
1151 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001152 return null;
1153 }
1154
1155 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001156 public NetworkCapabilities getNetworkCapabilities(Network network) {
1157 enforceAccessPermission();
1158 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1159 }
1160
1161 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001162 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001163 // Require internal since we're handing out IMSI details
1164 enforceConnectivityInternalPermission();
1165
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001166 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001167 for (Network network : getAllNetworks()) {
1168 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1169 if (nai != null) {
1170 synchronized (nai) {
1171 final String subscriberId = (nai.networkMisc != null)
1172 ? nai.networkMisc.subscriberId : null;
1173 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1174 nai.networkCapabilities, network, subscriberId, null));
1175 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001176 }
1177 }
1178 return result.toArray(new NetworkState[result.size()]);
1179 }
1180
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001181 @Override
1182 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1183 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001184 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001185 final long token = Binder.clearCallingIdentity();
1186 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001187 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1188 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001189 try {
1190 return mPolicyManager.getNetworkQuotaInfo(state);
1191 } catch (RemoteException e) {
1192 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001193 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001194 return null;
1195 } finally {
1196 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001197 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001198 }
1199
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001200 @Override
1201 public boolean isActiveNetworkMetered() {
1202 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001203 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001204 final long token = Binder.clearCallingIdentity();
1205 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001206 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001207 } finally {
1208 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001209 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001210 }
1211
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001212 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1213 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1214 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001215 try {
1216 return mPolicyManager.isNetworkMetered(state);
1217 } catch (RemoteException e) {
1218 }
1219 }
1220 return false;
1221 }
1222
Jeff Sharkey216c1812012-08-05 14:29:23 -07001223 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1224 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001225 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001226 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001227 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001228 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001229 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001230
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001231 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001232 * Ensure that a network route exists to deliver traffic to the specified
1233 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001234 * @param networkType the type of the network over which traffic to the
1235 * specified host is to be routed
1236 * @param hostAddress the IP address of the host to which the route is
1237 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001238 * @return {@code true} on success, {@code false} on failure
1239 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001240 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001242 if (mProtectedNetworks.contains(networkType)) {
1243 enforceConnectivityInternalPermission();
1244 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001245
Chad Brubakerc0234532014-02-14 13:24:29 -08001246 InetAddress addr;
1247 try {
1248 addr = InetAddress.getByAddress(hostAddress);
1249 } catch (UnknownHostException e) {
1250 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1251 return false;
1252 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001253
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001254 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001255 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 return false;
1257 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001258
1259 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1260 if (nai == null) {
1261 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1262 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1263 } else {
1264 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1265 }
1266 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001267 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001268
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001269 DetailedState netState;
1270 synchronized (nai) {
1271 netState = nai.networkInfo.getDetailedState();
1272 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001273
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001274 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001275 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001276 log("requestRouteToHostAddress on down network "
1277 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001278 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001279 }
1280 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001282
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001283 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001284 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001285 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001286 LinkProperties lp;
1287 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001288 synchronized (nai) {
1289 lp = nai.linkProperties;
1290 netId = nai.network.netId;
1291 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001292 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001293 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1294 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001295 } finally {
1296 Binder.restoreCallingIdentity(token);
1297 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001298 }
1299
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001300 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001301 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001302 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001303 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001304 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001305 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001306 if (bestRoute.getGateway().equals(addr)) {
1307 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001308 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001309 } else {
1310 // if we will connect to this through another route, add a direct route
1311 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001312 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001313 }
1314 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001315 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001316 try {
1317 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1318 } catch (Exception e) {
1319 // never crash - catch them all
1320 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001321 return false;
1322 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001323 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001324 }
1325
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001326 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1327 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001328 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001329 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001330 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001331 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001332 }
1333
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001334 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001335 // skip update when we've already applied rules
1336 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1337 if (oldRules == uidRules) return;
1338
1339 mUidRules.put(uid, uidRules);
1340 }
1341
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001342 // TODO: notify UID when it has requested targeted updates
1343 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001344
1345 @Override
1346 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001347 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001348 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001349 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001350 }
1351
1352 synchronized (mRulesLock) {
1353 mMeteredIfaces.clear();
1354 for (String iface : meteredIfaces) {
1355 mMeteredIfaces.add(iface);
1356 }
1357 }
1358 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001359
1360 @Override
1361 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1362 // caller is NPMS, since we only register with them
1363 if (LOGD_RULES) {
1364 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1365 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001366 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001367 };
1368
Robin Lee3b3dd942015-05-12 18:14:58 +01001369 /**
1370 * Require that the caller is either in the same user or has appropriate permission to interact
1371 * across users.
1372 *
1373 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1374 */
1375 private void enforceCrossUserPermission(int userId) {
1376 if (userId == UserHandle.getCallingUserId()) {
1377 // Not a cross-user call.
1378 return;
1379 }
1380 mContext.enforceCallingOrSelfPermission(
1381 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1382 "ConnectivityService");
1383 }
1384
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001385 private void enforceInternetPermission() {
1386 mContext.enforceCallingOrSelfPermission(
1387 android.Manifest.permission.INTERNET,
1388 "ConnectivityService");
1389 }
1390
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001391 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001392 mContext.enforceCallingOrSelfPermission(
1393 android.Manifest.permission.ACCESS_NETWORK_STATE,
1394 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001395 }
1396
1397 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001398 mContext.enforceCallingOrSelfPermission(
1399 android.Manifest.permission.CHANGE_NETWORK_STATE,
1400 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001401 }
1402
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001403 private void enforceTetherAccessPermission() {
1404 mContext.enforceCallingOrSelfPermission(
1405 android.Manifest.permission.ACCESS_NETWORK_STATE,
1406 "ConnectivityService");
1407 }
1408
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001409 private void enforceConnectivityInternalPermission() {
1410 mContext.enforceCallingOrSelfPermission(
1411 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1412 "ConnectivityService");
1413 }
1414
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001415 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001416 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001417 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001418 }
1419
1420 private void sendInetConditionBroadcast(NetworkInfo info) {
1421 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1422 }
1423
Wink Saville628b0852011-08-04 15:01:58 -07001424 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001425 if (mLockdownTracker != null) {
1426 info = mLockdownTracker.augmentNetworkInfo(info);
1427 }
1428
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001429 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001430 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001431 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001432 if (info.isFailover()) {
1433 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1434 info.setFailover(false);
1435 }
1436 if (info.getReason() != null) {
1437 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1438 }
1439 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001440 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1441 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001442 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001443 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001444 return intent;
1445 }
1446
1447 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1448 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1449 }
1450
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001451 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001452 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1453 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1454 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001455 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001456 final long ident = Binder.clearCallingIdentity();
1457 try {
1458 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1459 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1460 } finally {
1461 Binder.restoreCallingIdentity(ident);
1462 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001463 }
1464
Mike Lockwood0f79b542009-08-14 14:18:49 -04001465 private void sendStickyBroadcast(Intent intent) {
1466 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001467 if (!mSystemReady) {
1468 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001469 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001470 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001471 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001472 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001473 }
1474
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001475 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001476 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1477 final IBatteryStats bs = BatteryStatsService.getService();
1478 try {
1479 NetworkInfo ni = intent.getParcelableExtra(
1480 ConnectivityManager.EXTRA_NETWORK_INFO);
1481 bs.noteConnectivityChanged(intent.getIntExtra(
1482 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1483 ni != null ? ni.getState().toString() : "?");
1484 } catch (RemoteException e) {
1485 }
1486 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001487 try {
1488 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1489 } finally {
1490 Binder.restoreCallingIdentity(ident);
1491 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001492 }
1493 }
1494
1495 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001496 loadGlobalProxy();
1497
Mike Lockwood0f79b542009-08-14 14:18:49 -04001498 synchronized(this) {
1499 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001500 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001501 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001502 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001503 }
1504 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001505 // load the global proxy at startup
1506 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001507
1508 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1509 // for user to unlock device.
1510 if (!updateLockdownVpn()) {
1511 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1512 mContext.registerReceiver(mUserPresentReceiver, filter);
1513 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001514
Erik Klineda4bfa82015-04-30 12:58:40 +09001515 // Configure whether mobile data is always on.
1516 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1517
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001518 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001519
1520 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001521 }
1522
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001523 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1524 @Override
1525 public void onReceive(Context context, Intent intent) {
1526 // Try creating lockdown tracker, since user present usually means
1527 // unlocked keystore.
1528 if (updateLockdownVpn()) {
1529 mContext.unregisterReceiver(this);
1530 }
1531 }
1532 };
1533
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001534 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001535 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001536 *
1537 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001538 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001539 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001540 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1541 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001542
1543 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001544 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001545
Robert Greenwalt7b816022014-04-18 15:25:25 -07001546 if (networkAgent.networkCapabilities.hasTransport(
1547 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001548 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1549 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001550 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001551 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001552 } else if (networkAgent.networkCapabilities.hasTransport(
1553 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001554 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1555 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001556 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001557 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001558 } else {
1559 // do not track any other networks
1560 timeout = 0;
1561 }
1562
Robert Greenwalt7b816022014-04-18 15:25:25 -07001563 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001564 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001565 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001566 } catch (Exception e) {
1567 // You shall not crash!
1568 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001569 }
1570 }
1571 }
1572
1573 /**
1574 * Remove data activity tracking when network disconnects.
1575 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001576 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1577 final String iface = networkAgent.linkProperties.getInterfaceName();
1578 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001579
Robert Greenwalt7b816022014-04-18 15:25:25 -07001580 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1581 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001582 try {
1583 // the call fails silently if no idletimer setup for this interface
1584 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001585 } catch (Exception e) {
1586 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001587 }
1588 }
1589 }
1590
1591 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001592 * Reads the network specific MTU size from reources.
1593 * and set it on it's iface.
1594 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001595 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1596 final String iface = newLp.getInterfaceName();
1597 final int mtu = newLp.getMtu();
1598 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1599 if (VDBG) log("identical MTU - not setting");
1600 return;
1601 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001602
Robert Greenwalt43074032014-08-15 17:53:05 -07001603 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001604 loge("Unexpected mtu value: " + mtu + ", " + iface);
1605 return;
1606 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001607
w1997615afd812014-08-05 15:18:11 -07001608 // Cannot set MTU without interface name
1609 if (TextUtils.isEmpty(iface)) {
1610 loge("Setting MTU size with null iface.");
1611 return;
1612 }
1613
Robert Greenwalt7b816022014-04-18 15:25:25 -07001614 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001615 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001616 mNetd.setMtu(iface, mtu);
1617 } catch (Exception e) {
1618 Slog.e(TAG, "exception in setMtu()" + e);
1619 }
1620 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001621
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001622 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001623 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1624
1625 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001626 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001627 protected int getDefaultTcpRwnd() {
1628 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1629 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001630
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001631 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1632 if (isDefaultNetwork(nai) == false) {
1633 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001634 }
1635
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001636 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1637 String[] values = null;
1638 if (tcpBufferSizes != null) {
1639 values = tcpBufferSizes.split(",");
1640 }
1641
1642 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001643 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001644 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1645 values = tcpBufferSizes.split(",");
1646 }
1647
1648 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1649
1650 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001651 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001652
1653 final String prefix = "/sys/kernel/ipv4/tcp_";
1654 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1655 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1656 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1657 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1658 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1659 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1660 mCurrentTcpBufferSizes = tcpBufferSizes;
1661 } catch (IOException e) {
1662 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001663 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001664
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001665 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001666 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001667 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1668 if (rwndValue != 0) {
1669 SystemProperties.set(sysctlKey, rwndValue.toString());
1670 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001671 }
1672
Mattias Falk8b47b362011-08-23 14:15:13 +02001673 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001674 /*
1675 * Tell the VMs to toss their DNS caches
1676 */
1677 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1678 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001679 /*
1680 * Connectivity events can happen before boot has completed ...
1681 */
1682 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001683 final long ident = Binder.clearCallingIdentity();
1684 try {
1685 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1686 } finally {
1687 Binder.restoreCallingIdentity(ident);
1688 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001689 }
1690
Robert Greenwalt562cc542014-05-15 18:07:26 -07001691 @Override
1692 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001693 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1694 NETWORK_RESTORE_DELAY_PROP_NAME);
1695 if(restoreDefaultNetworkDelayStr != null &&
1696 restoreDefaultNetworkDelayStr.length() != 0) {
1697 try {
1698 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1699 } catch (NumberFormatException e) {
1700 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001701 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001702 // if the system property isn't set, use the value for the apn type
1703 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1704
1705 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1706 (mNetConfigs[networkType] != null)) {
1707 ret = mNetConfigs[networkType].restoreTime;
1708 }
1709 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001710 }
1711
Erik Kline379747a2015-06-05 17:47:34 +09001712 private boolean shouldPerformDiagnostics(String[] args) {
1713 for (String arg : args) {
1714 if (arg.equals("--diag")) {
1715 return true;
1716 }
1717 }
1718 return false;
1719 }
1720
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001722 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1723 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001724 if (mContext.checkCallingOrSelfPermission(
1725 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001726 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001727 pw.println("Permission Denial: can't dump ConnectivityService " +
1728 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1729 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 return;
1731 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001732
Erik Kline379747a2015-06-05 17:47:34 +09001733 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1734 if (shouldPerformDiagnostics(args)) {
1735 final long DIAG_TIME_MS = 5000;
1736 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1737 // Start gathering diagnostic information.
1738 netDiags.add(new NetworkDiagnostics(
1739 nai.network,
1740 new LinkProperties(nai.linkProperties),
1741 DIAG_TIME_MS));
1742 }
1743
1744 for (NetworkDiagnostics netDiag : netDiags) {
1745 pw.println();
1746 netDiag.waitForMeasurements();
1747 netDiag.dump(pw);
1748 }
1749
1750 return;
1751 }
1752
Lorenzo Colittie3805462015-06-03 11:18:24 +09001753 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001754 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001755 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001756 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001757 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001758 pw.println();
1759
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001760 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1761 pw.print("Active default network: ");
1762 if (defaultNai == null) {
1763 pw.println("none");
1764 } else {
1765 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001767 pw.println();
1768
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001769 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001770 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001771 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1772 pw.println(nai.toString());
1773 pw.increaseIndent();
1774 pw.println("Requests:");
1775 pw.increaseIndent();
1776 for (int i = 0; i < nai.networkRequests.size(); i++) {
1777 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001778 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001779 pw.decreaseIndent();
1780 pw.println("Lingered:");
1781 pw.increaseIndent();
1782 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1783 pw.decreaseIndent();
1784 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001785 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001786 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001787 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001788
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001789 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001790 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001791 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1792 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001793 }
1794 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001795 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001796
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001797 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001798
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001799 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001800 pw.print("mNetTransitionWakeLock: currently " +
1801 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1802 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1803 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1804 } else {
1805 pw.println(", last requested never");
1806 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001807 }
1808 pw.println();
1809
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001810 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001811
Lorenzo Colittie3805462015-06-03 11:18:24 +09001812 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001813 pw.println();
1814 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001815 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001816 for(int i = 0; i < mInetLog.size(); i++) {
1817 pw.println(mInetLog.get(i));
1818 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001819 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001820 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001821 }
1822
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001823 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001824 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001825 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001826 if (officialNai != null && officialNai.equals(nai)) return true;
1827 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001828 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001829 " - " + nai);
1830 }
1831 return false;
1832 }
1833
Paul Jensenc8b9a742014-09-30 15:37:41 -04001834 private boolean isRequest(NetworkRequest request) {
1835 return mNetworkRequests.get(request).isRequest;
1836 }
1837
Robert Greenwalt42acef32009-08-12 16:08:25 -07001838 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001839 private class NetworkStateTrackerHandler extends Handler {
1840 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001841 super(looper);
1842 }
1843
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001844 @Override
1845 public void handleMessage(Message msg) {
1846 NetworkInfo info;
1847 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001848 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001849 handleAsyncChannelHalfConnect(msg);
1850 break;
1851 }
1852 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1853 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1854 if (nai != null) nai.asyncChannel.disconnect();
1855 break;
1856 }
1857 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1858 handleAsyncChannelDisconnected(msg);
1859 break;
1860 }
1861 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1862 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1863 if (nai == null) {
1864 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1865 } else {
1866 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001867 }
1868 break;
1869 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001870 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1871 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1872 if (nai == null) {
1873 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1874 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001875 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001876 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001877 "; created=" + nai.created);
1878 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001879 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001880 synchronized (nai) {
1881 nai.linkProperties = (LinkProperties)msg.obj;
1882 }
Paul Jenseneec75412014-08-04 12:21:19 -04001883 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001884 }
1885 break;
1886 }
1887 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1888 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1889 if (nai == null) {
1890 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1891 break;
1892 }
1893 info = (NetworkInfo) msg.obj;
1894 updateNetworkInfo(nai, info);
1895 break;
1896 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001897 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1898 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1899 if (nai == null) {
1900 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1901 break;
1902 }
1903 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001904 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001905 break;
1906 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001907 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1908 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1909 if (nai == null) {
1910 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1911 break;
1912 }
1913 try {
1914 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001915 } catch (Exception e) {
1916 // Never crash!
1917 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001918 }
1919 break;
1920 }
1921 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1922 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1923 if (nai == null) {
1924 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1925 break;
1926 }
1927 try {
1928 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001929 } catch (Exception e) {
1930 // Never crash!
1931 loge("Exception in removeVpnUidRanges: " + e);
1932 }
1933 break;
1934 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001935 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1936 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1937 if (nai == null) {
1938 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1939 break;
1940 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001941 if (nai.created && !nai.networkMisc.explicitlySelected) {
1942 loge("ERROR: created network explicitly selected.");
1943 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001944 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001945 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001946 break;
1947 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001948 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001949 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001950 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1951 final boolean valid =
1952 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
1953 final boolean validationChanged = (valid != nai.lastValidated);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001954 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001955 if (valid) {
1956 if (DBG) log("Validated " + nai.name());
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001957 nai.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001958 if (!nai.everValidated) {
1959 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001960 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1961 ReapUnvalidatedNetworks.REAP);
1962 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001963 sendUpdatedScoreToFactories(nai);
1964 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001965 } else {
1966 nai.networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -04001967 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001968 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001969 // Let the NetworkAgent know the state of its network
1970 nai.asyncChannel.sendMessage(
1971 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1972 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1973 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001974
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001975 if (validationChanged) {
1976 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
1977 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001978 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001979 break;
1980 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001981 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001982 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001983 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1984 handleLingerComplete(nai);
1985 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001986 break;
1987 }
Paul Jensen869868be2014-05-15 10:33:05 -04001988 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09001989 final int netId = msg.arg2;
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001990 if (msg.arg1 == 0) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09001991 setProvNotificationVisibleIntent(false, netId, null, 0, null, null);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001992 } else {
Lorenzo Colittid49159f2015-05-14 23:15:10 +09001993 final NetworkAgentInfo nai;
Paul Jensen5df4bec2014-08-25 22:45:39 -04001994 synchronized (mNetworkForNetId) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09001995 nai = mNetworkForNetId.get(netId);
Paul Jensen5df4bec2014-08-25 22:45:39 -04001996 }
1997 if (nai == null) {
1998 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1999 break;
2000 }
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002001 nai.captivePortalDetected = true;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002002 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
2003 nai.networkInfo.getType(),nai.networkInfo.getExtraInfo(),
2004 (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04002005 }
Paul Jensen869868be2014-05-15 10:33:05 -04002006 break;
2007 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002008 }
2009 }
2010 }
2011
Paul Jensen0cc17322014-11-25 15:26:53 -05002012 // Cancel any lingering so the linger timeout doesn't teardown a network.
2013 // This should be called when a network begins satisfying a NetworkRequest.
2014 // Note: depending on what state the NetworkMonitor is in (e.g.,
2015 // if it's awaiting captive portal login, or if validation failed), this
2016 // may trigger a re-evaluation of the network.
2017 private void unlinger(NetworkAgentInfo nai) {
2018 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002019 // If network has never been validated, it cannot have been lingered, so don't bother
2020 // needlessly triggering a re-evaluation.
2021 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002022 nai.networkLingered.clear();
2023 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2024 }
2025
Robert Greenwalt7b816022014-04-18 15:25:25 -07002026 private void handleAsyncChannelHalfConnect(Message msg) {
2027 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002028 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002029 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2030 if (VDBG) log("NetworkFactory connected");
2031 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002032 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002033 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002034 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002035 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002036 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002037 }
2038 } else {
2039 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002040 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002041 }
2042 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2043 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2044 if (VDBG) log("NetworkAgent connected");
2045 // A network agent has requested a connection. Establish the connection.
2046 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2047 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2048 } else {
2049 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002050 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002051 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002052 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002053 synchronized (mNetworkForNetId) {
2054 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002055 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002056 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002057 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002058 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002059 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002060 }
2061 }
2062 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002063
Robert Greenwalt7b816022014-04-18 15:25:25 -07002064 private void handleAsyncChannelDisconnected(Message msg) {
2065 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2066 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002067 if (DBG) {
2068 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2069 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002070 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002071 if (nai.created) {
2072 // Tell netd to clean up the configuration for this network
2073 // (routing rules, DNS, etc).
2074 try {
2075 mNetd.removeNetwork(nai.network.netId);
2076 } catch (Exception e) {
2077 loge("Exception removing network: " + e);
2078 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002079 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002080 // TODO - if we move the logic to the network agent (have them disconnect
2081 // because they lost all their requests or because their score isn't good)
2082 // then they would disconnect organically, report their new state and then
2083 // disconnect the channel.
2084 if (nai.networkInfo.isConnected()) {
2085 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2086 null, null);
2087 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002088 final boolean wasDefault = isDefaultNetwork(nai);
2089 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002090 mDefaultInetConditionPublished = 0;
2091 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002092 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002093 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002094 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002095 mNetworkAgentInfos.remove(msg.replyTo);
2096 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002097 synchronized (mNetworkForNetId) {
2098 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002099 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002100 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002101 // Since we've lost the network, go through all the requests that
2102 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002103 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002104 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002105 for (int i = 0; i < nai.networkRequests.size(); i++) {
2106 NetworkRequest request = nai.networkRequests.valueAt(i);
2107 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2108 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002109 if (DBG) {
2110 log("Checking for replacement network to handle request " + request );
2111 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002112 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002113 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002114 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002115 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2116 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002117 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002118 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002119 alternative = existing;
2120 }
2121 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002122 if (alternative != null) {
2123 if (DBG) log(" found replacement in " + alternative.name());
2124 if (!toActivate.contains(alternative)) {
2125 toActivate.add(alternative);
2126 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002127 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 }
2129 }
2130 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2131 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002132 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002133 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002134 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002135 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002136 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002137 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002138 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2139 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002140 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002141 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302142 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2143 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 }
2145
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002146 // If this method proves to be too slow then we can maintain a separate
2147 // pendingIntent => NetworkRequestInfo map.
2148 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2149 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2150 Intent intent = pendingIntent.getIntent();
2151 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2152 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2153 if (existingPendingIntent != null &&
2154 existingPendingIntent.getIntent().filterEquals(intent)) {
2155 return entry.getValue();
2156 }
2157 }
2158 return null;
2159 }
2160
2161 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2162 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2163
2164 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2165 if (existingRequest != null) { // remove the existing request.
2166 if (DBG) log("Replacing " + existingRequest.request + " with "
2167 + nri.request + " because their intents matched.");
2168 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2169 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002170 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002171 }
2172
Erik Klineda4bfa82015-04-30 12:58:40 +09002173 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002174 mNetworkRequests.put(nri.request, nri);
2175
Paul Jensen0cc17322014-11-25 15:26:53 -05002176 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2177
Robert Greenwalt9258c642014-03-26 16:47:06 -07002178 // Check for the best currently alive network that satisfies this request
2179 NetworkAgentInfo bestNetwork = null;
2180 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002181 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002182 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002183 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002184 if (!nri.isRequest) {
2185 // Not setting bestNetwork here as a listening NetworkRequest may be
2186 // satisfied by multiple Networks. Instead the request is added to
2187 // each satisfying Network and notified about each.
2188 network.addRequest(nri.request);
2189 notifyNetworkCallback(network, nri);
2190 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002191 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002192 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002193 }
2194 }
2195 }
2196 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002197 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002198 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002199 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002200 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002201 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002202 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002203 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2204 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002205 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002206
Lorenzo Colittia793a672014-07-31 23:20:17 +09002207 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002208 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002209 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002210 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002211 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002212 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002213 }
2214 }
2215 }
2216
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002217 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2218 int callingUid) {
2219 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2220 if (nri != null) {
2221 handleReleaseNetworkRequest(nri.request, callingUid);
2222 }
2223 }
2224
Paul Jensen99364842014-12-09 11:43:45 -05002225 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2226 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2227 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2228 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2229 private boolean unneeded(NetworkAgentInfo nai) {
2230 if (!nai.created || nai.isVPN()) return false;
2231 boolean unneeded = true;
2232 if (nai.everValidated) {
2233 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2234 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2235 try {
2236 if (isRequest(nr)) unneeded = false;
2237 } catch (Exception e) {
2238 loge("Request " + nr + " not found in mNetworkRequests.");
2239 loge(" it came from request list of " + nai.name());
2240 }
2241 }
2242 } else {
2243 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2244 // If this Network is already the highest scoring Network for a request, or if
2245 // there is hope for it to become one if it validated, then it is needed.
2246 if (nri.isRequest && nai.satisfies(nri.request) &&
2247 (nai.networkRequests.get(nri.request.requestId) != null ||
2248 // Note that this catches two important cases:
2249 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2250 // is currently satisfying the request. This is desirable when
2251 // cellular ends up validating but WiFi does not.
2252 // 2. Unvalidated WiFi will not be reaped when validated cellular
2253 // is currently satsifying the request. This is desirable when
2254 // WiFi ends up validating and out scoring cellular.
2255 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2256 nai.getCurrentScoreAsValidated())) {
2257 unneeded = false;
2258 break;
2259 }
2260 }
2261 }
2262 return unneeded;
2263 }
2264
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002265 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2266 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002267 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002268 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002269 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2270 return;
2271 }
2272 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002273 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002274 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002275 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002276 // Find all networks that are satisfying this request and remove the request
2277 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002278 // TODO - it's my understanding that for a request there is only a single
2279 // network satisfying it, so this loop is wasteful
2280 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002281 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2282 if (nai.networkRequests.get(nri.request.requestId) != null) {
2283 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002284 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002285 log(" Removing from current network " + nai.name() +
2286 ", leaving " + nai.networkRequests.size() +
2287 " requests.");
2288 }
Paul Jensen99364842014-12-09 11:43:45 -05002289 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002290 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002291 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002292 } else {
2293 // suspect there should only be one pass through here
2294 // but if any were kept do the check below
2295 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002296 }
2297 }
2298 }
2299
Robert Greenwalt51481852015-01-08 14:43:31 -08002300 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2301 if (nai != null) {
2302 mNetworkForRequestId.remove(nri.request.requestId);
2303 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002304 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002305 // that a network connected to serve it, even though the network was already
2306 // connected. Now that this request has gone away, we might have to pretend
2307 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002308 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002309 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2310 boolean doRemove = true;
2311 if (wasKept) {
2312 // check if any of the remaining requests for this network are for the
2313 // same legacy type - if so, don't remove the nai
2314 for (int i = 0; i < nai.networkRequests.size(); i++) {
2315 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2316 if (otherRequest.legacyType == nri.request.legacyType &&
2317 isRequest(otherRequest)) {
2318 if (DBG) log(" still have other legacy request - leaving");
2319 doRemove = false;
2320 }
2321 }
2322 }
2323
2324 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002325 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002326 }
2327 }
2328
Robert Greenwalta67be032014-05-16 15:49:14 -07002329 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002330 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2331 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002332 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002333 } else {
2334 // listens don't have a singular affectedNetwork. Check all networks to see
2335 // if this listen request applies and remove it.
2336 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2337 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002338 }
2339 }
2340 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2341 }
2342 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002343
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002344 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2345 enforceConnectivityInternalPermission();
2346 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2347 accept ? 1 : 0, always ? 1: 0, network));
2348 }
2349
2350 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2351 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2352 " accept=" + accept + " always=" + always);
2353
2354 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2355 if (nai == null) {
2356 // Nothing to do.
2357 return;
2358 }
2359
2360 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002361 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002362 return;
2363 }
2364
2365 if (!nai.networkMisc.explicitlySelected) {
2366 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2367 }
2368
2369 if (accept != nai.networkMisc.acceptUnvalidated) {
2370 int oldScore = nai.getCurrentScore();
2371 nai.networkMisc.acceptUnvalidated = accept;
2372 rematchAllNetworksAndRequests(nai, oldScore);
2373 sendUpdatedScoreToFactories(nai);
2374 }
2375
2376 if (always) {
2377 nai.asyncChannel.sendMessage(
2378 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2379 }
2380
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002381 if (!accept) {
2382 // Tell the NetworkAgent that the network does not have Internet access (because that's
2383 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2384 // the future. We do this now because NetworkMonitor might not yet have finished
2385 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2386 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2387 NetworkAgent.INVALID_NETWORK, 0, null);
2388 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2389 // to reconnect to it immediately. http://b/20739299
2390 }
2391
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002392 }
2393
2394 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002395 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002396 mHandler.sendMessageDelayed(
2397 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2398 PROMPT_UNVALIDATED_DELAY_MS);
2399 }
2400
2401 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002402 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002403 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2404
2405 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2406 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002407 // Also don't prompt on captive portals because we're already prompting the user to sign in.
2408 if (nai == null || nai.everValidated || nai.captivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002409 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2410 return;
2411 }
2412
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002413 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002414 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002415 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2416 intent.setClassName("com.android.settings",
2417 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002418
2419 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2420 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2421 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
2422 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002423 }
2424
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002425 private class InternalHandler extends Handler {
2426 public InternalHandler(Looper looper) {
2427 super(looper);
2428 }
2429
2430 @Override
2431 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002432 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002433 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002434 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002435 String causedBy = null;
2436 synchronized (ConnectivityService.this) {
2437 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2438 mNetTransitionWakeLock.isHeld()) {
2439 mNetTransitionWakeLock.release();
2440 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002441 } else {
2442 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002443 }
2444 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002445 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2446 log("Failed to find a new network - expiring NetTransition Wakelock");
2447 } else {
2448 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2449 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002450 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002451 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002452 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002453 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002454 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002455 break;
2456 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002457 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002458 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002459 sendStickyBroadcast(intent);
2460 break;
2461 }
Jason Monkdecd2952013-10-10 14:02:51 -04002462 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002463 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002464 break;
2465 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002466 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002467 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2468 break;
2469 }
2470 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2471 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002472 break;
2473 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002474 case EVENT_REGISTER_NETWORK_AGENT: {
2475 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2476 break;
2477 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002478 case EVENT_REGISTER_NETWORK_REQUEST:
2479 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002480 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002481 break;
2482 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002483 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2484 handleRegisterNetworkRequestWithIntent(msg);
2485 break;
2486 }
2487 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2488 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2489 break;
2490 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002491 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002492 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002493 break;
2494 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002495 case EVENT_SET_ACCEPT_UNVALIDATED: {
2496 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2497 break;
2498 }
2499 case EVENT_PROMPT_UNVALIDATED: {
2500 handlePromptUnvalidated((Network) msg.obj);
2501 break;
2502 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002503 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2504 handleMobileDataAlwaysOn();
2505 break;
2506 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002507 case EVENT_SYSTEM_READY: {
2508 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2509 nai.networkMonitor.systemReady = true;
2510 }
2511 break;
2512 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002513 }
2514 }
2515 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002516
2517 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002518 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002519 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002520 if (isTetheringSupported()) {
2521 return mTethering.tether(iface);
2522 } else {
2523 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2524 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002525 }
2526
2527 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002528 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002529 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002530
2531 if (isTetheringSupported()) {
2532 return mTethering.untether(iface);
2533 } else {
2534 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2535 }
2536 }
2537
2538 // javadoc from interface
2539 public int getLastTetherError(String iface) {
2540 enforceTetherAccessPermission();
2541
2542 if (isTetheringSupported()) {
2543 return mTethering.getLastTetherError(iface);
2544 } else {
2545 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2546 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002547 }
2548
2549 // TODO - proper iface API for selection by property, inspection, etc
2550 public String[] getTetherableUsbRegexs() {
2551 enforceTetherAccessPermission();
2552 if (isTetheringSupported()) {
2553 return mTethering.getTetherableUsbRegexs();
2554 } else {
2555 return new String[0];
2556 }
2557 }
2558
2559 public String[] getTetherableWifiRegexs() {
2560 enforceTetherAccessPermission();
2561 if (isTetheringSupported()) {
2562 return mTethering.getTetherableWifiRegexs();
2563 } else {
2564 return new String[0];
2565 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002566 }
2567
Danica Chang6fdd0c62010-08-11 14:54:43 -07002568 public String[] getTetherableBluetoothRegexs() {
2569 enforceTetherAccessPermission();
2570 if (isTetheringSupported()) {
2571 return mTethering.getTetherableBluetoothRegexs();
2572 } else {
2573 return new String[0];
2574 }
2575 }
2576
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002577 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002578 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002579 if (isTetheringSupported()) {
2580 return mTethering.setUsbTethering(enable);
2581 } else {
2582 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2583 }
2584 }
2585
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002586 // TODO - move iface listing, queries, etc to new module
2587 // javadoc from interface
2588 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002589 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002590 return mTethering.getTetherableIfaces();
2591 }
2592
2593 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002594 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002595 return mTethering.getTetheredIfaces();
2596 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002597
Robert Greenwalt5a735062010-03-02 17:25:02 -08002598 public String[] getTetheringErroredIfaces() {
2599 enforceTetherAccessPermission();
2600 return mTethering.getErroredIfaces();
2601 }
2602
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002603 public String[] getTetheredDhcpRanges() {
2604 enforceConnectivityInternalPermission();
2605 return mTethering.getTetheredDhcpRanges();
2606 }
2607
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002608 // if ro.tether.denied = true we default to no tethering
2609 // gservices could set the secure setting to 1 though to enable it on a build where it
2610 // had previously been turned off.
2611 public boolean isTetheringSupported() {
2612 enforceTetherAccessPermission();
2613 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002614 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002615 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2616 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002617 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2618 mTethering.getTetherableWifiRegexs().length != 0 ||
2619 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2620 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002621 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002622
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002623 // Called when we lose the default network and have no replacement yet.
2624 // This will automatically be cleared after X seconds or a new default network
2625 // becomes CONNECTED, whichever happens first. The timer is started by the
2626 // first caller and not restarted by subsequent callers.
2627 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002628 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002629 synchronized (this) {
2630 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002631 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002632 mNetTransitionWakeLock.acquire();
2633 mNetTransitionWakeLockCausedBy = forWhom;
2634 }
2635 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002636 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002637 mNetTransitionWakeLockTimeout);
2638 return;
2639 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002640
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002641 // 100 percent is full good, 0 is full bad.
2642 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002643 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002644 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002645 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002646 }
2647
Paul Jensenbfd17b72015-04-07 12:43:13 -04002648 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002649 enforceAccessPermission();
2650 enforceInternetPermission();
2651
Paul Jensenbfd17b72015-04-07 12:43:13 -04002652 NetworkAgentInfo nai;
2653 if (network == null) {
2654 nai = getDefaultNetwork();
2655 } else {
2656 nai = getNetworkAgentInfoForNetwork(network);
2657 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002658 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002659 // Revalidate if the app report does not match our current validated state.
2660 if (hasConnectivity == nai.lastValidated) return;
2661 final int uid = Binder.getCallingUid();
2662 if (DBG) {
2663 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2664 ") by " + uid);
2665 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002666 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002667 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2668 // which isn't meant to work on uncreated networks.
2669 if (!nai.created) return;
2670
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002671 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002672
2673 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2674 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002675 }
2676
Paul Jensen25a217c2015-02-27 22:55:47 -05002677 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2678 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2679 enforceConnectivityInternalPermission();
2680 }
2681 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2682 if (nai == null) return;
2683 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2684 actionToken);
2685 }
2686
Paul Jensencee9b512015-05-06 07:32:40 -04002687 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002688 // this information is already available as a world read/writable jvm property
2689 // so this API change wouldn't have a benifit. It also breaks the passing
2690 // of proxy info to all the JVMs.
2691 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002692 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002693 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002694 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2695 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002696 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002697 }
2698
Paul Jensencee9b512015-05-06 07:32:40 -04002699 public ProxyInfo getProxyForNetwork(Network network) {
2700 if (network == null) return getDefaultProxy();
2701 final ProxyInfo globalProxy = getGlobalProxy();
2702 if (globalProxy != null) return globalProxy;
2703 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2704 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2705 // caller may not have.
2706 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2707 if (nai == null) return null;
2708 synchronized (nai) {
2709 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2710 if (proxyInfo == null) return null;
2711 return new ProxyInfo(proxyInfo);
2712 }
2713 }
2714
Paul Jensene0bef712014-12-10 15:12:18 -05002715 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2716 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2717 // proxy is null then there is no proxy in place).
2718 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2719 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2720 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2721 proxy = null;
2722 }
2723 return proxy;
2724 }
2725
2726 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2727 // better for determining if a new proxy broadcast is necessary:
2728 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2729 // avoid unnecessary broadcasts.
2730 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2731 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2732 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2733 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2734 // all set.
2735 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2736 a = canonicalizeProxyInfo(a);
2737 b = canonicalizeProxyInfo(b);
2738 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2739 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2740 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2741 }
2742
Jason Monk207900c2014-04-25 15:00:09 -04002743 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002744 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002745
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002746 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002747 if (proxyProperties == mGlobalProxy) return;
2748 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2749 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2750
2751 String host = "";
2752 int port = 0;
2753 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002754 String pacFileUrl = "";
2755 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002756 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002757 if (!proxyProperties.isValid()) {
2758 if (DBG)
2759 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2760 return;
2761 }
Jason Monk207900c2014-04-25 15:00:09 -04002762 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002763 host = mGlobalProxy.getHost();
2764 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002765 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002766 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002767 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002768 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002769 } else {
2770 mGlobalProxy = null;
2771 }
2772 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002773 final long token = Binder.clearCallingIdentity();
2774 try {
2775 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2776 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2777 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2778 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002779 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002780 } finally {
2781 Binder.restoreCallingIdentity(token);
2782 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002783
Jason Monkcf0f97a2014-10-02 15:39:38 -04002784 if (mGlobalProxy == null) {
2785 proxyProperties = mDefaultProxy;
2786 }
2787 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002788 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002789 }
2790
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002791 private void loadGlobalProxy() {
2792 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002793 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2794 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2795 String exclList = Settings.Global.getString(res,
2796 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002797 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2798 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002799 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002800 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002801 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002802 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002803 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002804 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002805 if (!proxyProperties.isValid()) {
2806 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2807 return;
2808 }
2809
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002810 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002811 mGlobalProxy = proxyProperties;
2812 }
2813 }
2814 }
2815
Jason Monk207900c2014-04-25 15:00:09 -04002816 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002817 // this information is already available as a world read/writable jvm property
2818 // so this API change wouldn't have a benifit. It also breaks the passing
2819 // of proxy info to all the JVMs.
2820 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002821 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002822 return mGlobalProxy;
2823 }
2824 }
2825
Jason Monk207900c2014-04-25 15:00:09 -04002826 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002827 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002828 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002829 proxy = null;
2830 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002831 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002832 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002833 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002834 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002835 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2836 return;
2837 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002838
2839 // This call could be coming from the PacManager, containing the port of the local
2840 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2841 // global (to get the correct local port), and send a broadcast.
2842 // TODO: Switch PacManager to have its own message to send back rather than
2843 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002844 if ((mGlobalProxy != null) && (proxy != null)
2845 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002846 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2847 mGlobalProxy = proxy;
2848 sendProxyBroadcast(mGlobalProxy);
2849 return;
2850 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002851 mDefaultProxy = proxy;
2852
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002853 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002854 if (!mDefaultProxyDisabled) {
2855 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002856 }
2857 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002858 }
2859
Paul Jensene0bef712014-12-10 15:12:18 -05002860 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2861 // This method gets called when any network changes proxy, but the broadcast only ever contains
2862 // the default proxy (even if it hasn't changed).
2863 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2864 // world where an app might be bound to a non-default network.
2865 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2866 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2867 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2868
2869 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2870 sendProxyBroadcast(getDefaultProxy());
2871 }
2872 }
2873
Robert Greenwalt434203a2010-10-11 16:00:27 -07002874 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002875 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2876 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002877 if (!TextUtils.isEmpty(proxy)) {
2878 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002879 if (data.length == 0) {
2880 return;
2881 }
2882
Robert Greenwalt434203a2010-10-11 16:00:27 -07002883 String proxyHost = data[0];
2884 int proxyPort = 8080;
2885 if (data.length > 1) {
2886 try {
2887 proxyPort = Integer.parseInt(data[1]);
2888 } catch (NumberFormatException e) {
2889 return;
2890 }
2891 }
Jason Monk207900c2014-04-25 15:00:09 -04002892 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002893 setGlobalProxy(p);
2894 }
2895 }
2896
Jason Monk207900c2014-04-25 15:00:09 -04002897 private void sendProxyBroadcast(ProxyInfo proxy) {
2898 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002899 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002900 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002901 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002902 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2903 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002904 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002905 final long ident = Binder.clearCallingIdentity();
2906 try {
2907 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2908 } finally {
2909 Binder.restoreCallingIdentity(ident);
2910 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002911 }
2912
2913 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002914 final private HashMap<Uri, Integer> mUriEventMap;
2915 final private Context mContext;
2916 final private Handler mHandler;
2917
2918 SettingsObserver(Context context, Handler handler) {
2919 super(null);
2920 mUriEventMap = new HashMap<Uri, Integer>();
2921 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002923 }
2924
Erik Klineda4bfa82015-04-30 12:58:40 +09002925 void observe(Uri uri, int what) {
2926 mUriEventMap.put(uri, what);
2927 final ContentResolver resolver = mContext.getContentResolver();
2928 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002929 }
2930
2931 @Override
2932 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002933 Slog.wtf(TAG, "Should never be reached.");
2934 }
2935
2936 @Override
2937 public void onChange(boolean selfChange, Uri uri) {
2938 final Integer what = mUriEventMap.get(uri);
2939 if (what != null) {
2940 mHandler.obtainMessage(what.intValue()).sendToTarget();
2941 } else {
2942 loge("No matching event to send for URI=" + uri);
2943 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002944 }
2945 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002946
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002947 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002948 Slog.d(TAG, s);
2949 }
2950
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002951 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002952 Slog.e(TAG, s);
2953 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002954
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002955 private static <T> T checkNotNull(T value, String message) {
2956 if (value == null) {
2957 throw new NullPointerException(message);
2958 }
2959 return value;
2960 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002961
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002962 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002963 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002964 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2965 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2966 *
2967 * @param oldPackage Package name of the application which currently controls VPN, which will
2968 * be replaced. If there is no such application, this should should either be
2969 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2970 * @param newPackage Package name of the application which should gain control of VPN, or
2971 * {@code null} to disable.
2972 * @param userId User for whom to prepare the new VPN.
2973 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002974 * @hide
2975 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002976 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002977 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2978 int userId) {
2979 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002980 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002981
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002982 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07002983 Vpn vpn = mVpns.get(userId);
2984 if (vpn != null) {
2985 return vpn.prepare(oldPackage, newPackage);
2986 } else {
2987 return false;
2988 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002989 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002990 }
2991
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002992 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002993 * Set whether the VPN package has the ability to launch VPNs without user intervention.
2994 * This method is used by system-privileged apps.
2995 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2996 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2997 *
2998 * @param packageName The package for which authorization state should change.
2999 * @param userId User for whom {@code packageName} is installed.
3000 * @param authorized {@code true} if this app should be able to start a VPN connection without
3001 * explicit user approval, {@code false} if not.
3002 *
Jeff Davidson05542602014-08-11 14:07:27 -07003003 * @hide
3004 */
3005 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003006 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3007 enforceCrossUserPermission(userId);
3008
Jeff Davidson05542602014-08-11 14:07:27 -07003009 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003010 Vpn vpn = mVpns.get(userId);
3011 if (vpn != null) {
3012 vpn.setPackageAuthorization(packageName, authorized);
3013 }
Jeff Davidson05542602014-08-11 14:07:27 -07003014 }
3015 }
3016
3017 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003018 * Configure a TUN interface and return its file descriptor. Parameters
3019 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003020 * and not available in ConnectivityManager. Permissions are checked in
3021 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003022 * @hide
3023 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003024 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003025 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003026 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003027 int user = UserHandle.getUserId(Binder.getCallingUid());
3028 synchronized(mVpns) {
3029 return mVpns.get(user).establish(config);
3030 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003031 }
3032
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003033 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003034 * Start legacy VPN, controlling native daemons as needed. Creates a
3035 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003036 */
3037 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003038 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003039 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003040 final LinkProperties egress = getActiveLinkProperties();
3041 if (egress == null) {
3042 throw new IllegalStateException("Missing active network connection");
3043 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003044 int user = UserHandle.getUserId(Binder.getCallingUid());
3045 synchronized(mVpns) {
3046 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3047 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003048 }
3049
3050 /**
3051 * Return the information of the ongoing legacy VPN. This method is used
3052 * by VpnSettings and not available in ConnectivityManager. Permissions
3053 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003054 */
3055 @Override
3056 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003057 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003058 int user = UserHandle.getUserId(Binder.getCallingUid());
3059 synchronized(mVpns) {
3060 return mVpns.get(user).getLegacyVpnInfo();
3061 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003062 }
3063
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003064 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003065 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3066 * and not available in ConnectivityManager.
3067 */
3068 @Override
3069 public VpnInfo[] getAllVpnInfo() {
3070 enforceConnectivityInternalPermission();
3071 if (mLockdownEnabled) {
3072 return new VpnInfo[0];
3073 }
3074
3075 synchronized(mVpns) {
3076 List<VpnInfo> infoList = new ArrayList<>();
3077 for (int i = 0; i < mVpns.size(); i++) {
3078 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3079 if (info != null) {
3080 infoList.add(info);
3081 }
3082 }
3083 return infoList.toArray(new VpnInfo[infoList.size()]);
3084 }
3085 }
3086
3087 /**
3088 * @return VPN information for accounting, or null if we can't retrieve all required
3089 * information, e.g primary underlying iface.
3090 */
3091 @Nullable
3092 private VpnInfo createVpnInfo(Vpn vpn) {
3093 VpnInfo info = vpn.getVpnInfo();
3094 if (info == null) {
3095 return null;
3096 }
3097 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3098 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3099 // the underlyingNetworks list.
3100 if (underlyingNetworks == null) {
3101 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3102 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3103 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3104 }
3105 } else if (underlyingNetworks.length > 0) {
3106 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3107 if (linkProperties != null) {
3108 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3109 }
3110 }
3111 return info.primaryUnderlyingIface == null ? null : info;
3112 }
3113
3114 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003115 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3116 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003117 * Permissions are checked in Vpn class.
3118 * @hide
3119 */
3120 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003121 public VpnConfig getVpnConfig(int userId) {
3122 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003123 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003124 Vpn vpn = mVpns.get(userId);
3125 if (vpn != null) {
3126 return vpn.getVpnConfig();
3127 } else {
3128 return null;
3129 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003130 }
3131 }
3132
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003133 @Override
3134 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003135 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3136 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3137 return false;
3138 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003139
3140 // Tear down existing lockdown if profile was removed
3141 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3142 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003143 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003144 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3145 return false;
3146 }
3147
3148 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3149 final VpnProfile profile = VpnProfile.decode(
3150 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003151 int user = UserHandle.getUserId(Binder.getCallingUid());
3152 synchronized(mVpns) {
3153 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3154 profile));
3155 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003156 } else {
3157 setLockdownTracker(null);
3158 }
3159
3160 return true;
3161 }
3162
3163 /**
3164 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3165 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3166 */
3167 private void setLockdownTracker(LockdownVpnTracker tracker) {
3168 // Shutdown any existing tracker
3169 final LockdownVpnTracker existing = mLockdownTracker;
3170 mLockdownTracker = null;
3171 if (existing != null) {
3172 existing.shutdown();
3173 }
3174
3175 try {
3176 if (tracker != null) {
3177 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003178 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003179 mLockdownTracker = tracker;
3180 mLockdownTracker.init();
3181 } else {
3182 mNetd.setFirewallEnabled(false);
3183 }
3184 } catch (RemoteException e) {
3185 // ignored; NMS lives inside system_server
3186 }
3187 }
3188
3189 private void throwIfLockdownEnabled() {
3190 if (mLockdownEnabled) {
3191 throw new IllegalStateException("Unavailable in lockdown mode");
3192 }
3193 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003194
Wink Savilleab9321d2013-06-29 21:10:57 -07003195 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003196 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003197 // TODO: Remove? Any reason to trigger a provisioning check?
3198 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003199 }
3200
3201 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003202 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003203
Paul Jensen89e0f092014-09-15 15:59:36 -04003204 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003205 if (DBG) {
3206 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003207 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003208 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003209 Intent intent = new Intent(action);
3210 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003211 // Concatenate the range of types onto the range of NetIDs.
3212 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003213 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3214 networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003215 }
3216
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003217 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003218 * Show or hide network provisioning notifications.
3219 *
3220 * We use notifications for two purposes: to notify that a network requires sign in
3221 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3222 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3223 * particular network we can display the notification type that was most recently requested.
3224 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3225 * might first display NO_INTERNET, and then when the captive portal check completes, display
3226 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003227 *
3228 * @param id an identifier that uniquely identifies this notification. This must match
3229 * between show and hide calls. We use the NetID value but for legacy callers
3230 * we concatenate the range of types with the range of NetIDs.
3231 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003232 private void setProvNotificationVisibleIntent(boolean visible, int id,
3233 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent) {
Paul Jensen869868be2014-05-15 10:33:05 -04003234 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003235 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3236 + " networkType=" + getNetworkTypeName(networkType)
3237 + " extraInfo=" + extraInfo);
Paul Jensen869868be2014-05-15 10:33:05 -04003238 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003239
3240 Resources r = Resources.getSystem();
3241 NotificationManager notificationManager = (NotificationManager) mContext
3242 .getSystemService(Context.NOTIFICATION_SERVICE);
3243
3244 if (visible) {
3245 CharSequence title;
3246 CharSequence details;
3247 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003248 if (notifyType == NotificationType.NO_INTERNET &&
3249 networkType == ConnectivityManager.TYPE_WIFI) {
3250 title = r.getString(R.string.wifi_no_internet, 0);
3251 details = r.getString(R.string.wifi_no_internet_detailed);
3252 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3253 } else if (notifyType == NotificationType.SIGN_IN) {
3254 switch (networkType) {
3255 case ConnectivityManager.TYPE_WIFI:
3256 title = r.getString(R.string.wifi_available_sign_in, 0);
3257 details = r.getString(R.string.network_available_sign_in_detailed,
3258 extraInfo);
3259 icon = R.drawable.stat_notify_wifi_in_range;
3260 break;
3261 case ConnectivityManager.TYPE_MOBILE:
3262 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3263 title = r.getString(R.string.network_available_sign_in, 0);
3264 // TODO: Change this to pull from NetworkInfo once a printable
3265 // name has been added to it
3266 details = mTelephonyManager.getNetworkOperatorName();
3267 icon = R.drawable.stat_notify_rssi_in_range;
3268 break;
3269 default:
3270 title = r.getString(R.string.network_available_sign_in, 0);
3271 details = r.getString(R.string.network_available_sign_in_detailed,
3272 extraInfo);
3273 icon = R.drawable.stat_notify_rssi_in_range;
3274 break;
3275 }
3276 } else {
3277 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3278 + getNetworkTypeName(networkType));
3279 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003280 }
3281
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003282 Notification notification = new Notification.Builder(mContext)
3283 .setWhen(0)
3284 .setSmallIcon(icon)
3285 .setAutoCancel(true)
3286 .setTicker(title)
3287 .setColor(mContext.getColor(
3288 com.android.internal.R.color.system_notification_accent_color))
3289 .setContentTitle(title)
3290 .setContentText(details)
3291 .setContentIntent(intent)
3292 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003293
Wink Saville948282b2013-08-29 08:55:16 -07003294 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003295 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003296 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003297 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003298 npe.printStackTrace();
3299 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003300 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003301 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003302 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003303 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003304 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003305 npe.printStackTrace();
3306 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003307 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003308 }
3309
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003310 /** Location to an updatable file listing carrier provisioning urls.
3311 * An example:
3312 *
3313 * <?xml version="1.0" encoding="utf-8"?>
3314 * <provisioningUrls>
3315 * <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 -07003316 * </provisioningUrls>
3317 */
3318 private static final String PROVISIONING_URL_PATH =
3319 "/data/misc/radio/provisioning_urls.xml";
3320 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003321
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003322 /** XML tag for root element. */
3323 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3324 /** XML tag for individual url */
3325 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003326 /** XML attribute for mcc */
3327 private static final String ATTR_MCC = "mcc";
3328 /** XML attribute for mnc */
3329 private static final String ATTR_MNC = "mnc";
3330
Paul Jensen434dde82015-06-11 09:43:30 -04003331 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003332 FileReader fileReader = null;
3333 XmlPullParser parser = null;
3334 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003335
3336 try {
3337 fileReader = new FileReader(mProvisioningUrlFile);
3338 parser = Xml.newPullParser();
3339 parser.setInput(fileReader);
3340 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3341
3342 while (true) {
3343 XmlUtils.nextElement(parser);
3344
3345 String element = parser.getName();
3346 if (element == null) break;
3347
Paul Jensen434dde82015-06-11 09:43:30 -04003348 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003349 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3350 try {
3351 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3352 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3353 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3354 parser.next();
3355 if (parser.getEventType() == XmlPullParser.TEXT) {
3356 return parser.getText();
3357 }
3358 }
3359 }
3360 } catch (NumberFormatException e) {
3361 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3362 }
3363 }
3364 }
3365 return null;
3366 } catch (FileNotFoundException e) {
3367 loge("Carrier Provisioning Urls file not found");
3368 } catch (XmlPullParserException e) {
3369 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3370 } catch (IOException e) {
3371 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3372 } finally {
3373 if (fileReader != null) {
3374 try {
3375 fileReader.close();
3376 } catch (IOException e) {}
3377 }
3378 }
3379 return null;
3380 }
3381
Wink Saville42d4f082013-07-20 20:31:59 -07003382 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003383 public String getMobileProvisioningUrl() {
3384 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003385 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003386 if (TextUtils.isEmpty(url)) {
3387 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003388 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003389 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003390 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003391 }
Wink Saville8cf35602013-07-10 23:00:07 -07003392 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003393 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003394 String phoneNumber = mTelephonyManager.getLine1Number();
3395 if (TextUtils.isEmpty(phoneNumber)) {
3396 phoneNumber = "0000000000";
3397 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003398 url = String.format(url,
3399 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3400 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003401 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003402 }
3403
Wink Savilleab9321d2013-06-29 21:10:57 -07003404 return url;
3405 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003406
Wink Saville948282b2013-08-29 08:55:16 -07003407 @Override
3408 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003409 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003410 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003411 final long ident = Binder.clearCallingIdentity();
3412 try {
3413 setProvNotificationVisible(visible, networkType, action);
3414 } finally {
3415 Binder.restoreCallingIdentity(ident);
3416 }
Wink Saville948282b2013-08-29 08:55:16 -07003417 }
Wink Saville7788c612013-08-29 14:57:08 -07003418
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003419 @Override
3420 public void setAirplaneMode(boolean enable) {
3421 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003422 final long ident = Binder.clearCallingIdentity();
3423 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003424 final ContentResolver cr = mContext.getContentResolver();
3425 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3426 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3427 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003428 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003429 } finally {
3430 Binder.restoreCallingIdentity(ident);
3431 }
3432 }
3433
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003434 private void onUserStart(int userId) {
3435 synchronized(mVpns) {
3436 Vpn userVpn = mVpns.get(userId);
3437 if (userVpn != null) {
3438 loge("Starting user already has a VPN");
3439 return;
3440 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003441 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003442 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003443 }
3444 }
3445
3446 private void onUserStop(int userId) {
3447 synchronized(mVpns) {
3448 Vpn userVpn = mVpns.get(userId);
3449 if (userVpn == null) {
3450 loge("Stopping user has no VPN");
3451 return;
3452 }
3453 mVpns.delete(userId);
3454 }
3455 }
3456
3457 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3458 @Override
3459 public void onReceive(Context context, Intent intent) {
3460 final String action = intent.getAction();
3461 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3462 if (userId == UserHandle.USER_NULL) return;
3463
3464 if (Intent.ACTION_USER_STARTING.equals(action)) {
3465 onUserStart(userId);
3466 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3467 onUserStop(userId);
3468 }
3469 }
3470 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003471
Robert Greenwalta67be032014-05-16 15:49:14 -07003472 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3473 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003474 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3475 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003476
Robert Greenwalta67be032014-05-16 15:49:14 -07003477 private static class NetworkFactoryInfo {
3478 public final String name;
3479 public final Messenger messenger;
3480 public final AsyncChannel asyncChannel;
3481
3482 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3483 this.name = name;
3484 this.messenger = messenger;
3485 this.asyncChannel = asyncChannel;
3486 }
3487 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003488
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003489 /**
3490 * Tracks info about the requester.
3491 * Also used to notice when the calling process dies so we can self-expire
3492 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003493 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3494 static final boolean REQUEST = true;
3495 static final boolean LISTEN = false;
3496
3497 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003498 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003499 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003500 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003501 final int mPid;
3502 final int mUid;
3503 final Messenger messenger;
3504 final boolean isRequest;
3505
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003506 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3507 request = r;
3508 mPendingIntent = pi;
3509 messenger = null;
3510 mBinder = null;
3511 mPid = getCallingPid();
3512 mUid = getCallingUid();
3513 this.isRequest = isRequest;
3514 }
3515
Robert Greenwalt9258c642014-03-26 16:47:06 -07003516 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3517 super();
3518 messenger = m;
3519 request = r;
3520 mBinder = binder;
3521 mPid = getCallingPid();
3522 mUid = getCallingUid();
3523 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003524 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003525
3526 try {
3527 mBinder.linkToDeath(this, 0);
3528 } catch (RemoteException e) {
3529 binderDied();
3530 }
3531 }
3532
3533 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003534 if (mBinder != null) {
3535 mBinder.unlinkToDeath(this, 0);
3536 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003537 }
3538
3539 public void binderDied() {
3540 log("ConnectivityService NetworkRequestInfo binderDied(" +
3541 request + ", " + mBinder + ")");
3542 releaseNetworkRequest(request);
3543 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003544
3545 public String toString() {
3546 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003547 mPid + " for " + request +
3548 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003549 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003550 }
3551
3552 @Override
3553 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003554 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003555 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003556 enforceNetworkRequestPermissions(networkCapabilities);
3557 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003558
Robert Greenwalt6078b502014-06-11 16:05:07 -07003559 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003560 throw new IllegalArgumentException("Bad timeout specified");
3561 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003562
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003563 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3564 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003565 if (DBG) log("requestNetwork for " + networkRequest);
3566 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3567 NetworkRequestInfo.REQUEST);
3568
3569 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003570 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003571 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003572 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003573 }
3574 return networkRequest;
3575 }
3576
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003577 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003578 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003579 enforceConnectivityInternalPermission();
3580 } else {
3581 enforceChangePermission();
3582 }
3583 }
3584
fenglub15e72b2015-03-20 11:29:56 -07003585 @Override
fengludb571472015-04-21 17:12:05 -07003586 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003587 enforceAccessPermission();
3588 NetworkAgentInfo nai = null;
3589 if (network == null) {
3590 return false;
3591 }
3592 synchronized (mNetworkForNetId) {
3593 nai = mNetworkForNetId.get(network.netId);
3594 }
3595 if (nai != null) {
3596 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3597 return true;
3598 }
3599 return false;
3600 }
3601
3602
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003603 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3604 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003605 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003606 final int uidRules;
3607 final int uid = Binder.getCallingUid();
3608 synchronized(mRulesLock) {
3609 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3610 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003611 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003612 // we could silently fail or we can filter the available nets to only give
3613 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003614 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003615 }
3616 }
3617 }
3618
Robert Greenwalt9258c642014-03-26 16:47:06 -07003619 @Override
3620 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3621 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003622 checkNotNull(operation, "PendingIntent cannot be null.");
3623 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3624 enforceNetworkRequestPermissions(networkCapabilities);
3625 enforceMeteredApnPolicy(networkCapabilities);
3626
3627 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3628 nextNetworkRequestId());
3629 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3630 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3631 NetworkRequestInfo.REQUEST);
3632 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3633 nri));
3634 return networkRequest;
3635 }
3636
Jeremy Joslin79294842014-12-03 17:15:28 -08003637 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3638 mHandler.sendMessageDelayed(
3639 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3640 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3641 }
3642
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003643 @Override
3644 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003645 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003646 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3647 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003648 }
3649
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003650 // In order to implement the compatibility measure for pre-M apps that call
3651 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3652 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3653 // This ensures it has permission to do so.
3654 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3655 if (nc == null) {
3656 return false;
3657 }
3658 int[] transportTypes = nc.getTransportTypes();
3659 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3660 return false;
3661 }
3662 try {
3663 mContext.enforceCallingOrSelfPermission(
3664 android.Manifest.permission.ACCESS_WIFI_STATE,
3665 "ConnectivityService");
3666 } catch (SecurityException e) {
3667 return false;
3668 }
3669 return true;
3670 }
3671
Robert Greenwalt9258c642014-03-26 16:47:06 -07003672 @Override
3673 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3674 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003675 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3676 enforceAccessPermission();
3677 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003678
3679 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003680 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003681 if (DBG) log("listenForNetwork for " + networkRequest);
3682 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3683 NetworkRequestInfo.LISTEN);
3684
3685 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3686 return networkRequest;
3687 }
3688
3689 @Override
3690 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3691 PendingIntent operation) {
3692 }
3693
3694 @Override
3695 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003696 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3697 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003698 }
3699
3700 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003701 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003702 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003703 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3704 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003705 }
3706
Robert Greenwalta67be032014-05-16 15:49:14 -07003707 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003708 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003709 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3710 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3711 }
3712
3713 @Override
3714 public void unregisterNetworkFactory(Messenger messenger) {
3715 enforceConnectivityInternalPermission();
3716 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3717 }
3718
3719 private void handleUnregisterNetworkFactory(Messenger messenger) {
3720 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3721 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003722 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003723 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003724 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003725 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003726 }
3727
Robert Greenwalt7b816022014-04-18 15:25:25 -07003728 /**
3729 * NetworkAgentInfo supporting a request by requestId.
3730 * These have already been vetted (their Capabilities satisfy the request)
3731 * and the are the highest scored network available.
3732 * the are keyed off the Requests requestId.
3733 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003734 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003735 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3736 new SparseArray<NetworkAgentInfo>();
3737
Paul Jensen31a94f42015-02-13 14:18:39 -05003738 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3739 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003740 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3741 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003742 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3743 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3744 // there may not be a strict 1:1 correlation between the two.
3745 @GuardedBy("mNetworkForNetId")
3746 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003747
Robert Greenwalt7b816022014-04-18 15:25:25 -07003748 // NetworkAgentInfo keyed off its connecting messenger
3749 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003750 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003751 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3752 new HashMap<Messenger, NetworkAgentInfo>();
3753
Paul Jensen2c311d62014-11-17 12:34:51 -05003754 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003755 private final NetworkRequest mDefaultRequest;
3756
Erik Klineda4bfa82015-04-30 12:58:40 +09003757 // Request used to optionally keep mobile data active even when higher
3758 // priority networks like Wi-Fi are active.
3759 private final NetworkRequest mDefaultMobileDataRequest;
3760
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003761 private NetworkAgentInfo getDefaultNetwork() {
3762 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3763 }
3764
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003765 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003766 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003767 }
3768
Paul Jensen31a94f42015-02-13 14:18:39 -05003769 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003770 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003771 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003772 enforceConnectivityInternalPermission();
3773
Paul Jensen2c311d62014-11-17 12:34:51 -05003774 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3775 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003776 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003777 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3778 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3779 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003780 synchronized (this) {
3781 nai.networkMonitor.systemReady = mSystemReady;
3782 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003783 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003784 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003785 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003786 }
3787
3788 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3789 if (VDBG) log("Got NetworkAgent Messenger");
3790 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003791 synchronized (mNetworkForNetId) {
3792 mNetworkForNetId.put(na.network.netId, na);
3793 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003794 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3795 NetworkInfo networkInfo = na.networkInfo;
3796 na.networkInfo = null;
3797 updateNetworkInfo(na, networkInfo);
3798 }
3799
3800 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3801 LinkProperties newLp = networkAgent.linkProperties;
3802 int netId = networkAgent.network.netId;
3803
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003804 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3805 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003806 if (networkAgent.clatd != null) {
3807 networkAgent.clatd.fixupLinkProperties(oldLp);
3808 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003809
Paul Jensen992f2522014-04-28 10:33:11 -04003810 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003811 updateMtu(newLp, oldLp);
3812 // TODO - figure out what to do for clat
3813// for (LinkProperties lp : newLp.getStackedLinks()) {
3814// updateMtu(lp, null);
3815// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003816 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003817
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003818 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3819 // In L, we used it only when the network had Internet access but provided no DNS servers.
3820 // For now, just disable it, and if disabling it doesn't break things, remove it.
3821 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3822 // NET_CAPABILITY_INTERNET);
3823 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003824 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003825 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3826
Paul Jensen3b759822014-05-13 11:44:01 -04003827 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003828 if (isDefaultNetwork(networkAgent)) {
3829 handleApplyDefaultProxy(newLp.getHttpProxy());
3830 } else {
3831 updateProxy(newLp, oldLp, networkAgent);
3832 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003833 // TODO - move this check to cover the whole function
3834 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003835 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003836 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3837 }
Paul Jensen3b759822014-05-13 11:44:01 -04003838 }
3839
Lorenzo Colitti95439462014-10-09 13:44:48 +09003840 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3841 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3842 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003843
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003844 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003845 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3846 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003847 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003848 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003849 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003850 }
Paul Jensen992f2522014-04-28 10:33:11 -04003851
3852 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3853 CompareResult<String> interfaceDiff = new CompareResult<String>();
3854 if (oldLp != null) {
3855 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3856 } else if (newLp != null) {
3857 interfaceDiff.added = newLp.getAllInterfaceNames();
3858 }
3859 for (String iface : interfaceDiff.added) {
3860 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003861 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003862 mNetd.addInterfaceToNetwork(iface, netId);
3863 } catch (Exception e) {
3864 loge("Exception adding interface: " + e);
3865 }
3866 }
3867 for (String iface : interfaceDiff.removed) {
3868 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003869 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003870 mNetd.removeInterfaceFromNetwork(iface, netId);
3871 } catch (Exception e) {
3872 loge("Exception removing interface: " + e);
3873 }
3874 }
3875 }
3876
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003877 /**
3878 * Have netd update routes from oldLp to newLp.
3879 * @return true if routes changed between oldLp and newLp
3880 */
3881 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003882 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3883 if (oldLp != null) {
3884 routeDiff = oldLp.compareAllRoutes(newLp);
3885 } else if (newLp != null) {
3886 routeDiff.added = newLp.getAllRoutes();
3887 }
3888
3889 // add routes before removing old in case it helps with continuous connectivity
3890
3891 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3892 for (RouteInfo route : routeDiff.added) {
3893 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003894 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003895 try {
3896 mNetd.addRoute(netId, route);
3897 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003898 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3899 loge("Exception in addRoute for non-gateway: " + e);
3900 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003901 }
3902 }
3903 for (RouteInfo route : routeDiff.added) {
3904 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003905 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003906 try {
3907 mNetd.addRoute(netId, route);
3908 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003909 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3910 loge("Exception in addRoute for gateway: " + e);
3911 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003912 }
3913 }
3914
3915 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003916 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003917 try {
3918 mNetd.removeRoute(netId, route);
3919 } catch (Exception e) {
3920 loge("Exception in removeRoute: " + e);
3921 }
3922 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003923 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003924 }
Erik Kline41368502015-06-17 13:19:54 +09003925
3926 // TODO: investigate moving this into LinkProperties, if only to make more accurate
3927 // the isProvisioned() checks.
3928 private static Collection<InetAddress> getLikelyReachableDnsServers(LinkProperties lp) {
3929 final ArrayList<InetAddress> dnsServers = new ArrayList<InetAddress>();
3930 final List<RouteInfo> allRoutes = lp.getAllRoutes();
3931 for (InetAddress nameserver : lp.getDnsServers()) {
3932 // If the LinkProperties doesn't include a route to the nameserver, ignore it.
3933 final RouteInfo bestRoute = RouteInfo.selectBestRoute(allRoutes, nameserver);
3934 if (bestRoute == null) {
3935 continue;
3936 }
3937
3938 // TODO: better source address evaluation for destination addresses.
3939 if (nameserver instanceof Inet4Address) {
3940 if (!lp.hasIPv4Address()) {
3941 continue;
3942 }
3943 } else if (nameserver instanceof Inet6Address) {
3944 if (nameserver.isLinkLocalAddress()) {
3945 if (((Inet6Address)nameserver).getScopeId() == 0) {
3946 // For now, just make sure link-local DNS servers have
3947 // scopedIds set, since DNS lookups will fail otherwise.
3948 // TODO: verify the scopeId matches that of lp's interface.
3949 continue;
3950 }
3951 } else {
3952 if (bestRoute.isIPv6Default() && !lp.hasGlobalIPv6Address()) {
3953 // TODO: reconsider all corner cases (disconnected ULA networks, ...).
3954 continue;
3955 }
3956 }
3957 }
3958
3959 dnsServers.add(nameserver);
3960 }
3961 return Collections.unmodifiableList(dnsServers);
3962 }
3963
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003964 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3965 boolean flush, boolean useDefaultDns) {
Erik Kline41368502015-06-17 13:19:54 +09003966 // TODO: consider comparing the getLikelyReachableDnsServers() lists, in case the
3967 // route to a DNS server has been removed (only really applicable in special cases
3968 // where there is no default route).
Robert Greenwalt7b816022014-04-18 15:25:25 -07003969 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Kline41368502015-06-17 13:19:54 +09003970 Collection<InetAddress> dnses = getLikelyReachableDnsServers(newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003971 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003972 dnses = new ArrayList();
3973 dnses.add(mDefaultDns);
3974 if (DBG) {
3975 loge("no dns provided for netId " + netId + ", so using defaults");
3976 }
3977 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003978 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003979 try {
3980 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3981 newLp.getDomains());
3982 } catch (Exception e) {
3983 loge("Exception in setDnsServersForNetwork: " + e);
3984 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003985 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3986 if (defaultNai != null && defaultNai.network.netId == netId) {
3987 setDefaultDnsSystemProperties(dnses);
3988 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003989 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003990 } else if (flush) {
3991 try {
3992 mNetd.flushNetworkDnsCache(netId);
3993 } catch (Exception e) {
3994 loge("Exception in flushNetworkDnsCache: " + e);
3995 }
3996 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003997 }
3998 }
3999
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004000 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4001 int last = 0;
4002 for (InetAddress dns : dnses) {
4003 ++last;
4004 String key = "net.dns" + last;
4005 String value = dns.getHostAddress();
4006 SystemProperties.set(key, value);
4007 }
4008 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4009 String key = "net.dns" + i;
4010 SystemProperties.set(key, "");
4011 }
4012 mNumDnsEntries = last;
4013 }
4014
Robert Greenwalt7b816022014-04-18 15:25:25 -07004015 private void updateCapabilities(NetworkAgentInfo networkAgent,
4016 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004017 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4018 synchronized (networkAgent) {
4019 networkAgent.networkCapabilities = networkCapabilities;
4020 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004021 if (networkAgent.lastValidated) {
4022 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4023 // There's no need to remove the capability if we think the network is unvalidated,
4024 // because NetworkAgents don't set the validated capability.
4025 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08004026 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004027 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004028 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004029 }
4030
Paul Jensenc8b9a742014-09-30 15:37:41 -04004031 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4032 for (int i = 0; i < nai.networkRequests.size(); i++) {
4033 NetworkRequest nr = nai.networkRequests.valueAt(i);
4034 // Don't send listening requests to factories. b/17393458
4035 if (!isRequest(nr)) continue;
4036 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4037 }
4038 }
4039
Robert Greenwalt7b816022014-04-18 15:25:25 -07004040 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4041 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004042 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004043 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4044 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004045 }
4046 }
4047
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004048 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4049 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004050 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004051 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004052 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4053 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004054 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004055 sendIntent(nri.mPendingIntent, intent);
4056 }
4057 // else not handled
4058 }
4059
4060 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4061 mPendingIntentWakeLock.acquire();
4062 try {
4063 if (DBG) log("Sending " + pendingIntent);
4064 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4065 } catch (PendingIntent.CanceledException e) {
4066 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4067 mPendingIntentWakeLock.release();
4068 releasePendingNetworkRequest(pendingIntent);
4069 }
4070 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4071 }
4072
4073 @Override
4074 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4075 String resultData, Bundle resultExtras) {
4076 if (DBG) log("Finished sending " + pendingIntent);
4077 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004078 // Release with a delay so the receiving client has an opportunity to put in its
4079 // own request.
4080 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004081 }
4082
Robert Greenwalt9258c642014-03-26 16:47:06 -07004083 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004084 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004085 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004086 Bundle bundle = new Bundle();
4087 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4088 new NetworkRequest(nri.request));
4089 Message msg = Message.obtain();
4090 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4091 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4092 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4093 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004094 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004095 case ConnectivityManager.CALLBACK_LOSING: {
4096 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4097 break;
4098 }
4099 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4100 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4101 new NetworkCapabilities(networkAgent.networkCapabilities));
4102 break;
4103 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004104 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004105 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4106 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004107 break;
4108 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004109 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004110 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004111 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004112 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004113 if (VDBG) {
4114 log("sending notification " + notifyTypeToName(notificationType) +
4115 " for " + nri.request);
4116 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004117 nri.messenger.send(msg);
4118 } catch (RemoteException e) {
4119 // may occur naturally in the race of binder death.
4120 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4121 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004122 }
4123
Paul Jensenc8b9a742014-09-30 15:37:41 -04004124 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4125 for (int i = 0; i < nai.networkRequests.size(); i++) {
4126 NetworkRequest nr = nai.networkRequests.valueAt(i);
4127 // Ignore listening requests.
4128 if (!isRequest(nr)) continue;
4129 loge("Dead network still had at least " + nr);
4130 break;
4131 }
4132 nai.asyncChannel.disconnect();
4133 }
4134
Robert Greenwalt7b816022014-04-18 15:25:25 -07004135 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4136 if (oldNetwork == null) {
4137 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4138 return;
4139 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004140 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4141 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004142 }
4143
Paul Jensen27b02b72014-07-14 12:03:33 -04004144 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004145 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004146 setupDataActivityTracking(newNetwork);
4147 try {
4148 mNetd.setDefaultNetId(newNetwork.network.netId);
4149 } catch (Exception e) {
4150 loge("Exception setting default network :" + e);
4151 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004152 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004153 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004154 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004155 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004156 }
4157
Paul Jensen2161a8e2014-09-11 11:00:39 -04004158 // Handles a network appearing or improving its score.
4159 //
4160 // - Evaluates all current NetworkRequests that can be
4161 // satisfied by newNetwork, and reassigns to newNetwork
4162 // any such requests for which newNetwork is the best.
4163 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004164 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004165 // needed. A network is needed if it is the best network for
4166 // one or more NetworkRequests, or if it is a VPN.
4167 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004168 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004169 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4170 //
4171 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4172 // networks that have no chance (i.e. even if validated)
4173 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004174 //
4175 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4176 // it does not remove NetworkRequests that other Networks could better satisfy.
4177 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4178 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4179 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004180 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004181 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004182 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004183 // torn down if unneeded.
4184 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4185 // performed to tear down unvalidated networks that have no chance (i.e. even if
4186 // validated) of becoming the highest scoring network.
4187 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4188 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004189 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004190 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004191 loge("ERROR: nascent network not validated.");
4192 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004193 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004194 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004195 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004196 if (DBG) log("rematching " + newNetwork.name());
4197 // Find and migrate to this Network any NetworkRequests for
4198 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004199 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004200 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004201 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004202 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4203 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004204 if (DBG) {
4205 log("Network " + newNetwork.name() + " was already satisfying" +
4206 " request " + nri.request.requestId + ". No change.");
4207 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004208 keep = true;
4209 continue;
4210 }
4211
4212 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004213 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004214 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004215 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004216 // This is not a request, it's a callback listener.
4217 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004218 newNetwork.addRequest(nri.request);
4219 continue;
4220 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004221
Robert Greenwalt7b816022014-04-18 15:25:25 -07004222 // next check if it's better than any current network we're using for
4223 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004224 if (VDBG) {
4225 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004226 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4227 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004228 }
4229 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004230 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004231 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004232 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004233 currentNetwork.networkRequests.remove(nri.request.requestId);
4234 currentNetwork.networkLingered.add(nri.request);
4235 affectedNetworks.add(currentNetwork);
4236 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004237 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004238 }
Paul Jensen573a0352015-01-08 10:49:34 -05004239 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004240 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004241 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004242 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004243 // Tell NetworkFactories about the new score, so they can stop
4244 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004245 // TODO - this could get expensive if we have alot of requests for this
4246 // network. Think about if there is a way to reduce this. Push
4247 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004248 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004249 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004250 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004251 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004252 }
4253 }
4254 }
4255 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004256 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004257 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004258 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004259 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4260 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4261 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004262 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004263 }
4264 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004265 if (keep) {
4266 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004267 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004268 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004269 synchronized (ConnectivityService.this) {
4270 // have a new default network, release the transition wakelock in
4271 // a second if it's held. The second pause is to allow apps
4272 // to reconnect over the new network
4273 if (mNetTransitionWakeLock.isHeld()) {
4274 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4275 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4276 mNetTransitionWakeLockSerialNumber, 0),
4277 1000);
4278 }
4279 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004280 }
4281
4282 // do this after the default net is switched, but
4283 // before LegacyTypeTracker sends legacy broadcasts
4284 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4285
4286 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004287 // Maintain the illusion: since the legacy API only
4288 // understands one network at a time, we must pretend
4289 // that the current default network disconnected before
4290 // the new one connected.
4291 if (oldDefaultNetwork != null) {
4292 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004293 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004294 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004295 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004296 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4297 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004298 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004299
4300 // Notify battery stats service about this network, both the normal
4301 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004302 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004303 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004304 final IBatteryStats bs = BatteryStatsService.getService();
4305 final int type = newNetwork.networkInfo.getType();
4306
4307 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4308 bs.noteNetworkInterfaceType(baseIface, type);
4309 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4310 final String stackedIface = stacked.getInterfaceName();
4311 bs.noteNetworkInterfaceType(stackedIface, type);
4312 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4313 }
4314 } catch (RemoteException ignored) {
4315 }
4316
Robert Greenwalt152ed372014-12-17 17:19:53 -08004317 // This has to happen after the notifyNetworkCallbacks as that tickles each
4318 // ConnectivityManager instance so that legacy requests correctly bind dns
4319 // requests to this network. The legacy users are listening for this bcast
4320 // and will generally do a dns request so they can ensureRouteToHost and if
4321 // they do that before the callbacks happen they'll use the default network.
4322 //
4323 // TODO: Is there still a race here? We send the broadcast
4324 // after sending the callback, but if the app can receive the
4325 // broadcast before the callback, it might still break.
4326 //
4327 // This *does* introduce a race where if the user uses the new api
4328 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4329 // they may get old info. Reverse this after the old startUsing api is removed.
4330 // This is on top of the multiple intent sequencing referenced in the todo above.
4331 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4332 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4333 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4334 // legacy type tracker filters out repeat adds
4335 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4336 }
4337 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004338
4339 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4340 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4341 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4342 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4343 if (newNetwork.isVPN()) {
4344 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4345 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004346 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004347 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004348 // validated (and get evaluated against peers, one losing here), or get reaped (see
4349 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4350 // network. Networks that have been up for a while and are validated should be torn
4351 // down via the lingering process so communication on that network is given time to
4352 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004353 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004354 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004355 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004356 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4357 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004358 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004359 if (DBG) log("Reaping " + nai.name());
4360 teardownUnneededNetwork(nai);
4361 }
4362 }
4363 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004364 }
4365
Paul Jensen2161a8e2014-09-11 11:00:39 -04004366 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4367 // being disconnected.
4368 // If only one Network's score or capabilities have been modified since the last time
4369 // this function was called, pass this Network in via the "changed" arugment, otherwise
4370 // pass null.
4371 // If only one Network has been changed but its NetworkCapabilities have not changed,
4372 // pass in the Network's score (from getCurrentScore()) prior to the change via
4373 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4374 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4375 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4376 // to avoid the slowness. It is not simply enough to process just "changed", for
4377 // example in the case where "changed"'s score decreases and another network should begin
4378 // satifying a NetworkRequest that "changed" currently satisfies.
4379
4380 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4381 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4382 // rematchNetworkAndRequests() handles.
4383 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004384 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4385 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004386 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004387 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4388 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4389 NascentState.NOT_JUST_VALIDATED,
4390 // Only reap the last time through the loop. Reaping before all rematching
4391 // is complete could incorrectly teardown a network that hasn't yet been
4392 // rematched.
4393 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4394 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004395 }
4396 }
4397 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004399 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004400 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004401 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004402 // For now only update icons for default connection.
4403 // TODO: Update WiFi and cellular icons separately. b/17237507
4404 if (!isDefaultNetwork(nai)) return;
4405
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004406 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004407 // Don't repeat publish.
4408 if (newInetCondition == mDefaultInetConditionPublished) return;
4409
4410 mDefaultInetConditionPublished = newInetCondition;
4411 sendInetConditionBroadcast(nai.networkInfo);
4412 }
4413
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004414 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4415 if (mLockdownTracker != null) {
4416 if (nai != null && nai.isVPN()) {
4417 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4418 } else {
4419 mLockdownTracker.onNetworkInfoChanged();
4420 }
4421 }
4422 }
4423
Robert Greenwalt7b816022014-04-18 15:25:25 -07004424 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4425 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004426 NetworkInfo oldInfo = null;
4427 synchronized (networkAgent) {
4428 oldInfo = networkAgent.networkInfo;
4429 networkAgent.networkInfo = newInfo;
4430 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004431 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004432
4433 if (oldInfo != null && oldInfo.getState() == state) {
4434 if (VDBG) log("ignoring duplicate network state non-change");
4435 return;
4436 }
4437 if (DBG) {
4438 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4439 (oldInfo == null ? "null" : oldInfo.getState()) +
4440 " to " + state);
4441 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004442
Paul Jenseneec75412014-08-04 12:21:19 -04004443 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004444 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004445 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004446 if (networkAgent.isVPN()) {
4447 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004448 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4449 (networkAgent.networkMisc == null ||
4450 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004451 } else {
4452 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4453 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004454 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004455 loge("Error creating network " + networkAgent.network.netId + ": "
4456 + e.getMessage());
4457 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004458 }
Paul Jenseneec75412014-08-04 12:21:19 -04004459 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004460 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004461 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004462
Paul Jensenca8f16a2014-05-09 12:47:55 -04004463 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004464 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004465
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004466 if (networkAgent.isVPN()) {
4467 // Temporarily disable the default proxy (not global).
4468 synchronized (mProxyLock) {
4469 if (!mDefaultProxyDisabled) {
4470 mDefaultProxyDisabled = true;
4471 if (mGlobalProxy == null && mDefaultProxy != null) {
4472 sendProxyBroadcast(null);
4473 }
4474 }
4475 }
4476 // TODO: support proxy per network.
4477 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004478
Paul Jensen2161a8e2014-09-11 11:00:39 -04004479 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004480 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4481 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004482
4483 // This has to happen after matching the requests, because callbacks are just requests.
4484 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004485 } else if (state == NetworkInfo.State.DISCONNECTED ||
4486 state == NetworkInfo.State.SUSPENDED) {
4487 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004488 if (networkAgent.isVPN()) {
4489 synchronized (mProxyLock) {
4490 if (mDefaultProxyDisabled) {
4491 mDefaultProxyDisabled = false;
4492 if (mGlobalProxy == null && mDefaultProxy != null) {
4493 sendProxyBroadcast(mDefaultProxy);
4494 }
4495 }
4496 }
4497 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004498 }
4499 }
4500
Robert Greenwaltac96c522014-06-03 16:43:57 -07004501 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4502 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004503 if (score < 0) {
4504 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4505 "). Bumping score to min of 0");
4506 score = 0;
4507 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004508
Paul Jensen2161a8e2014-09-11 11:00:39 -04004509 final int oldScore = nai.getCurrentScore();
4510 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004511
Paul Jensen57a767f2014-11-19 13:01:46 -05004512 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004513
Paul Jensenc8b9a742014-09-30 15:37:41 -04004514 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004515 }
4516
Robert Greenwalt9258c642014-03-26 16:47:06 -07004517 // notify only this one new request of the current state
4518 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4519 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4520 // TODO - read state from monitor to decide what to send.
4521// if (nai.networkMonitor.isLingering()) {
4522// notifyType = NetworkCallbacks.LOSING;
4523// } else if (nai.networkMonitor.isEvaluating()) {
4524// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4525// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004526 if (nri.mPendingIntent == null) {
4527 callCallbackForRequest(nri, nai, notifyType);
4528 } else {
4529 sendPendingIntentForRequest(nri, nai, notifyType);
4530 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004531 }
4532
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004533 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004534 // The NetworkInfo we actually send out has no bearing on the real
4535 // state of affairs. For example, if the default connection is mobile,
4536 // and a request for HIPRI has just gone away, we need to pretend that
4537 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4538 // the state to DISCONNECTED, even though the network is of type MOBILE
4539 // and is still connected.
4540 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4541 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004542 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004543 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004544 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004545 } else {
Feixiong Zhang376133f2015-06-01 18:07:58 -07004546 info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004547 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4548 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4549 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4550 if (info.isFailover()) {
4551 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4552 nai.networkInfo.setFailover(false);
4553 }
4554 if (info.getReason() != null) {
4555 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4556 }
4557 if (info.getExtraInfo() != null) {
4558 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4559 }
4560 NetworkAgentInfo newDefaultAgent = null;
4561 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4562 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4563 if (newDefaultAgent != null) {
4564 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4565 newDefaultAgent.networkInfo);
4566 } else {
4567 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4568 }
4569 }
4570 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4571 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004572 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004573 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004574 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004575 }
4576 }
4577 }
4578
Robert Greenwalt7b816022014-04-18 15:25:25 -07004579 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004580 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004581 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004582 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4583 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4584 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004585 if (nri.mPendingIntent == null) {
4586 callCallbackForRequest(nri, networkAgent, notifyType);
4587 } else {
4588 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4589 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004590 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004591 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004592
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004593 private String notifyTypeToName(int notifyType) {
4594 switch (notifyType) {
4595 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4596 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4597 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4598 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4599 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4600 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4601 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4602 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4603 }
4604 return "UNKNOWN";
4605 }
4606
Jeff Sharkey69736342014-12-08 14:50:12 -08004607 /**
4608 * Notify other system services that set of active ifaces has changed.
4609 */
4610 private void notifyIfacesChanged() {
4611 try {
4612 mStatsService.forceUpdateIfaces();
4613 } catch (Exception ignored) {
4614 }
4615 }
4616
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004617 @Override
4618 public boolean addVpnAddress(String address, int prefixLength) {
4619 throwIfLockdownEnabled();
4620 int user = UserHandle.getUserId(Binder.getCallingUid());
4621 synchronized (mVpns) {
4622 return mVpns.get(user).addAddress(address, prefixLength);
4623 }
4624 }
4625
4626 @Override
4627 public boolean removeVpnAddress(String address, int prefixLength) {
4628 throwIfLockdownEnabled();
4629 int user = UserHandle.getUserId(Binder.getCallingUid());
4630 synchronized (mVpns) {
4631 return mVpns.get(user).removeAddress(address, prefixLength);
4632 }
4633 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004634
4635 @Override
4636 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4637 throwIfLockdownEnabled();
4638 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004639 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004640 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004641 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004642 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004643 if (success) {
4644 notifyIfacesChanged();
4645 }
4646 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004647 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004648
4649 @Override
4650 public void factoryReset() {
4651 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004652
4653 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4654 return;
4655 }
4656
Robin Lee3b3dd942015-05-12 18:14:58 +01004657 final int userId = UserHandle.getCallingUserId();
4658
Stuart Scottf1fb3972015-04-02 18:00:02 -07004659 // Turn airplane mode off
4660 setAirplaneMode(false);
4661
Stuart Scotte3e314d2015-04-20 14:07:45 -07004662 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4663 // Untether
4664 for (String tether : getTetheredIfaces()) {
4665 untether(tether);
4666 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004667 }
4668
Stuart Scotte3e314d2015-04-20 14:07:45 -07004669 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4670 // Turn VPN off
4671 VpnConfig vpnConfig = getVpnConfig(userId);
4672 if (vpnConfig != null) {
4673 if (vpnConfig.legacy) {
4674 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4675 } else {
4676 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4677 // in the future without user intervention.
4678 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004679
Stuart Scotte3e314d2015-04-20 14:07:45 -07004680 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4681 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004682 }
4683 }
4684 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004685}