blob: 99c4eda62c26b7623ec32161d620c239c69606f6 [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;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700103import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700104import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700105import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700106import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800107import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700108import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700109import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700110import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700111import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700112import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700113import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400114import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900115import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700116import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400117import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700119import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800120import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700121import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700122import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700123import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700124import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700125import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700126
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700127import org.xmlpull.v1.XmlPullParser;
128import org.xmlpull.v1.XmlPullParserException;
129
130import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import java.io.FileNotFoundException;
133import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700134import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700136import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700137import java.net.InetAddress;
138import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700139import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700140import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700141import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700142import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700143import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500144import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700145import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700146import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700147import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700148import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150/**
151 * @hide
152 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800153public class ConnectivityService extends IConnectivityManager.Stub
154 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700155 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700157 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700158 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Jake Hamby786e71a2014-02-06 14:43:50 -0800160 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700161
Jeff Sharkey899223b2012-08-04 15:24:58 -0700162 // TODO: create better separation between radio types and network types
163
Robert Greenwalt42acef32009-08-12 16:08:25 -0700164 // how long to wait before switching back to a radio's default network
165 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
166 // system property that can override the above value
167 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
168 "android.telephony.apn-restore";
169
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900170 // How long to wait before putting up a "This network doesn't have an Internet connection,
171 // connect anyway?" dialog after the user selects a network that doesn't validate.
172 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
173
Jeremy Joslin79294842014-12-03 17:15:28 -0800174 // How long to delay to removal of a pending intent based request.
175 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
176 private final int mReleasePendingIntentDelayMs;
177
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800178 private Tethering mTethering;
179
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700180 private final PermissionMonitor mPermissionMonitor;
181
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700182 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700183
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700184 @GuardedBy("mVpns")
185 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700186
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700187 private boolean mLockdownEnabled;
188 private LockdownVpnTracker mLockdownTracker;
189
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700190 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
191 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192 /** Currently active network rules by UID. */
193 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700194 /** Set of ifaces that are costly. */
195 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700196
Erik Klineda4bfa82015-04-30 12:58:40 +0900197 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700199 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700200 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800202 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
204 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700205 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700207 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800208 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700209 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700210
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700211 private String mCurrentTcpBufferSizes;
212
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700213 private static final int ENABLED = 1;
214 private static final int DISABLED = 0;
215
Paul Jensenb10e37f2014-11-25 12:33:08 -0500216 // Arguments to rematchNetworkAndRequests()
217 private enum NascentState {
218 // Indicates a network was just validated for the first time. If the network is found to
219 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
220 JUST_VALIDATED,
221 // Indicates a network was not validated for the first time immediately prior to this call.
222 NOT_JUST_VALIDATED
223 };
224 private enum ReapUnvalidatedNetworks {
225 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
226 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
227 // known that there may be unvalidated networks that could potentially be reaped, and when
228 // all networks have been rematched against all NetworkRequests.
229 REAP,
230 // Don't reap unvalidated networks. This should be passed when it's known that there are
231 // no unvalidated networks that could potentially be reaped, and when some networks have
232 // not yet been rematched against all NetworkRequests.
233 DONT_REAP
234 };
235
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700236 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237 * used internally to change our mobile data enabled flag
238 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700239 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700240
241 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700242 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700243 * from one net to another. Clear happens when we get a new
244 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
245 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700246 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700247 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700248
Robert Greenwalt434203a2010-10-11 16:00:27 -0700249 /**
250 * used internally to reload global proxy settings
251 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700252 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700253
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700254 /**
Wink Saville628b0852011-08-04 15:01:58 -0700255 * used internally to send a sticky broadcast delayed.
256 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700257 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700258
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700259 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400260 * PAC manager has received new port.
261 */
262 private static final int EVENT_PROXY_HAS_CHANGED = 16;
263
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 /**
265 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700266 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700267 */
268 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
269
Robert Greenwalt7b816022014-04-18 15:25:25 -0700270 /**
271 * used internally when registering NetworkAgents
272 * obj = Messenger
273 */
274 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
275
Robert Greenwalt9258c642014-03-26 16:47:06 -0700276 /**
277 * used to add a network request
278 * includes a NetworkRequestInfo
279 */
280 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
281
282 /**
283 * indicates a timeout period is over - check if we had a network yet or not
284 * and if not, call the timeout calback (but leave the request live until they
285 * cancel it.
286 * includes a NetworkRequestInfo
287 */
288 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
289
290 /**
291 * used to add a network listener - no request
292 * includes a NetworkRequestInfo
293 */
294 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
295
296 /**
297 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400298 * arg1 = UID of caller
299 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700300 */
301 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
302
Robert Greenwalta67be032014-05-16 15:49:14 -0700303 /**
304 * used internally when registering NetworkFactories
305 * obj = Messenger
306 */
307 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
308
Robert Greenwalt27711812014-06-25 16:45:57 -0700309 /**
310 * used internally to expire a wakelock when transitioning
311 * from one net to another. Expire happens when we fail to find
312 * a new network (typically after 1 minute) -
313 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
314 * a replacement network.
315 */
316 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
317
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700318 /**
319 * Used internally to indicate the system is ready.
320 */
321 private static final int EVENT_SYSTEM_READY = 25;
322
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800323 /**
324 * used to add a network request with a pending intent
325 * includes a NetworkRequestInfo
326 */
327 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
328
329 /**
330 * used to remove a pending intent and its associated network request.
331 * arg1 = UID of caller
332 * obj = PendingIntent
333 */
334 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
335
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900336 /**
337 * used to specify whether a network should be used even if unvalidated.
338 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
339 * arg2 = whether to remember this choice in the future (1 or 0)
340 * obj = network
341 */
342 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
343
344 /**
345 * used to ask the user to confirm a connection to an unvalidated network.
346 * obj = network
347 */
348 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700349
Erik Klineda4bfa82015-04-30 12:58:40 +0900350 /**
351 * used internally to (re)configure mobile data always-on settings.
352 */
353 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
354
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700355 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700356 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700357 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700358 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700359
Mike Lockwood0f79b542009-08-14 14:18:49 -0400360 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800361 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400362
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700363 private PowerManager.WakeLock mNetTransitionWakeLock;
364 private String mNetTransitionWakeLockCausedBy = "";
365 private int mNetTransitionWakeLockSerialNumber;
366 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800367 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700368
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700369 private InetAddress mDefaultDns;
370
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700371 // used in DBG mode to track inet condition reports
372 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
373 private ArrayList mInetLog;
374
Robert Greenwalt434203a2010-10-11 16:00:27 -0700375 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400376 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700377 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700378 private boolean mDefaultProxyDisabled = false;
379
Robert Greenwalt434203a2010-10-11 16:00:27 -0700380 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400381 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700382
Jason Monk602b2322013-07-03 17:04:33 -0400383 private PacManager mPacManager = null;
384
Erik Klineda4bfa82015-04-30 12:58:40 +0900385 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700386
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400387 private UserManager mUserManager;
388
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700389 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700390 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700391
Robert Greenwalt50393202011-06-21 17:26:14 -0700392 // the set of network types that can only be enabled by system/sig apps
393 List mProtectedNetworks;
394
John Spurlockbf991a82013-06-24 14:20:23 -0400395 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700396
Wink Savilleab9321d2013-06-29 21:10:57 -0700397 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400398
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700399 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
400 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700401 private final static int MAX_NET_ID = 65535;
402 private int mNextNetId = MIN_NET_ID;
403
Robert Greenwalt34524f02014-05-18 16:22:10 -0700404 // sequence number of NetworkRequests
405 private int mNextNetworkRequestId = 1;
406
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700407 /**
408 * Implements support for the legacy "one network per network type" model.
409 *
410 * We used to have a static array of NetworkStateTrackers, one for each
411 * network type, but that doesn't work any more now that we can have,
412 * for example, more that one wifi network. This class stores all the
413 * NetworkAgentInfo objects that support a given type, but the legacy
414 * API will only see the first one.
415 *
416 * It serves two main purposes:
417 *
418 * 1. Provide information about "the network for a given type" (since this
419 * API only supports one).
420 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
421 * the first network for a given type changes, or if the default network
422 * changes.
423 */
424 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900425
426 private static final boolean DBG = true;
427 private static final boolean VDBG = false;
428 private static final String TAG = "CSLegacyTypeTracker";
429
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700430 /**
431 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
432 * Each list holds references to all NetworkAgentInfos that are used to
433 * satisfy requests for that network type.
434 *
435 * This array is built out at startup such that an unsupported network
436 * doesn't get an ArrayList instance, making this a tristate:
437 * unsupported, supported but not active and active.
438 *
439 * The actual lists are populated when we scan the network types that
440 * are supported on this device.
441 */
442 private ArrayList<NetworkAgentInfo> mTypeLists[];
443
444 public LegacyTypeTracker() {
445 mTypeLists = (ArrayList<NetworkAgentInfo>[])
446 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
447 }
448
449 public void addSupportedType(int type) {
450 if (mTypeLists[type] != null) {
451 throw new IllegalStateException(
452 "legacy list for type " + type + "already initialized");
453 }
454 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
455 }
456
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700457 public boolean isTypeSupported(int type) {
458 return isNetworkTypeValid(type) && mTypeLists[type] != null;
459 }
460
461 public NetworkAgentInfo getNetworkForType(int type) {
462 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
463 return mTypeLists[type].get(0);
464 } else {
465 return null;
466 }
467 }
468
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900469 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
470 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900471 if (DBG) {
472 log("Sending " + (connected ? "connected" : "disconnected") +
473 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900474 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900475 }
476 }
477
478 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700479 public void add(int type, NetworkAgentInfo nai) {
480 if (!isTypeSupported(type)) {
481 return; // Invalid network type.
482 }
483 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
484
485 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
486 if (list.contains(nai)) {
487 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
488 return;
489 }
490
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900491 list.add(nai);
492
493 // 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 +0900494 final boolean isDefaultNetwork = isDefaultNetwork(nai);
495 if (list.size() == 1 || isDefaultNetwork) {
496 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700497 sendLegacyNetworkBroadcast(nai, true, type);
498 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700499 }
500
Lorenzo Colittia793a672014-07-31 23:20:17 +0900501 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900502 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900503 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
504 if (list == null || list.isEmpty()) {
505 return;
506 }
507
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900508 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900509
510 if (!list.remove(nai)) {
511 return;
512 }
513
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900514 if (wasFirstNetwork || wasDefault) {
515 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900516 sendLegacyNetworkBroadcast(nai, false, type);
517 }
518
519 if (!list.isEmpty() && wasFirstNetwork) {
520 if (DBG) log("Other network available for type " + type +
521 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900522 final NetworkAgentInfo replacement = list.get(0);
523 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
524 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525 }
526 }
527
528 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900529 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
530 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700531 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900532 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700533 }
534 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700535
Lorenzo Colittia793a672014-07-31 23:20:17 +0900536 private String naiToString(NetworkAgentInfo nai) {
537 String name = (nai != null) ? nai.name() : "null";
538 String state = (nai.networkInfo != null) ?
539 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
540 "???/???";
541 return name + " " + state;
542 }
543
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700544 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900545 pw.println("mLegacyTypeTracker:");
546 pw.increaseIndent();
547 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700548 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900549 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700550 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900551 pw.println();
552 pw.println("Current state:");
553 pw.increaseIndent();
554 for (int type = 0; type < mTypeLists.length; type++) {
555 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
556 for (NetworkAgentInfo nai : mTypeLists[type]) {
557 pw.println(type + " " + naiToString(nai));
558 }
559 }
560 pw.decreaseIndent();
561 pw.decreaseIndent();
562 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700563 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900564
565 // This class needs its own log method because it has a different TAG.
566 private void log(String s) {
567 Slog.d(TAG, s);
568 }
569
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700570 }
571 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
572
Jeff Sharkey899223b2012-08-04 15:24:58 -0700573 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700574 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800575 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800576
Erik Klineda4bfa82015-04-30 12:58:40 +0900577 mDefaultRequest = createInternetRequestForTransport(-1);
578 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
579 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
580
581 mDefaultMobileDataRequest = createInternetRequestForTransport(
582 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700583
Wink Savillebb08caf2010-09-02 19:23:52 -0700584 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
585 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700586 mHandler = new InternalHandler(handlerThread.getLooper());
587 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700588
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800589 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800590 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
591 String id = Settings.Secure.getString(context.getContentResolver(),
592 Settings.Secure.ANDROID_ID);
593 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700594 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800595 SystemProperties.set("net.hostname", name);
596 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800597 }
598
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700599 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700600 String dns = Settings.Global.getString(context.getContentResolver(),
601 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700602 if (dns == null || dns.length() == 0) {
603 dns = context.getResources().getString(
604 com.android.internal.R.string.config_default_dns_server);
605 }
606 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800607 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
608 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800609 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700610 }
611
Jeremy Joslin79294842014-12-03 17:15:28 -0800612 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
613 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
614
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700615 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700616 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800617 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700618 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700619 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700620 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700621
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700622 try {
623 mPolicyManager.registerListener(mPolicyListener);
624 } catch (RemoteException e) {
625 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700626 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700627 }
628
629 final PowerManager powerManager = (PowerManager) context.getSystemService(
630 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700631 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
632 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
633 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800634 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700635
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700636 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700637
Wink Saville51f456f2013-04-23 14:26:51 -0700638 // TODO: What is the "correct" way to do determine if this is a wifi only device?
639 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
640 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700641 String[] naStrings = context.getResources().getStringArray(
642 com.android.internal.R.array.networkAttributes);
643 for (String naString : naStrings) {
644 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700645 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700646 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700647 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800648 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700649 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700650 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700651 }
Wink Saville51f456f2013-04-23 14:26:51 -0700652 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
653 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
654 n.type);
655 continue;
656 }
Wink Saville975c8482011-04-07 14:23:45 -0700657 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800658 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700659 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700660 continue;
661 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700662 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700663
Wink Saville975c8482011-04-07 14:23:45 -0700664 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700665 mNetworksDefined++;
666 } catch(Exception e) {
667 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700668 }
669 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700670
671 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
672 if (mNetConfigs[TYPE_VPN] == null) {
673 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
674 // don't need to add TYPE_VPN to mNetConfigs.
675 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
676 mNetworksDefined++; // used only in the log() statement below.
677 }
678
Wink Saville5e56bc52013-07-29 15:00:57 -0700679 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700680
Robert Greenwalt50393202011-06-21 17:26:14 -0700681 mProtectedNetworks = new ArrayList<Integer>();
682 int[] protectedNetworks = context.getResources().getIntArray(
683 com.android.internal.R.array.config_protectedNetworks);
684 for (int p : protectedNetworks) {
685 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
686 mProtectedNetworks.add(p);
687 } else {
688 if (DBG) loge("Ignoring protectedNetwork " + p);
689 }
690 }
691
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700692 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
693 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700694
Robert Greenwaltfab501672014-07-23 11:44:01 -0700695 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800696
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700697 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
698
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700699 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700700 IntentFilter intentFilter = new IntentFilter();
701 intentFilter.addAction(Intent.ACTION_USER_STARTING);
702 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
703 mContext.registerReceiverAsUser(
704 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900705
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700706 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700707 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700708 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700709 } catch (RemoteException e) {
710 loge("Error registering observer :" + e);
711 }
712
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700713 if (DBG) {
714 mInetLog = new ArrayList();
715 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700716
Erik Klineda4bfa82015-04-30 12:58:40 +0900717 mSettingsObserver = new SettingsObserver(mContext, mHandler);
718 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800719
John Spurlockbf991a82013-06-24 14:20:23 -0400720 mDataConnectionStats = new DataConnectionStats(mContext);
721 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400722
Jason Monkdecd2952013-10-10 14:02:51 -0400723 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700724
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400725 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800726 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700727
Erik Klineda4bfa82015-04-30 12:58:40 +0900728 private NetworkRequest createInternetRequestForTransport(int transportType) {
729 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900730 netCap.addCapability(NET_CAPABILITY_INTERNET);
731 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900732 if (transportType > -1) {
733 netCap.addTransportType(transportType);
734 }
735 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
736 }
737
738 private void handleMobileDataAlwaysOn() {
739 final boolean enable = (Settings.Global.getInt(
740 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
741 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
742 if (enable == isEnabled) {
743 return; // Nothing to do.
744 }
745
746 if (enable) {
747 handleRegisterNetworkRequest(new NetworkRequestInfo(
748 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
749 } else {
750 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
751 }
752 }
753
754 private void registerSettingsCallbacks() {
755 // Watch for global HTTP proxy changes.
756 mSettingsObserver.observe(
757 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
758 EVENT_APPLY_GLOBAL_HTTP_PROXY);
759
760 // Watch for whether or not to keep mobile data always on.
761 mSettingsObserver.observe(
762 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
763 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
764 }
765
Robert Greenwalt34524f02014-05-18 16:22:10 -0700766 private synchronized int nextNetworkRequestId() {
767 return mNextNetworkRequestId++;
768 }
769
Paul Jensen31a94f42015-02-13 14:18:39 -0500770 private int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400771 synchronized (mNetworkForNetId) {
772 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
773 int netId = mNextNetId;
774 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
775 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500776 if (!mNetIdInUse.get(netId)) {
777 mNetIdInUse.put(netId, true);
778 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400779 }
780 }
781 }
782 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700783 }
784
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800785 private NetworkState getFilteredNetworkState(int networkType, int uid) {
786 NetworkInfo info = null;
787 LinkProperties lp = null;
788 NetworkCapabilities nc = null;
789 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800790 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800791
792 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
793 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
794 if (nai != null) {
795 synchronized (nai) {
796 info = new NetworkInfo(nai.networkInfo);
797 lp = new LinkProperties(nai.linkProperties);
798 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400799 // Network objects are outwardly immutable so there is no point to duplicating.
800 // Duplicating also precludes sharing socket factories and connection pools.
801 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800802 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800803 }
804 info.setType(networkType);
805 } else {
806 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
807 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
808 info.setIsAvailable(true);
809 lp = new LinkProperties();
810 nc = new NetworkCapabilities();
811 network = null;
812 }
813 info = getFilteredNetworkInfo(info, lp, uid);
814 }
815
Jeff Sharkey32566012014-12-02 18:30:14 -0800816 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400817 }
818
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800819 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
820 if (network == null) {
821 return null;
822 }
823 synchronized (mNetworkForNetId) {
824 return mNetworkForNetId.get(network.netId);
825 }
826 };
827
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900828 private Network[] getVpnUnderlyingNetworks(int uid) {
829 if (!mLockdownEnabled) {
830 int user = UserHandle.getUserId(uid);
831 synchronized (mVpns) {
832 Vpn vpn = mVpns.get(user);
833 if (vpn != null && vpn.appliesToUid(uid)) {
834 return vpn.getUnderlyingNetworks();
835 }
836 }
837 }
838 return null;
839 }
840
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800841 private NetworkState getUnfilteredActiveNetworkState(int uid) {
842 NetworkInfo info = null;
843 LinkProperties lp = null;
844 NetworkCapabilities nc = null;
845 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800846 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847
848 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800849
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900850 final Network[] networks = getVpnUnderlyingNetworks(uid);
851 if (networks != null) {
852 // getUnderlyingNetworks() returns:
853 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
854 // empty array => the VPN explicitly said "no default network".
855 // non-empty array => the VPN specified one or more default networks; we use the
856 // first one.
857 if (networks.length > 0) {
858 nai = getNetworkAgentInfoForNetwork(networks[0]);
859 } else {
860 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800861 }
862 }
863
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800864 if (nai != null) {
865 synchronized (nai) {
866 info = new NetworkInfo(nai.networkInfo);
867 lp = new LinkProperties(nai.linkProperties);
868 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400869 // Network objects are outwardly immutable so there is no point to duplicating.
870 // Duplicating also precludes sharing socket factories and connection pools.
871 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800872 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800873 }
874 }
875
Jeff Sharkey32566012014-12-02 18:30:14 -0800876 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400877 }
878
879 /**
880 * Check if UID should be blocked from using the network with the given LinkProperties.
881 */
882 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700883 final boolean networkCostly;
884 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700885
Robert Greenwalt12e67352014-05-13 21:41:06 -0700886 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700887 synchronized (mRulesLock) {
888 networkCostly = mMeteredIfaces.contains(iface);
889 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700890 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700891
Amith Yamasani15e472352015-04-24 19:06:07 -0700892 if ((uidRules & RULE_REJECT_ALL) != 0
893 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700894 return true;
895 }
896
897 // no restrictive rules; network is visible
898 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700899 }
900
901 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700902 * Return a filtered {@link NetworkInfo}, potentially marked
903 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800904 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700905 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800906 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
907 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400908 // network is blocked; clone and override state
909 info = new NetworkInfo(info);
910 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900911 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900912 log("returning Blocked NetworkInfo for ifname=" +
913 lp.getInterfaceName() + ", uid=" + uid);
914 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700915 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800916 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700917 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900918 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700919 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700920 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700921 }
922
923 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 * Return NetworkInfo for the active (i.e., connected) network interface.
925 * It is assumed that at most one network is active at a time. If more
926 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700927 * @return the info for the active network, or {@code null} if none is
928 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700930 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800931 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700932 enforceAccessPermission();
933 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 NetworkState state = getUnfilteredActiveNetworkState(uid);
935 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800936 }
937
Paul Jensen31a94f42015-02-13 14:18:39 -0500938 @Override
939 public Network getActiveNetwork() {
940 enforceAccessPermission();
941 final int uid = Binder.getCallingUid();
942 final int user = UserHandle.getUserId(uid);
943 int vpnNetId = NETID_UNSET;
944 synchronized (mVpns) {
945 final Vpn vpn = mVpns.get(user);
946 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
947 }
948 NetworkAgentInfo nai;
949 if (vpnNetId != NETID_UNSET) {
950 synchronized (mNetworkForNetId) {
951 nai = mNetworkForNetId.get(vpnNetId);
952 }
953 if (nai != null) return nai.network;
954 }
955 nai = getDefaultNetwork();
956 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
957 return nai != null ? nai.network : null;
958 }
959
Wink Saville948282b2013-08-29 08:55:16 -0700960 /**
961 * Find the first Provisioning network.
962 *
963 * @return NetworkInfo or null if none.
964 */
965 private NetworkInfo getProvisioningNetworkInfo() {
966 enforceAccessPermission();
967
968 // Find the first Provisioning Network
969 NetworkInfo provNi = null;
970 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700971 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700972 provNi = ni;
973 break;
974 }
975 }
976 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
977 return provNi;
978 }
979
980 /**
981 * Find the first Provisioning network or the ActiveDefaultNetwork
982 * if there is no Provisioning network
983 *
984 * @return NetworkInfo or null if none.
985 */
986 @Override
987 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
988 enforceAccessPermission();
989
990 NetworkInfo provNi = getProvisioningNetworkInfo();
991 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800992 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700993 }
994 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
995 return provNi;
996 }
997
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700998 public NetworkInfo getActiveNetworkInfoUnfiltered() {
999 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001000 final int uid = Binder.getCallingUid();
1001 NetworkState state = getUnfilteredActiveNetworkState(uid);
1002 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001003 }
1004
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001005 @Override
1006 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1007 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001008 NetworkState state = getUnfilteredActiveNetworkState(uid);
1009 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001010 }
1011
1012 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001013 public NetworkInfo getNetworkInfo(int networkType) {
1014 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001015 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001016 if (getVpnUnderlyingNetworks(uid) != null) {
1017 // A VPN is active, so we may need to return one of its underlying networks. This
1018 // information is not available in LegacyTypeTracker, so we have to get it from
1019 // getUnfilteredActiveNetworkState.
1020 NetworkState state = getUnfilteredActiveNetworkState(uid);
1021 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1022 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1023 }
1024 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 NetworkState state = getFilteredNetworkState(networkType, uid);
1026 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001027 }
1028
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001029 @Override
1030 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1031 enforceAccessPermission();
1032 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001033 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001034 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1035 if (nai != null) {
1036 synchronized (nai) {
1037 info = new NetworkInfo(nai.networkInfo);
1038 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001039 }
1040 }
1041 return info;
1042 }
1043
1044 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 public NetworkInfo[] getAllNetworkInfo() {
1046 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001047 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001048 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1049 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001050 NetworkInfo info = getNetworkInfo(networkType);
1051 if (info != null) {
1052 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001053 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001054 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001055 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001056 }
1057
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001058 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001059 public Network getNetworkForType(int networkType) {
1060 enforceAccessPermission();
1061 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001062 NetworkState state = getFilteredNetworkState(networkType, uid);
1063 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1064 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001065 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001066 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001067 }
1068
1069 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001070 public Network[] getAllNetworks() {
1071 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001072 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001073 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001074 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001075 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001076 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001077 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001078 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001079 }
1080
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001081 @Override
1082 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1083 // The basic principle is: if an app's traffic could possibly go over a
1084 // network, without the app doing anything multinetwork-specific,
1085 // (hence, by "default"), then include that network's capabilities in
1086 // the array.
1087 //
1088 // In the normal case, app traffic only goes over the system's default
1089 // network connection, so that's the only network returned.
1090 //
1091 // With a VPN in force, some app traffic may go into the VPN, and thus
1092 // over whatever underlying networks the VPN specifies, while other app
1093 // traffic may go over the system default network (e.g.: a split-tunnel
1094 // VPN, or an app disallowed by the VPN), so the set of networks
1095 // returned includes the VPN's underlying networks and the system
1096 // default.
1097 enforceAccessPermission();
1098
1099 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1100
1101 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001102 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001103 if (nc != null) {
1104 result.put(nai.network, nc);
1105 }
1106
1107 if (!mLockdownEnabled) {
1108 synchronized (mVpns) {
1109 Vpn vpn = mVpns.get(userId);
1110 if (vpn != null) {
1111 Network[] networks = vpn.getUnderlyingNetworks();
1112 if (networks != null) {
1113 for (Network network : networks) {
1114 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001115 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001116 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001117 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001118 }
1119 }
1120 }
1121 }
1122 }
1123 }
1124
1125 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1126 out = result.values().toArray(out);
1127 return out;
1128 }
1129
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001130 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001131 public boolean isNetworkSupported(int networkType) {
1132 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001133 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001134 }
1135
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001136 /**
1137 * Return LinkProperties for the active (i.e., connected) default
1138 * network interface. It is assumed that at most one default network
1139 * is active at a time. If more than one is active, it is indeterminate
1140 * which will be returned.
1141 * @return the ip properties for the active network, or {@code null} if
1142 * none is active
1143 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001144 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001145 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001146 enforceAccessPermission();
1147 final int uid = Binder.getCallingUid();
1148 NetworkState state = getUnfilteredActiveNetworkState(uid);
1149 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001150 }
1151
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001152 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001153 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001154 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1156 if (nai != null) {
1157 synchronized (nai) {
1158 return new LinkProperties(nai.linkProperties);
1159 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001160 }
1161 return null;
1162 }
1163
Robert Greenwalt12e67352014-05-13 21:41:06 -07001164 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001165 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001166 public LinkProperties getLinkProperties(Network network) {
1167 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001168 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001169 if (nai != null) {
1170 synchronized (nai) {
1171 return new LinkProperties(nai.linkProperties);
1172 }
1173 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001174 return null;
1175 }
1176
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001177 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001178 if (nai != null) {
1179 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001180 if (nai.networkCapabilities != null) {
1181 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001182 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001183 }
1184 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001185 return null;
1186 }
1187
1188 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001189 public NetworkCapabilities getNetworkCapabilities(Network network) {
1190 enforceAccessPermission();
1191 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1192 }
1193
1194 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001195 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001196 // Require internal since we're handing out IMSI details
1197 enforceConnectivityInternalPermission();
1198
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001199 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001200 for (Network network : getAllNetworks()) {
1201 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1202 if (nai != null) {
1203 synchronized (nai) {
1204 final String subscriberId = (nai.networkMisc != null)
1205 ? nai.networkMisc.subscriberId : null;
1206 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1207 nai.networkCapabilities, network, subscriberId, null));
1208 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001209 }
1210 }
1211 return result.toArray(new NetworkState[result.size()]);
1212 }
1213
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001214 @Override
1215 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1216 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001217 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001218 final long token = Binder.clearCallingIdentity();
1219 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001220 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1221 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001222 try {
1223 return mPolicyManager.getNetworkQuotaInfo(state);
1224 } catch (RemoteException e) {
1225 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001226 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001227 return null;
1228 } finally {
1229 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001230 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001231 }
1232
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001233 @Override
1234 public boolean isActiveNetworkMetered() {
1235 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001237 final long token = Binder.clearCallingIdentity();
1238 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001239 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001240 } finally {
1241 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001242 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001243 }
1244
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001245 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1246 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1247 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001248 try {
1249 return mPolicyManager.isNetworkMetered(state);
1250 } catch (RemoteException e) {
1251 }
1252 }
1253 return false;
1254 }
1255
Jeff Sharkey216c1812012-08-05 14:29:23 -07001256 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1257 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001258 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001259 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001260 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001261 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001262 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001263
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001264 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 * Ensure that a network route exists to deliver traffic to the specified
1266 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001267 * @param networkType the type of the network over which traffic to the
1268 * specified host is to be routed
1269 * @param hostAddress the IP address of the host to which the route is
1270 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001271 * @return {@code true} on success, {@code false} on failure
1272 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001273 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001274 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001275 if (mProtectedNetworks.contains(networkType)) {
1276 enforceConnectivityInternalPermission();
1277 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001278
Chad Brubakerc0234532014-02-14 13:24:29 -08001279 InetAddress addr;
1280 try {
1281 addr = InetAddress.getByAddress(hostAddress);
1282 } catch (UnknownHostException e) {
1283 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1284 return false;
1285 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001286
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001287 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001288 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001289 return false;
1290 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001291
1292 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1293 if (nai == null) {
1294 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1295 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1296 } else {
1297 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1298 }
1299 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001300 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001301
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001302 DetailedState netState;
1303 synchronized (nai) {
1304 netState = nai.networkInfo.getDetailedState();
1305 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001306
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001307 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001308 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001309 log("requestRouteToHostAddress on down network "
1310 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001311 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001312 }
1313 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001314 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001315
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001316 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001317 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001318 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001319 LinkProperties lp;
1320 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001321 synchronized (nai) {
1322 lp = nai.linkProperties;
1323 netId = nai.network.netId;
1324 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001325 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001326 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1327 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001328 } finally {
1329 Binder.restoreCallingIdentity(token);
1330 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001331 }
1332
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001333 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001334 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001335 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001336 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001337 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001338 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001339 if (bestRoute.getGateway().equals(addr)) {
1340 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001341 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001342 } else {
1343 // if we will connect to this through another route, add a direct route
1344 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001345 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001346 }
1347 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001348 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001349 try {
1350 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1351 } catch (Exception e) {
1352 // never crash - catch them all
1353 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001354 return false;
1355 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001356 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001357 }
1358
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001359 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1360 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001361 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001362 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001363 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001364 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001365 }
1366
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001367 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001368 // skip update when we've already applied rules
1369 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1370 if (oldRules == uidRules) return;
1371
1372 mUidRules.put(uid, uidRules);
1373 }
1374
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 // TODO: notify UID when it has requested targeted updates
1376 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001377
1378 @Override
1379 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001380 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001381 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001382 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001383 }
1384
1385 synchronized (mRulesLock) {
1386 mMeteredIfaces.clear();
1387 for (String iface : meteredIfaces) {
1388 mMeteredIfaces.add(iface);
1389 }
1390 }
1391 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001392
1393 @Override
1394 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1395 // caller is NPMS, since we only register with them
1396 if (LOGD_RULES) {
1397 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1398 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001399 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001400 };
1401
Robin Lee3b3dd942015-05-12 18:14:58 +01001402 /**
1403 * Require that the caller is either in the same user or has appropriate permission to interact
1404 * across users.
1405 *
1406 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1407 */
1408 private void enforceCrossUserPermission(int userId) {
1409 if (userId == UserHandle.getCallingUserId()) {
1410 // Not a cross-user call.
1411 return;
1412 }
1413 mContext.enforceCallingOrSelfPermission(
1414 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1415 "ConnectivityService");
1416 }
1417
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001418 private void enforceInternetPermission() {
1419 mContext.enforceCallingOrSelfPermission(
1420 android.Manifest.permission.INTERNET,
1421 "ConnectivityService");
1422 }
1423
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001424 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001425 mContext.enforceCallingOrSelfPermission(
1426 android.Manifest.permission.ACCESS_NETWORK_STATE,
1427 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001428 }
1429
1430 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001431 mContext.enforceCallingOrSelfPermission(
1432 android.Manifest.permission.CHANGE_NETWORK_STATE,
1433 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001434 }
1435
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001436 private void enforceTetherAccessPermission() {
1437 mContext.enforceCallingOrSelfPermission(
1438 android.Manifest.permission.ACCESS_NETWORK_STATE,
1439 "ConnectivityService");
1440 }
1441
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001442 private void enforceConnectivityInternalPermission() {
1443 mContext.enforceCallingOrSelfPermission(
1444 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1445 "ConnectivityService");
1446 }
1447
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001448 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001449 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001450 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001451 }
1452
1453 private void sendInetConditionBroadcast(NetworkInfo info) {
1454 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1455 }
1456
Wink Saville628b0852011-08-04 15:01:58 -07001457 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001458 if (mLockdownTracker != null) {
1459 info = mLockdownTracker.augmentNetworkInfo(info);
1460 }
1461
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001462 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001463 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001464 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001465 if (info.isFailover()) {
1466 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1467 info.setFailover(false);
1468 }
1469 if (info.getReason() != null) {
1470 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1471 }
1472 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001473 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1474 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001475 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001476 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001477 return intent;
1478 }
1479
1480 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1481 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1482 }
1483
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001484 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001485 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1486 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1487 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001488 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001489 final long ident = Binder.clearCallingIdentity();
1490 try {
1491 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1492 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1493 } finally {
1494 Binder.restoreCallingIdentity(ident);
1495 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001496 }
1497
Mike Lockwood0f79b542009-08-14 14:18:49 -04001498 private void sendStickyBroadcast(Intent intent) {
1499 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001500 if (!mSystemReady) {
1501 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001502 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001503 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001504 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001505 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001506 }
1507
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001508 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001509 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1510 final IBatteryStats bs = BatteryStatsService.getService();
1511 try {
1512 NetworkInfo ni = intent.getParcelableExtra(
1513 ConnectivityManager.EXTRA_NETWORK_INFO);
1514 bs.noteConnectivityChanged(intent.getIntExtra(
1515 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1516 ni != null ? ni.getState().toString() : "?");
1517 } catch (RemoteException e) {
1518 }
1519 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001520 try {
1521 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1522 } finally {
1523 Binder.restoreCallingIdentity(ident);
1524 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001525 }
1526 }
1527
1528 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001529 loadGlobalProxy();
1530
Mike Lockwood0f79b542009-08-14 14:18:49 -04001531 synchronized(this) {
1532 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001533 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001534 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001535 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001536 }
1537 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001538 // load the global proxy at startup
1539 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001540
1541 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1542 // for user to unlock device.
1543 if (!updateLockdownVpn()) {
1544 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1545 mContext.registerReceiver(mUserPresentReceiver, filter);
1546 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001547
Erik Klineda4bfa82015-04-30 12:58:40 +09001548 // Configure whether mobile data is always on.
1549 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1550
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001551 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001552
1553 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001554 }
1555
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001556 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1557 @Override
1558 public void onReceive(Context context, Intent intent) {
1559 // Try creating lockdown tracker, since user present usually means
1560 // unlocked keystore.
1561 if (updateLockdownVpn()) {
1562 mContext.unregisterReceiver(this);
1563 }
1564 }
1565 };
1566
Wink Savilled747cbc2013-08-07 16:22:47 -07001567 /** @hide */
1568 @Override
1569 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1570 enforceConnectivityInternalPermission();
1571 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001572// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001573 }
1574
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001575 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001576 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001577 *
1578 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001579 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001580 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001581 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1582 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001583
1584 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001585 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001586
Robert Greenwalt7b816022014-04-18 15:25:25 -07001587 if (networkAgent.networkCapabilities.hasTransport(
1588 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001589 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1590 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001591 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001592 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001593 } else if (networkAgent.networkCapabilities.hasTransport(
1594 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001595 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1596 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001597 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001598 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001599 } else {
1600 // do not track any other networks
1601 timeout = 0;
1602 }
1603
Robert Greenwalt7b816022014-04-18 15:25:25 -07001604 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001605 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001606 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001607 } catch (Exception e) {
1608 // You shall not crash!
1609 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001610 }
1611 }
1612 }
1613
1614 /**
1615 * Remove data activity tracking when network disconnects.
1616 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001617 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1618 final String iface = networkAgent.linkProperties.getInterfaceName();
1619 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001620
Robert Greenwalt7b816022014-04-18 15:25:25 -07001621 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1622 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001623 try {
1624 // the call fails silently if no idletimer setup for this interface
1625 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001626 } catch (Exception e) {
1627 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001628 }
1629 }
1630 }
1631
1632 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001633 * Reads the network specific MTU size from reources.
1634 * and set it on it's iface.
1635 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001636 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1637 final String iface = newLp.getInterfaceName();
1638 final int mtu = newLp.getMtu();
1639 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1640 if (VDBG) log("identical MTU - not setting");
1641 return;
1642 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001643
Robert Greenwalt43074032014-08-15 17:53:05 -07001644 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001645 loge("Unexpected mtu value: " + mtu + ", " + iface);
1646 return;
1647 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001648
w1997615afd812014-08-05 15:18:11 -07001649 // Cannot set MTU without interface name
1650 if (TextUtils.isEmpty(iface)) {
1651 loge("Setting MTU size with null iface.");
1652 return;
1653 }
1654
Robert Greenwalt7b816022014-04-18 15:25:25 -07001655 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001656 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001657 mNetd.setMtu(iface, mtu);
1658 } catch (Exception e) {
1659 Slog.e(TAG, "exception in setMtu()" + e);
1660 }
1661 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001662
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001663 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001664 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1665
1666 // Overridden for testing purposes to avoid writing to SystemProperties.
1667 protected int getDefaultTcpRwnd() {
1668 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1669 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001670
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001671 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1672 if (isDefaultNetwork(nai) == false) {
1673 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001674 }
1675
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001676 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1677 String[] values = null;
1678 if (tcpBufferSizes != null) {
1679 values = tcpBufferSizes.split(",");
1680 }
1681
1682 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001683 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001684 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1685 values = tcpBufferSizes.split(",");
1686 }
1687
1688 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1689
1690 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001691 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001692
1693 final String prefix = "/sys/kernel/ipv4/tcp_";
1694 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1695 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1696 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1697 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1698 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1699 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1700 mCurrentTcpBufferSizes = tcpBufferSizes;
1701 } catch (IOException e) {
1702 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001703 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001704
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001705 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001706 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001707 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1708 if (rwndValue != 0) {
1709 SystemProperties.set(sysctlKey, rwndValue.toString());
1710 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001711 }
1712
Mattias Falk8b47b362011-08-23 14:15:13 +02001713 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001714 /*
1715 * Tell the VMs to toss their DNS caches
1716 */
1717 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1718 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001719 /*
1720 * Connectivity events can happen before boot has completed ...
1721 */
1722 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001723 final long ident = Binder.clearCallingIdentity();
1724 try {
1725 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1726 } finally {
1727 Binder.restoreCallingIdentity(ident);
1728 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001729 }
1730
Robert Greenwalt562cc542014-05-15 18:07:26 -07001731 @Override
1732 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001733 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1734 NETWORK_RESTORE_DELAY_PROP_NAME);
1735 if(restoreDefaultNetworkDelayStr != null &&
1736 restoreDefaultNetworkDelayStr.length() != 0) {
1737 try {
1738 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1739 } catch (NumberFormatException e) {
1740 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001741 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001742 // if the system property isn't set, use the value for the apn type
1743 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1744
1745 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1746 (mNetConfigs[networkType] != null)) {
1747 ret = mNetConfigs[networkType].restoreTime;
1748 }
1749 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 }
1751
1752 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001753 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1754 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001755 if (mContext.checkCallingOrSelfPermission(
1756 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001757 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001758 pw.println("Permission Denial: can't dump ConnectivityService " +
1759 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1760 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001761 return;
1762 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001763
Lorenzo Colittie3805462015-06-03 11:18:24 +09001764 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001765 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001766 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001767 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001768 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001769 pw.println();
1770
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001771 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1772 pw.print("Active default network: ");
1773 if (defaultNai == null) {
1774 pw.println("none");
1775 } else {
1776 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001777 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001778 pw.println();
1779
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001780 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001781 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001782 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1783 pw.println(nai.toString());
1784 pw.increaseIndent();
1785 pw.println("Requests:");
1786 pw.increaseIndent();
1787 for (int i = 0; i < nai.networkRequests.size(); i++) {
1788 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001789 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001790 pw.decreaseIndent();
1791 pw.println("Lingered:");
1792 pw.increaseIndent();
1793 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1794 pw.decreaseIndent();
1795 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001796 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001797 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001798 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001799
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001800 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001801 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001802 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1803 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001804 }
1805 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001806 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001807
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001808 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001809
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001810 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001811 pw.print("mNetTransitionWakeLock: currently " +
1812 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1813 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1814 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1815 } else {
1816 pw.println(", last requested never");
1817 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001818 }
1819 pw.println();
1820
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001821 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001822
Lorenzo Colittie3805462015-06-03 11:18:24 +09001823 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001824 pw.println();
1825 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001826 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001827 for(int i = 0; i < mInetLog.size(); i++) {
1828 pw.println(mInetLog.get(i));
1829 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001830 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001831 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001832 }
1833
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001834 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001835 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001836 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001837 if (officialNai != null && officialNai.equals(nai)) return true;
1838 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001839 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001840 " - " + nai);
1841 }
1842 return false;
1843 }
1844
Paul Jensenc8b9a742014-09-30 15:37:41 -04001845 private boolean isRequest(NetworkRequest request) {
1846 return mNetworkRequests.get(request).isRequest;
1847 }
1848
Robert Greenwalt42acef32009-08-12 16:08:25 -07001849 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001850 private class NetworkStateTrackerHandler extends Handler {
1851 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001852 super(looper);
1853 }
1854
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001855 @Override
1856 public void handleMessage(Message msg) {
1857 NetworkInfo info;
1858 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001859 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001860 handleAsyncChannelHalfConnect(msg);
1861 break;
1862 }
1863 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1864 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1865 if (nai != null) nai.asyncChannel.disconnect();
1866 break;
1867 }
1868 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1869 handleAsyncChannelDisconnected(msg);
1870 break;
1871 }
1872 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1873 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1874 if (nai == null) {
1875 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1876 } else {
1877 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001878 }
1879 break;
1880 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001881 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1882 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1883 if (nai == null) {
1884 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1885 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001886 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001887 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001888 "; created=" + nai.created);
1889 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001890 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001891 synchronized (nai) {
1892 nai.linkProperties = (LinkProperties)msg.obj;
1893 }
Paul Jenseneec75412014-08-04 12:21:19 -04001894 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001895 }
1896 break;
1897 }
1898 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1899 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1900 if (nai == null) {
1901 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1902 break;
1903 }
1904 info = (NetworkInfo) msg.obj;
1905 updateNetworkInfo(nai, info);
1906 break;
1907 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001908 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1909 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1910 if (nai == null) {
1911 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1912 break;
1913 }
1914 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001915 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001916 break;
1917 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001918 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1919 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1920 if (nai == null) {
1921 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1922 break;
1923 }
1924 try {
1925 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001926 } catch (Exception e) {
1927 // Never crash!
1928 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001929 }
1930 break;
1931 }
1932 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1933 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1934 if (nai == null) {
1935 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1936 break;
1937 }
1938 try {
1939 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001940 } catch (Exception e) {
1941 // Never crash!
1942 loge("Exception in removeVpnUidRanges: " + e);
1943 }
1944 break;
1945 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001946 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1947 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1948 if (nai == null) {
1949 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1950 break;
1951 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001952 if (nai.created && !nai.networkMisc.explicitlySelected) {
1953 loge("ERROR: created network explicitly selected.");
1954 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001955 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001956 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001957 break;
1958 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001959 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001960 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001961 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1962 final boolean valid =
1963 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
1964 final boolean validationChanged = (valid != nai.lastValidated);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001965 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001966 if (valid) {
1967 if (DBG) log("Validated " + nai.name());
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001968 nai.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001969 if (!nai.everValidated) {
1970 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001971 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1972 ReapUnvalidatedNetworks.REAP);
1973 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001974 sendUpdatedScoreToFactories(nai);
1975 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001976 } else {
1977 nai.networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -04001978 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001979 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001980 // Let the NetworkAgent know the state of its network
1981 nai.asyncChannel.sendMessage(
1982 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1983 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1984 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001985
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001986 if (validationChanged) {
1987 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
1988 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001989 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001990 break;
1991 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001992 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001993 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001994 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1995 handleLingerComplete(nai);
1996 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001997 break;
1998 }
Paul Jensen869868be2014-05-15 10:33:05 -04001999 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002000 if (msg.arg1 == 0) {
2001 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
2002 } else {
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002003 final NetworkAgentInfo nai;
Paul Jensen5df4bec2014-08-25 22:45:39 -04002004 synchronized (mNetworkForNetId) {
2005 nai = mNetworkForNetId.get(msg.arg2);
2006 }
2007 if (nai == null) {
2008 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2009 break;
2010 }
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002011 nai.captivePortalDetected = true;
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002012 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
2013 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04002014 }
Paul Jensen869868be2014-05-15 10:33:05 -04002015 break;
2016 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002017 }
2018 }
2019 }
2020
Paul Jensen0cc17322014-11-25 15:26:53 -05002021 // Cancel any lingering so the linger timeout doesn't teardown a network.
2022 // This should be called when a network begins satisfying a NetworkRequest.
2023 // Note: depending on what state the NetworkMonitor is in (e.g.,
2024 // if it's awaiting captive portal login, or if validation failed), this
2025 // may trigger a re-evaluation of the network.
2026 private void unlinger(NetworkAgentInfo nai) {
2027 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002028 // If network has never been validated, it cannot have been lingered, so don't bother
2029 // needlessly triggering a re-evaluation.
2030 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002031 nai.networkLingered.clear();
2032 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2033 }
2034
Robert Greenwalt7b816022014-04-18 15:25:25 -07002035 private void handleAsyncChannelHalfConnect(Message msg) {
2036 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002037 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002038 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2039 if (VDBG) log("NetworkFactory connected");
2040 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002041 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002042 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002043 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002044 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002045 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 }
2047 } else {
2048 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002049 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002050 }
2051 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2052 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2053 if (VDBG) log("NetworkAgent connected");
2054 // A network agent has requested a connection. Establish the connection.
2055 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2056 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2057 } else {
2058 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002059 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002060 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002061 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002062 synchronized (mNetworkForNetId) {
2063 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002064 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002065 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002066 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002067 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002068 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002069 }
2070 }
2071 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002072
Robert Greenwalt7b816022014-04-18 15:25:25 -07002073 private void handleAsyncChannelDisconnected(Message msg) {
2074 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2075 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002076 if (DBG) {
2077 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2078 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002079 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002080 if (nai.created) {
2081 // Tell netd to clean up the configuration for this network
2082 // (routing rules, DNS, etc).
2083 try {
2084 mNetd.removeNetwork(nai.network.netId);
2085 } catch (Exception e) {
2086 loge("Exception removing network: " + e);
2087 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002088 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002089 // TODO - if we move the logic to the network agent (have them disconnect
2090 // because they lost all their requests or because their score isn't good)
2091 // then they would disconnect organically, report their new state and then
2092 // disconnect the channel.
2093 if (nai.networkInfo.isConnected()) {
2094 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2095 null, null);
2096 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002097 final boolean wasDefault = isDefaultNetwork(nai);
2098 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002099 mDefaultInetConditionPublished = 0;
2100 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002101 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002102 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002103 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002104 mNetworkAgentInfos.remove(msg.replyTo);
2105 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002106 synchronized (mNetworkForNetId) {
2107 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002108 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002109 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002110 // Since we've lost the network, go through all the requests that
2111 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002112 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002113 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002114 for (int i = 0; i < nai.networkRequests.size(); i++) {
2115 NetworkRequest request = nai.networkRequests.valueAt(i);
2116 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2117 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002118 if (DBG) {
2119 log("Checking for replacement network to handle request " + request );
2120 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002121 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002122 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002123 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002124 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2125 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002126 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002127 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002128 alternative = existing;
2129 }
2130 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002131 if (alternative != null) {
2132 if (DBG) log(" found replacement in " + alternative.name());
2133 if (!toActivate.contains(alternative)) {
2134 toActivate.add(alternative);
2135 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002136 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002137 }
2138 }
2139 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2140 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002141 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002142 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002144 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002145 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002146 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002147 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2148 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002149 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302151 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2152 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002153 }
2154
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002155 // If this method proves to be too slow then we can maintain a separate
2156 // pendingIntent => NetworkRequestInfo map.
2157 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2158 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2159 Intent intent = pendingIntent.getIntent();
2160 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2161 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2162 if (existingPendingIntent != null &&
2163 existingPendingIntent.getIntent().filterEquals(intent)) {
2164 return entry.getValue();
2165 }
2166 }
2167 return null;
2168 }
2169
2170 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2171 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2172
2173 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2174 if (existingRequest != null) { // remove the existing request.
2175 if (DBG) log("Replacing " + existingRequest.request + " with "
2176 + nri.request + " because their intents matched.");
2177 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2178 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002179 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002180 }
2181
Erik Klineda4bfa82015-04-30 12:58:40 +09002182 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002183 mNetworkRequests.put(nri.request, nri);
2184
Paul Jensen0cc17322014-11-25 15:26:53 -05002185 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2186
Robert Greenwalt9258c642014-03-26 16:47:06 -07002187 // Check for the best currently alive network that satisfies this request
2188 NetworkAgentInfo bestNetwork = null;
2189 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002190 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002191 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002192 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002193 if (!nri.isRequest) {
2194 // Not setting bestNetwork here as a listening NetworkRequest may be
2195 // satisfied by multiple Networks. Instead the request is added to
2196 // each satisfying Network and notified about each.
2197 network.addRequest(nri.request);
2198 notifyNetworkCallback(network, nri);
2199 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002200 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002201 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002202 }
2203 }
2204 }
2205 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002206 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002207 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002208 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002209 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002210 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002211 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002212 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2213 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002214 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002215
Lorenzo Colittia793a672014-07-31 23:20:17 +09002216 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002217 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002218 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002219 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002220 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002221 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002222 }
2223 }
2224 }
2225
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002226 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2227 int callingUid) {
2228 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2229 if (nri != null) {
2230 handleReleaseNetworkRequest(nri.request, callingUid);
2231 }
2232 }
2233
Paul Jensen99364842014-12-09 11:43:45 -05002234 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2235 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2236 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2237 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2238 private boolean unneeded(NetworkAgentInfo nai) {
2239 if (!nai.created || nai.isVPN()) return false;
2240 boolean unneeded = true;
2241 if (nai.everValidated) {
2242 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2243 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2244 try {
2245 if (isRequest(nr)) unneeded = false;
2246 } catch (Exception e) {
2247 loge("Request " + nr + " not found in mNetworkRequests.");
2248 loge(" it came from request list of " + nai.name());
2249 }
2250 }
2251 } else {
2252 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2253 // If this Network is already the highest scoring Network for a request, or if
2254 // there is hope for it to become one if it validated, then it is needed.
2255 if (nri.isRequest && nai.satisfies(nri.request) &&
2256 (nai.networkRequests.get(nri.request.requestId) != null ||
2257 // Note that this catches two important cases:
2258 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2259 // is currently satisfying the request. This is desirable when
2260 // cellular ends up validating but WiFi does not.
2261 // 2. Unvalidated WiFi will not be reaped when validated cellular
2262 // is currently satsifying the request. This is desirable when
2263 // WiFi ends up validating and out scoring cellular.
2264 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2265 nai.getCurrentScoreAsValidated())) {
2266 unneeded = false;
2267 break;
2268 }
2269 }
2270 }
2271 return unneeded;
2272 }
2273
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002274 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2275 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002276 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002277 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002278 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2279 return;
2280 }
2281 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002282 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002283 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002284 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002285 // Find all networks that are satisfying this request and remove the request
2286 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002287 // TODO - it's my understanding that for a request there is only a single
2288 // network satisfying it, so this loop is wasteful
2289 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002290 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2291 if (nai.networkRequests.get(nri.request.requestId) != null) {
2292 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002293 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002294 log(" Removing from current network " + nai.name() +
2295 ", leaving " + nai.networkRequests.size() +
2296 " requests.");
2297 }
Paul Jensen99364842014-12-09 11:43:45 -05002298 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002299 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002300 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002301 } else {
2302 // suspect there should only be one pass through here
2303 // but if any were kept do the check below
2304 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002305 }
2306 }
2307 }
2308
Robert Greenwalt51481852015-01-08 14:43:31 -08002309 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2310 if (nai != null) {
2311 mNetworkForRequestId.remove(nri.request.requestId);
2312 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002313 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002314 // that a network connected to serve it, even though the network was already
2315 // connected. Now that this request has gone away, we might have to pretend
2316 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002317 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002318 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2319 boolean doRemove = true;
2320 if (wasKept) {
2321 // check if any of the remaining requests for this network are for the
2322 // same legacy type - if so, don't remove the nai
2323 for (int i = 0; i < nai.networkRequests.size(); i++) {
2324 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2325 if (otherRequest.legacyType == nri.request.legacyType &&
2326 isRequest(otherRequest)) {
2327 if (DBG) log(" still have other legacy request - leaving");
2328 doRemove = false;
2329 }
2330 }
2331 }
2332
2333 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002334 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002335 }
2336 }
2337
Robert Greenwalta67be032014-05-16 15:49:14 -07002338 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002339 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2340 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002341 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002342 } else {
2343 // listens don't have a singular affectedNetwork. Check all networks to see
2344 // if this listen request applies and remove it.
2345 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2346 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002347 }
2348 }
2349 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2350 }
2351 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002352
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002353 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2354 enforceConnectivityInternalPermission();
2355 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2356 accept ? 1 : 0, always ? 1: 0, network));
2357 }
2358
2359 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2360 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2361 " accept=" + accept + " always=" + always);
2362
2363 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2364 if (nai == null) {
2365 // Nothing to do.
2366 return;
2367 }
2368
2369 if (nai.everValidated) {
2370 // The network validated while the dialog box was up. Don't make any changes. There's a
2371 // TODO in the dialog code to make it go away if the network validates; once that's
2372 // implemented, taking action here will be confusing.
2373 return;
2374 }
2375
2376 if (!nai.networkMisc.explicitlySelected) {
2377 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2378 }
2379
2380 if (accept != nai.networkMisc.acceptUnvalidated) {
2381 int oldScore = nai.getCurrentScore();
2382 nai.networkMisc.acceptUnvalidated = accept;
2383 rematchAllNetworksAndRequests(nai, oldScore);
2384 sendUpdatedScoreToFactories(nai);
2385 }
2386
2387 if (always) {
2388 nai.asyncChannel.sendMessage(
2389 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2390 }
2391
2392 // TODO: should we also disconnect from the network if accept is false?
2393 }
2394
2395 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2396 mHandler.sendMessageDelayed(
2397 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2398 PROMPT_UNVALIDATED_DELAY_MS);
2399 }
2400
2401 private void handlePromptUnvalidated(Network network) {
2402 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2403
2404 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2405 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002406 // Also don't prompt on captive portals because we're already prompting the user to sign in.
2407 if (nai == null || nai.everValidated || nai.captivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002408 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2409 return;
2410 }
2411
2412 // TODO: What should we do if we've already switched to this network because we had no
2413 // better option? There are two obvious alternatives.
2414 //
2415 // 1. Decide that there's no point prompting because this is our only usable network.
2416 // However, because we didn't prompt, if later on a validated network comes along, we'll
2417 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2418 // unvalidated network - or b) prompt the user at that later time - bad because the user
2419 // might not understand why they are now being prompted.
2420 //
2421 // 2. Always prompt the user, even if we have no other network to use. The user could then
2422 // try to find an alternative network to join (remember, if we got here, then the user
2423 // selected this network manually). This is bad because the prompt isn't really very
2424 // useful.
2425 //
2426 // For now we do #1, but we can revisit that later.
2427 if (isDefaultNetwork(nai)) {
2428 return;
2429 }
2430
2431 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2432 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2433 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2434 intent.setClassName("com.android.settings",
2435 "com.android.settings.wifi.WifiNoInternetDialog");
2436 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2437 }
2438
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002439 private class InternalHandler extends Handler {
2440 public InternalHandler(Looper looper) {
2441 super(looper);
2442 }
2443
2444 @Override
2445 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002446 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002447 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002448 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002449 String causedBy = null;
2450 synchronized (ConnectivityService.this) {
2451 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2452 mNetTransitionWakeLock.isHeld()) {
2453 mNetTransitionWakeLock.release();
2454 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002455 } else {
2456 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002457 }
2458 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002459 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2460 log("Failed to find a new network - expiring NetTransition Wakelock");
2461 } else {
2462 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2463 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002464 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002465 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002466 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002467 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002468 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002469 break;
2470 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002471 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002472 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002473 sendStickyBroadcast(intent);
2474 break;
2475 }
Jason Monkdecd2952013-10-10 14:02:51 -04002476 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002477 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002478 break;
2479 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002480 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002481 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2482 break;
2483 }
2484 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2485 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002486 break;
2487 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002488 case EVENT_REGISTER_NETWORK_AGENT: {
2489 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2490 break;
2491 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002492 case EVENT_REGISTER_NETWORK_REQUEST:
2493 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002494 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002495 break;
2496 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002497 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2498 handleRegisterNetworkRequestWithIntent(msg);
2499 break;
2500 }
2501 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2502 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2503 break;
2504 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002505 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002506 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002507 break;
2508 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002509 case EVENT_SET_ACCEPT_UNVALIDATED: {
2510 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2511 break;
2512 }
2513 case EVENT_PROMPT_UNVALIDATED: {
2514 handlePromptUnvalidated((Network) msg.obj);
2515 break;
2516 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002517 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2518 handleMobileDataAlwaysOn();
2519 break;
2520 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002521 case EVENT_SYSTEM_READY: {
2522 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2523 nai.networkMonitor.systemReady = true;
2524 }
2525 break;
2526 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002527 }
2528 }
2529 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002530
2531 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002532 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002533 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002534 if (isTetheringSupported()) {
2535 return mTethering.tether(iface);
2536 } else {
2537 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2538 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002539 }
2540
2541 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002542 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002543 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002544
2545 if (isTetheringSupported()) {
2546 return mTethering.untether(iface);
2547 } else {
2548 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2549 }
2550 }
2551
2552 // javadoc from interface
2553 public int getLastTetherError(String iface) {
2554 enforceTetherAccessPermission();
2555
2556 if (isTetheringSupported()) {
2557 return mTethering.getLastTetherError(iface);
2558 } else {
2559 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2560 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002561 }
2562
2563 // TODO - proper iface API for selection by property, inspection, etc
2564 public String[] getTetherableUsbRegexs() {
2565 enforceTetherAccessPermission();
2566 if (isTetheringSupported()) {
2567 return mTethering.getTetherableUsbRegexs();
2568 } else {
2569 return new String[0];
2570 }
2571 }
2572
2573 public String[] getTetherableWifiRegexs() {
2574 enforceTetherAccessPermission();
2575 if (isTetheringSupported()) {
2576 return mTethering.getTetherableWifiRegexs();
2577 } else {
2578 return new String[0];
2579 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002580 }
2581
Danica Chang6fdd0c62010-08-11 14:54:43 -07002582 public String[] getTetherableBluetoothRegexs() {
2583 enforceTetherAccessPermission();
2584 if (isTetheringSupported()) {
2585 return mTethering.getTetherableBluetoothRegexs();
2586 } else {
2587 return new String[0];
2588 }
2589 }
2590
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002591 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002592 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002593 if (isTetheringSupported()) {
2594 return mTethering.setUsbTethering(enable);
2595 } else {
2596 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2597 }
2598 }
2599
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002600 // TODO - move iface listing, queries, etc to new module
2601 // javadoc from interface
2602 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002603 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002604 return mTethering.getTetherableIfaces();
2605 }
2606
2607 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002608 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002609 return mTethering.getTetheredIfaces();
2610 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002611
Robert Greenwalt5a735062010-03-02 17:25:02 -08002612 public String[] getTetheringErroredIfaces() {
2613 enforceTetherAccessPermission();
2614 return mTethering.getErroredIfaces();
2615 }
2616
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002617 public String[] getTetheredDhcpRanges() {
2618 enforceConnectivityInternalPermission();
2619 return mTethering.getTetheredDhcpRanges();
2620 }
2621
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002622 // if ro.tether.denied = true we default to no tethering
2623 // gservices could set the secure setting to 1 though to enable it on a build where it
2624 // had previously been turned off.
2625 public boolean isTetheringSupported() {
2626 enforceTetherAccessPermission();
2627 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002628 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002629 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2630 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002631 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2632 mTethering.getTetherableWifiRegexs().length != 0 ||
2633 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2634 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002635 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002636
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002637 // Called when we lose the default network and have no replacement yet.
2638 // This will automatically be cleared after X seconds or a new default network
2639 // becomes CONNECTED, whichever happens first. The timer is started by the
2640 // first caller and not restarted by subsequent callers.
2641 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002642 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002643 synchronized (this) {
2644 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002645 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002646 mNetTransitionWakeLock.acquire();
2647 mNetTransitionWakeLockCausedBy = forWhom;
2648 }
2649 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002650 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002651 mNetTransitionWakeLockTimeout);
2652 return;
2653 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002654
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002655 // 100 percent is full good, 0 is full bad.
2656 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002657 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002658 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002659 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002660 }
2661
Paul Jensenbfd17b72015-04-07 12:43:13 -04002662 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002663 enforceAccessPermission();
2664 enforceInternetPermission();
2665
Paul Jensenbfd17b72015-04-07 12:43:13 -04002666 NetworkAgentInfo nai;
2667 if (network == null) {
2668 nai = getDefaultNetwork();
2669 } else {
2670 nai = getNetworkAgentInfoForNetwork(network);
2671 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002672 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002673 // Revalidate if the app report does not match our current validated state.
2674 if (hasConnectivity == nai.lastValidated) return;
2675 final int uid = Binder.getCallingUid();
2676 if (DBG) {
2677 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2678 ") by " + uid);
2679 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002680 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002681 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2682 // which isn't meant to work on uncreated networks.
2683 if (!nai.created) return;
2684
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002685 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002686
2687 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2688 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002689 }
2690
Paul Jensen25a217c2015-02-27 22:55:47 -05002691 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2692 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2693 enforceConnectivityInternalPermission();
2694 }
2695 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2696 if (nai == null) return;
2697 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2698 actionToken);
2699 }
2700
Paul Jensencee9b512015-05-06 07:32:40 -04002701 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002702 // this information is already available as a world read/writable jvm property
2703 // so this API change wouldn't have a benifit. It also breaks the passing
2704 // of proxy info to all the JVMs.
2705 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002706 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002707 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002708 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2709 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002710 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002711 }
2712
Paul Jensencee9b512015-05-06 07:32:40 -04002713 public ProxyInfo getProxyForNetwork(Network network) {
2714 if (network == null) return getDefaultProxy();
2715 final ProxyInfo globalProxy = getGlobalProxy();
2716 if (globalProxy != null) return globalProxy;
2717 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2718 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2719 // caller may not have.
2720 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2721 if (nai == null) return null;
2722 synchronized (nai) {
2723 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2724 if (proxyInfo == null) return null;
2725 return new ProxyInfo(proxyInfo);
2726 }
2727 }
2728
Paul Jensene0bef712014-12-10 15:12:18 -05002729 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2730 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2731 // proxy is null then there is no proxy in place).
2732 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2733 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2734 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2735 proxy = null;
2736 }
2737 return proxy;
2738 }
2739
2740 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2741 // better for determining if a new proxy broadcast is necessary:
2742 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2743 // avoid unnecessary broadcasts.
2744 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2745 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2746 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2747 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2748 // all set.
2749 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2750 a = canonicalizeProxyInfo(a);
2751 b = canonicalizeProxyInfo(b);
2752 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2753 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2754 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2755 }
2756
Jason Monk207900c2014-04-25 15:00:09 -04002757 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002758 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002759
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002760 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002761 if (proxyProperties == mGlobalProxy) return;
2762 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2763 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2764
2765 String host = "";
2766 int port = 0;
2767 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002768 String pacFileUrl = "";
2769 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002770 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002771 if (!proxyProperties.isValid()) {
2772 if (DBG)
2773 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2774 return;
2775 }
Jason Monk207900c2014-04-25 15:00:09 -04002776 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002777 host = mGlobalProxy.getHost();
2778 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002779 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002780 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002781 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002782 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002783 } else {
2784 mGlobalProxy = null;
2785 }
2786 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002787 final long token = Binder.clearCallingIdentity();
2788 try {
2789 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2790 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2791 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2792 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002793 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002794 } finally {
2795 Binder.restoreCallingIdentity(token);
2796 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002797
Jason Monkcf0f97a2014-10-02 15:39:38 -04002798 if (mGlobalProxy == null) {
2799 proxyProperties = mDefaultProxy;
2800 }
2801 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002802 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002803 }
2804
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002805 private void loadGlobalProxy() {
2806 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002807 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2808 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2809 String exclList = Settings.Global.getString(res,
2810 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002811 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2812 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002813 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002814 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002815 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002816 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002817 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002818 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002819 if (!proxyProperties.isValid()) {
2820 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2821 return;
2822 }
2823
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002824 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002825 mGlobalProxy = proxyProperties;
2826 }
2827 }
2828 }
2829
Jason Monk207900c2014-04-25 15:00:09 -04002830 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002831 // this information is already available as a world read/writable jvm property
2832 // so this API change wouldn't have a benifit. It also breaks the passing
2833 // of proxy info to all the JVMs.
2834 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002835 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002836 return mGlobalProxy;
2837 }
2838 }
2839
Jason Monk207900c2014-04-25 15:00:09 -04002840 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002841 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002842 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002843 proxy = null;
2844 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002845 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002846 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002847 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002848 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002849 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2850 return;
2851 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002852
2853 // This call could be coming from the PacManager, containing the port of the local
2854 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2855 // global (to get the correct local port), and send a broadcast.
2856 // TODO: Switch PacManager to have its own message to send back rather than
2857 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002858 if ((mGlobalProxy != null) && (proxy != null)
2859 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002860 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2861 mGlobalProxy = proxy;
2862 sendProxyBroadcast(mGlobalProxy);
2863 return;
2864 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002865 mDefaultProxy = proxy;
2866
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002867 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002868 if (!mDefaultProxyDisabled) {
2869 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002870 }
2871 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002872 }
2873
Paul Jensene0bef712014-12-10 15:12:18 -05002874 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2875 // This method gets called when any network changes proxy, but the broadcast only ever contains
2876 // the default proxy (even if it hasn't changed).
2877 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2878 // world where an app might be bound to a non-default network.
2879 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2880 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2881 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2882
2883 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2884 sendProxyBroadcast(getDefaultProxy());
2885 }
2886 }
2887
Robert Greenwalt434203a2010-10-11 16:00:27 -07002888 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002889 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2890 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002891 if (!TextUtils.isEmpty(proxy)) {
2892 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002893 if (data.length == 0) {
2894 return;
2895 }
2896
Robert Greenwalt434203a2010-10-11 16:00:27 -07002897 String proxyHost = data[0];
2898 int proxyPort = 8080;
2899 if (data.length > 1) {
2900 try {
2901 proxyPort = Integer.parseInt(data[1]);
2902 } catch (NumberFormatException e) {
2903 return;
2904 }
2905 }
Jason Monk207900c2014-04-25 15:00:09 -04002906 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002907 setGlobalProxy(p);
2908 }
2909 }
2910
Jason Monk207900c2014-04-25 15:00:09 -04002911 private void sendProxyBroadcast(ProxyInfo proxy) {
2912 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002913 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002914 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002916 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2917 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002918 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002919 final long ident = Binder.clearCallingIdentity();
2920 try {
2921 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2922 } finally {
2923 Binder.restoreCallingIdentity(ident);
2924 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002925 }
2926
2927 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002928 final private HashMap<Uri, Integer> mUriEventMap;
2929 final private Context mContext;
2930 final private Handler mHandler;
2931
2932 SettingsObserver(Context context, Handler handler) {
2933 super(null);
2934 mUriEventMap = new HashMap<Uri, Integer>();
2935 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002936 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002937 }
2938
Erik Klineda4bfa82015-04-30 12:58:40 +09002939 void observe(Uri uri, int what) {
2940 mUriEventMap.put(uri, what);
2941 final ContentResolver resolver = mContext.getContentResolver();
2942 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002943 }
2944
2945 @Override
2946 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002947 Slog.wtf(TAG, "Should never be reached.");
2948 }
2949
2950 @Override
2951 public void onChange(boolean selfChange, Uri uri) {
2952 final Integer what = mUriEventMap.get(uri);
2953 if (what != null) {
2954 mHandler.obtainMessage(what.intValue()).sendToTarget();
2955 } else {
2956 loge("No matching event to send for URI=" + uri);
2957 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002958 }
2959 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002960
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002961 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002962 Slog.d(TAG, s);
2963 }
2964
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002965 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002966 Slog.e(TAG, s);
2967 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002968
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002969 private static <T> T checkNotNull(T value, String message) {
2970 if (value == null) {
2971 throw new NullPointerException(message);
2972 }
2973 return value;
2974 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002975
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002976 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002977 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002978 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2979 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2980 *
2981 * @param oldPackage Package name of the application which currently controls VPN, which will
2982 * be replaced. If there is no such application, this should should either be
2983 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2984 * @param newPackage Package name of the application which should gain control of VPN, or
2985 * {@code null} to disable.
2986 * @param userId User for whom to prepare the new VPN.
2987 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002988 * @hide
2989 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002990 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002991 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2992 int userId) {
2993 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002994 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002995
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002996 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01002997 return mVpns.get(userId).prepare(oldPackage, newPackage);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002998 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002999 }
3000
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003001 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003002 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3003 * This method is used by system-privileged apps.
3004 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3005 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3006 *
3007 * @param packageName The package for which authorization state should change.
3008 * @param userId User for whom {@code packageName} is installed.
3009 * @param authorized {@code true} if this app should be able to start a VPN connection without
3010 * explicit user approval, {@code false} if not.
3011 *
Jeff Davidson05542602014-08-11 14:07:27 -07003012 * @hide
3013 */
3014 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003015 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3016 enforceCrossUserPermission(userId);
3017
Jeff Davidson05542602014-08-11 14:07:27 -07003018 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003019 mVpns.get(userId).setPackageAuthorization(packageName, authorized);
Jeff Davidson05542602014-08-11 14:07:27 -07003020 }
3021 }
3022
3023 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003024 * Configure a TUN interface and return its file descriptor. Parameters
3025 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003026 * and not available in ConnectivityManager. Permissions are checked in
3027 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003028 * @hide
3029 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003030 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003031 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003032 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003033 int user = UserHandle.getUserId(Binder.getCallingUid());
3034 synchronized(mVpns) {
3035 return mVpns.get(user).establish(config);
3036 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003037 }
3038
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003039 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003040 * Start legacy VPN, controlling native daemons as needed. Creates a
3041 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003042 */
3043 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003044 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003045 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003046 final LinkProperties egress = getActiveLinkProperties();
3047 if (egress == null) {
3048 throw new IllegalStateException("Missing active network connection");
3049 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003050 int user = UserHandle.getUserId(Binder.getCallingUid());
3051 synchronized(mVpns) {
3052 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3053 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003054 }
3055
3056 /**
3057 * Return the information of the ongoing legacy VPN. This method is used
3058 * by VpnSettings and not available in ConnectivityManager. Permissions
3059 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003060 */
3061 @Override
3062 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003063 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003064 int user = UserHandle.getUserId(Binder.getCallingUid());
3065 synchronized(mVpns) {
3066 return mVpns.get(user).getLegacyVpnInfo();
3067 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003068 }
3069
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003070 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003071 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3072 * and not available in ConnectivityManager.
3073 */
3074 @Override
3075 public VpnInfo[] getAllVpnInfo() {
3076 enforceConnectivityInternalPermission();
3077 if (mLockdownEnabled) {
3078 return new VpnInfo[0];
3079 }
3080
3081 synchronized(mVpns) {
3082 List<VpnInfo> infoList = new ArrayList<>();
3083 for (int i = 0; i < mVpns.size(); i++) {
3084 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3085 if (info != null) {
3086 infoList.add(info);
3087 }
3088 }
3089 return infoList.toArray(new VpnInfo[infoList.size()]);
3090 }
3091 }
3092
3093 /**
3094 * @return VPN information for accounting, or null if we can't retrieve all required
3095 * information, e.g primary underlying iface.
3096 */
3097 @Nullable
3098 private VpnInfo createVpnInfo(Vpn vpn) {
3099 VpnInfo info = vpn.getVpnInfo();
3100 if (info == null) {
3101 return null;
3102 }
3103 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3104 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3105 // the underlyingNetworks list.
3106 if (underlyingNetworks == null) {
3107 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3108 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3109 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3110 }
3111 } else if (underlyingNetworks.length > 0) {
3112 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3113 if (linkProperties != null) {
3114 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3115 }
3116 }
3117 return info.primaryUnderlyingIface == null ? null : info;
3118 }
3119
3120 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003121 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3122 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003123 * Permissions are checked in Vpn class.
3124 * @hide
3125 */
3126 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003127 public VpnConfig getVpnConfig(int userId) {
3128 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003129 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003130 return mVpns.get(userId).getVpnConfig();
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003131 }
3132 }
3133
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003134 @Override
3135 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003136 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3137 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3138 return false;
3139 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003140
3141 // Tear down existing lockdown if profile was removed
3142 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3143 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003144 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003145 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3146 return false;
3147 }
3148
3149 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3150 final VpnProfile profile = VpnProfile.decode(
3151 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003152 int user = UserHandle.getUserId(Binder.getCallingUid());
3153 synchronized(mVpns) {
3154 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3155 profile));
3156 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003157 } else {
3158 setLockdownTracker(null);
3159 }
3160
3161 return true;
3162 }
3163
3164 /**
3165 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3166 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3167 */
3168 private void setLockdownTracker(LockdownVpnTracker tracker) {
3169 // Shutdown any existing tracker
3170 final LockdownVpnTracker existing = mLockdownTracker;
3171 mLockdownTracker = null;
3172 if (existing != null) {
3173 existing.shutdown();
3174 }
3175
3176 try {
3177 if (tracker != null) {
3178 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003179 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003180 mLockdownTracker = tracker;
3181 mLockdownTracker.init();
3182 } else {
3183 mNetd.setFirewallEnabled(false);
3184 }
3185 } catch (RemoteException e) {
3186 // ignored; NMS lives inside system_server
3187 }
3188 }
3189
3190 private void throwIfLockdownEnabled() {
3191 if (mLockdownEnabled) {
3192 throw new IllegalStateException("Unavailable in lockdown mode");
3193 }
3194 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003195
Wink Savilleab9321d2013-06-29 21:10:57 -07003196 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003197 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003198 // TODO: Remove? Any reason to trigger a provisioning check?
3199 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003200 }
3201
3202 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3203 private volatile boolean mIsNotificationVisible = false;
3204
Paul Jensen89e0f092014-09-15 15:59:36 -04003205 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003206 if (DBG) {
3207 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003208 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003209 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003210 Intent intent = new Intent(action);
3211 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003212 // Concatenate the range of types onto the range of NetIDs.
3213 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003214 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003215 }
3216
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003217 /**
3218 * Show or hide network provisioning notificaitons.
3219 *
3220 * @param id an identifier that uniquely identifies this notification. This must match
3221 * between show and hide calls. We use the NetID value but for legacy callers
3222 * we concatenate the range of types with the range of NetIDs.
3223 */
3224 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003225 String extraInfo, PendingIntent intent) {
3226 if (DBG) {
3227 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3228 networkType + " extraInfo=" + extraInfo);
3229 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003230
3231 Resources r = Resources.getSystem();
3232 NotificationManager notificationManager = (NotificationManager) mContext
3233 .getSystemService(Context.NOTIFICATION_SERVICE);
3234
3235 if (visible) {
3236 CharSequence title;
3237 CharSequence details;
3238 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003239 Notification notification = new Notification();
3240 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003241 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003242 title = r.getString(R.string.wifi_available_sign_in, 0);
3243 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003244 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003245 icon = R.drawable.stat_notify_wifi_in_range;
3246 break;
3247 case ConnectivityManager.TYPE_MOBILE:
3248 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003249 title = r.getString(R.string.network_available_sign_in, 0);
3250 // TODO: Change this to pull from NetworkInfo once a printable
3251 // name has been added to it
3252 details = mTelephonyManager.getNetworkOperatorName();
3253 icon = R.drawable.stat_notify_rssi_in_range;
3254 break;
3255 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003256 title = r.getString(R.string.network_available_sign_in, 0);
3257 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003258 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003259 icon = R.drawable.stat_notify_rssi_in_range;
3260 break;
3261 }
3262
Wink Savilleab9321d2013-06-29 21:10:57 -07003263 notification.when = 0;
3264 notification.icon = icon;
3265 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003266 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003267 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003268 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003269 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003270 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003271
Wink Saville948282b2013-08-29 08:55:16 -07003272 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003273 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003274 } catch (NullPointerException npe) {
3275 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3276 npe.printStackTrace();
3277 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003278 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003279 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003280 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003281 } catch (NullPointerException npe) {
3282 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3283 npe.printStackTrace();
3284 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003285 }
Wink Saville948282b2013-08-29 08:55:16 -07003286 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003287 }
3288
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003289 /** Location to an updatable file listing carrier provisioning urls.
3290 * An example:
3291 *
3292 * <?xml version="1.0" encoding="utf-8"?>
3293 * <provisioningUrls>
3294 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3295 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3296 * </provisioningUrls>
3297 */
3298 private static final String PROVISIONING_URL_PATH =
3299 "/data/misc/radio/provisioning_urls.xml";
3300 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003301
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003302 /** XML tag for root element. */
3303 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3304 /** XML tag for individual url */
3305 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3306 /** XML tag for redirected url */
3307 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3308 /** XML attribute for mcc */
3309 private static final String ATTR_MCC = "mcc";
3310 /** XML attribute for mnc */
3311 private static final String ATTR_MNC = "mnc";
3312
3313 private static final int REDIRECTED_PROVISIONING = 1;
3314 private static final int PROVISIONING = 2;
3315
3316 private String getProvisioningUrlBaseFromFile(int type) {
3317 FileReader fileReader = null;
3318 XmlPullParser parser = null;
3319 Configuration config = mContext.getResources().getConfiguration();
3320 String tagType;
3321
3322 switch (type) {
3323 case PROVISIONING:
3324 tagType = TAG_PROVISIONING_URL;
3325 break;
3326 case REDIRECTED_PROVISIONING:
3327 tagType = TAG_REDIRECTED_URL;
3328 break;
3329 default:
3330 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3331 type);
3332 }
3333
3334 try {
3335 fileReader = new FileReader(mProvisioningUrlFile);
3336 parser = Xml.newPullParser();
3337 parser.setInput(fileReader);
3338 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3339
3340 while (true) {
3341 XmlUtils.nextElement(parser);
3342
3343 String element = parser.getName();
3344 if (element == null) break;
3345
3346 if (element.equals(tagType)) {
3347 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3348 try {
3349 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3350 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3351 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3352 parser.next();
3353 if (parser.getEventType() == XmlPullParser.TEXT) {
3354 return parser.getText();
3355 }
3356 }
3357 }
3358 } catch (NumberFormatException e) {
3359 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3360 }
3361 }
3362 }
3363 return null;
3364 } catch (FileNotFoundException e) {
3365 loge("Carrier Provisioning Urls file not found");
3366 } catch (XmlPullParserException e) {
3367 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3368 } catch (IOException e) {
3369 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3370 } finally {
3371 if (fileReader != null) {
3372 try {
3373 fileReader.close();
3374 } catch (IOException e) {}
3375 }
3376 }
3377 return null;
3378 }
3379
Wink Saville42d4f082013-07-20 20:31:59 -07003380 @Override
3381 public String getMobileRedirectedProvisioningUrl() {
3382 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003383 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3384 if (TextUtils.isEmpty(url)) {
3385 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3386 }
3387 return url;
3388 }
3389
Wink Saville42d4f082013-07-20 20:31:59 -07003390 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003391 public String getMobileProvisioningUrl() {
3392 enforceConnectivityInternalPermission();
3393 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3394 if (TextUtils.isEmpty(url)) {
3395 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003396 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003397 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003398 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003399 }
Wink Saville8cf35602013-07-10 23:00:07 -07003400 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003401 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003402 String phoneNumber = mTelephonyManager.getLine1Number();
3403 if (TextUtils.isEmpty(phoneNumber)) {
3404 phoneNumber = "0000000000";
3405 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003406 url = String.format(url,
3407 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3408 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003409 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003410 }
3411
Wink Savilleab9321d2013-06-29 21:10:57 -07003412 return url;
3413 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003414
Wink Saville948282b2013-08-29 08:55:16 -07003415 @Override
3416 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003417 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003418 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003419 final long ident = Binder.clearCallingIdentity();
3420 try {
3421 setProvNotificationVisible(visible, networkType, action);
3422 } finally {
3423 Binder.restoreCallingIdentity(ident);
3424 }
Wink Saville948282b2013-08-29 08:55:16 -07003425 }
Wink Saville7788c612013-08-29 14:57:08 -07003426
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003427 @Override
3428 public void setAirplaneMode(boolean enable) {
3429 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003430 final long ident = Binder.clearCallingIdentity();
3431 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003432 final ContentResolver cr = mContext.getContentResolver();
3433 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3434 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3435 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003436 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003437 } finally {
3438 Binder.restoreCallingIdentity(ident);
3439 }
3440 }
3441
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003442 private void onUserStart(int userId) {
3443 synchronized(mVpns) {
3444 Vpn userVpn = mVpns.get(userId);
3445 if (userVpn != null) {
3446 loge("Starting user already has a VPN");
3447 return;
3448 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003449 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003450 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003451 }
3452 }
3453
3454 private void onUserStop(int userId) {
3455 synchronized(mVpns) {
3456 Vpn userVpn = mVpns.get(userId);
3457 if (userVpn == null) {
3458 loge("Stopping user has no VPN");
3459 return;
3460 }
3461 mVpns.delete(userId);
3462 }
3463 }
3464
3465 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3466 @Override
3467 public void onReceive(Context context, Intent intent) {
3468 final String action = intent.getAction();
3469 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3470 if (userId == UserHandle.USER_NULL) return;
3471
3472 if (Intent.ACTION_USER_STARTING.equals(action)) {
3473 onUserStart(userId);
3474 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3475 onUserStop(userId);
3476 }
3477 }
3478 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003479
Robert Greenwalta67be032014-05-16 15:49:14 -07003480 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3481 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003482 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3483 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003484
Robert Greenwalta67be032014-05-16 15:49:14 -07003485 private static class NetworkFactoryInfo {
3486 public final String name;
3487 public final Messenger messenger;
3488 public final AsyncChannel asyncChannel;
3489
3490 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3491 this.name = name;
3492 this.messenger = messenger;
3493 this.asyncChannel = asyncChannel;
3494 }
3495 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003496
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003497 /**
3498 * Tracks info about the requester.
3499 * Also used to notice when the calling process dies so we can self-expire
3500 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003501 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3502 static final boolean REQUEST = true;
3503 static final boolean LISTEN = false;
3504
3505 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003506 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003507 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003508 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003509 final int mPid;
3510 final int mUid;
3511 final Messenger messenger;
3512 final boolean isRequest;
3513
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003514 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3515 request = r;
3516 mPendingIntent = pi;
3517 messenger = null;
3518 mBinder = null;
3519 mPid = getCallingPid();
3520 mUid = getCallingUid();
3521 this.isRequest = isRequest;
3522 }
3523
Robert Greenwalt9258c642014-03-26 16:47:06 -07003524 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3525 super();
3526 messenger = m;
3527 request = r;
3528 mBinder = binder;
3529 mPid = getCallingPid();
3530 mUid = getCallingUid();
3531 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003532 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003533
3534 try {
3535 mBinder.linkToDeath(this, 0);
3536 } catch (RemoteException e) {
3537 binderDied();
3538 }
3539 }
3540
3541 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003542 if (mBinder != null) {
3543 mBinder.unlinkToDeath(this, 0);
3544 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003545 }
3546
3547 public void binderDied() {
3548 log("ConnectivityService NetworkRequestInfo binderDied(" +
3549 request + ", " + mBinder + ")");
3550 releaseNetworkRequest(request);
3551 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003552
3553 public String toString() {
3554 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003555 mPid + " for " + request +
3556 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003557 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003558 }
3559
3560 @Override
3561 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003562 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003563 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003564 enforceNetworkRequestPermissions(networkCapabilities);
3565 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003566
Robert Greenwalt6078b502014-06-11 16:05:07 -07003567 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003568 throw new IllegalArgumentException("Bad timeout specified");
3569 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003570
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003571 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3572 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003573 if (DBG) log("requestNetwork for " + networkRequest);
3574 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3575 NetworkRequestInfo.REQUEST);
3576
3577 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003578 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003579 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003580 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003581 }
3582 return networkRequest;
3583 }
3584
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003585 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003586 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003587 enforceConnectivityInternalPermission();
3588 } else {
3589 enforceChangePermission();
3590 }
3591 }
3592
fenglub15e72b2015-03-20 11:29:56 -07003593 @Override
fengludb571472015-04-21 17:12:05 -07003594 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003595 enforceAccessPermission();
3596 NetworkAgentInfo nai = null;
3597 if (network == null) {
3598 return false;
3599 }
3600 synchronized (mNetworkForNetId) {
3601 nai = mNetworkForNetId.get(network.netId);
3602 }
3603 if (nai != null) {
3604 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3605 return true;
3606 }
3607 return false;
3608 }
3609
3610
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003611 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3612 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003613 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003614 final int uidRules;
3615 final int uid = Binder.getCallingUid();
3616 synchronized(mRulesLock) {
3617 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3618 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003619 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003620 // we could silently fail or we can filter the available nets to only give
3621 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003622 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003623 }
3624 }
3625 }
3626
Robert Greenwalt9258c642014-03-26 16:47:06 -07003627 @Override
3628 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3629 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003630 checkNotNull(operation, "PendingIntent cannot be null.");
3631 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3632 enforceNetworkRequestPermissions(networkCapabilities);
3633 enforceMeteredApnPolicy(networkCapabilities);
3634
3635 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3636 nextNetworkRequestId());
3637 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3638 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3639 NetworkRequestInfo.REQUEST);
3640 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3641 nri));
3642 return networkRequest;
3643 }
3644
Jeremy Joslin79294842014-12-03 17:15:28 -08003645 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3646 mHandler.sendMessageDelayed(
3647 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3648 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3649 }
3650
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003651 @Override
3652 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003653 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003654 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3655 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003656 }
3657
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003658 // In order to implement the compatibility measure for pre-M apps that call
3659 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3660 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3661 // This ensures it has permission to do so.
3662 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3663 if (nc == null) {
3664 return false;
3665 }
3666 int[] transportTypes = nc.getTransportTypes();
3667 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3668 return false;
3669 }
3670 try {
3671 mContext.enforceCallingOrSelfPermission(
3672 android.Manifest.permission.ACCESS_WIFI_STATE,
3673 "ConnectivityService");
3674 } catch (SecurityException e) {
3675 return false;
3676 }
3677 return true;
3678 }
3679
Robert Greenwalt9258c642014-03-26 16:47:06 -07003680 @Override
3681 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3682 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003683 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3684 enforceAccessPermission();
3685 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003686
3687 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003688 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003689 if (DBG) log("listenForNetwork for " + networkRequest);
3690 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3691 NetworkRequestInfo.LISTEN);
3692
3693 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3694 return networkRequest;
3695 }
3696
3697 @Override
3698 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3699 PendingIntent operation) {
3700 }
3701
3702 @Override
3703 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003704 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3705 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003706 }
3707
3708 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003709 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003710 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003711 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3712 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003713 }
3714
Robert Greenwalta67be032014-05-16 15:49:14 -07003715 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003716 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003717 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3718 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3719 }
3720
3721 @Override
3722 public void unregisterNetworkFactory(Messenger messenger) {
3723 enforceConnectivityInternalPermission();
3724 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3725 }
3726
3727 private void handleUnregisterNetworkFactory(Messenger messenger) {
3728 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3729 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003730 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003731 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003732 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003733 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003734 }
3735
Robert Greenwalt7b816022014-04-18 15:25:25 -07003736 /**
3737 * NetworkAgentInfo supporting a request by requestId.
3738 * These have already been vetted (their Capabilities satisfy the request)
3739 * and the are the highest scored network available.
3740 * the are keyed off the Requests requestId.
3741 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003742 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003743 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3744 new SparseArray<NetworkAgentInfo>();
3745
Paul Jensen31a94f42015-02-13 14:18:39 -05003746 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3747 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003748 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3749 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003750 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3751 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3752 // there may not be a strict 1:1 correlation between the two.
3753 @GuardedBy("mNetworkForNetId")
3754 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003755
Robert Greenwalt7b816022014-04-18 15:25:25 -07003756 // NetworkAgentInfo keyed off its connecting messenger
3757 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003758 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003759 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3760 new HashMap<Messenger, NetworkAgentInfo>();
3761
Paul Jensen2c311d62014-11-17 12:34:51 -05003762 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003763 private final NetworkRequest mDefaultRequest;
3764
Erik Klineda4bfa82015-04-30 12:58:40 +09003765 // Request used to optionally keep mobile data active even when higher
3766 // priority networks like Wi-Fi are active.
3767 private final NetworkRequest mDefaultMobileDataRequest;
3768
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003769 private NetworkAgentInfo getDefaultNetwork() {
3770 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3771 }
3772
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003773 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003774 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003775 }
3776
Paul Jensen31a94f42015-02-13 14:18:39 -05003777 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003778 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003779 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003780 enforceConnectivityInternalPermission();
3781
Paul Jensen2c311d62014-11-17 12:34:51 -05003782 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3783 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003784 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003785 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3786 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3787 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003788 synchronized (this) {
3789 nai.networkMonitor.systemReady = mSystemReady;
3790 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003791 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003792 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003793 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003794 }
3795
3796 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3797 if (VDBG) log("Got NetworkAgent Messenger");
3798 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003799 synchronized (mNetworkForNetId) {
3800 mNetworkForNetId.put(na.network.netId, na);
3801 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003802 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3803 NetworkInfo networkInfo = na.networkInfo;
3804 na.networkInfo = null;
3805 updateNetworkInfo(na, networkInfo);
3806 }
3807
3808 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3809 LinkProperties newLp = networkAgent.linkProperties;
3810 int netId = networkAgent.network.netId;
3811
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003812 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3813 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003814 if (networkAgent.clatd != null) {
3815 networkAgent.clatd.fixupLinkProperties(oldLp);
3816 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003817
Paul Jensen992f2522014-04-28 10:33:11 -04003818 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003819 updateMtu(newLp, oldLp);
3820 // TODO - figure out what to do for clat
3821// for (LinkProperties lp : newLp.getStackedLinks()) {
3822// updateMtu(lp, null);
3823// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003824 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003825
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003826 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3827 // In L, we used it only when the network had Internet access but provided no DNS servers.
3828 // For now, just disable it, and if disabling it doesn't break things, remove it.
3829 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3830 // NET_CAPABILITY_INTERNET);
3831 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003832 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003833 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3834
Paul Jensen3b759822014-05-13 11:44:01 -04003835 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003836 if (isDefaultNetwork(networkAgent)) {
3837 handleApplyDefaultProxy(newLp.getHttpProxy());
3838 } else {
3839 updateProxy(newLp, oldLp, networkAgent);
3840 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003841 // TODO - move this check to cover the whole function
3842 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003843 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003844 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3845 }
Paul Jensen3b759822014-05-13 11:44:01 -04003846 }
3847
Lorenzo Colitti95439462014-10-09 13:44:48 +09003848 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3849 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3850 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003851
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003852 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003853 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3854 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003855 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003856 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003857 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003858 }
Paul Jensen992f2522014-04-28 10:33:11 -04003859
3860 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3861 CompareResult<String> interfaceDiff = new CompareResult<String>();
3862 if (oldLp != null) {
3863 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3864 } else if (newLp != null) {
3865 interfaceDiff.added = newLp.getAllInterfaceNames();
3866 }
3867 for (String iface : interfaceDiff.added) {
3868 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003869 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003870 mNetd.addInterfaceToNetwork(iface, netId);
3871 } catch (Exception e) {
3872 loge("Exception adding interface: " + e);
3873 }
3874 }
3875 for (String iface : interfaceDiff.removed) {
3876 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003877 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003878 mNetd.removeInterfaceFromNetwork(iface, netId);
3879 } catch (Exception e) {
3880 loge("Exception removing interface: " + e);
3881 }
3882 }
3883 }
3884
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003885 /**
3886 * Have netd update routes from oldLp to newLp.
3887 * @return true if routes changed between oldLp and newLp
3888 */
3889 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003890 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3891 if (oldLp != null) {
3892 routeDiff = oldLp.compareAllRoutes(newLp);
3893 } else if (newLp != null) {
3894 routeDiff.added = newLp.getAllRoutes();
3895 }
3896
3897 // add routes before removing old in case it helps with continuous connectivity
3898
3899 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3900 for (RouteInfo route : routeDiff.added) {
3901 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003902 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003903 try {
3904 mNetd.addRoute(netId, route);
3905 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003906 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3907 loge("Exception in addRoute for non-gateway: " + e);
3908 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003909 }
3910 }
3911 for (RouteInfo route : routeDiff.added) {
3912 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003913 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003914 try {
3915 mNetd.addRoute(netId, route);
3916 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003917 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3918 loge("Exception in addRoute for gateway: " + e);
3919 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003920 }
3921 }
3922
3923 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003924 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003925 try {
3926 mNetd.removeRoute(netId, route);
3927 } catch (Exception e) {
3928 loge("Exception in removeRoute: " + e);
3929 }
3930 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003931 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003932 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003933 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3934 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003935 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003936 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003937 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003938 dnses = new ArrayList();
3939 dnses.add(mDefaultDns);
3940 if (DBG) {
3941 loge("no dns provided for netId " + netId + ", so using defaults");
3942 }
3943 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003944 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003945 try {
3946 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3947 newLp.getDomains());
3948 } catch (Exception e) {
3949 loge("Exception in setDnsServersForNetwork: " + e);
3950 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003951 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3952 if (defaultNai != null && defaultNai.network.netId == netId) {
3953 setDefaultDnsSystemProperties(dnses);
3954 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003955 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003956 } else if (flush) {
3957 try {
3958 mNetd.flushNetworkDnsCache(netId);
3959 } catch (Exception e) {
3960 loge("Exception in flushNetworkDnsCache: " + e);
3961 }
3962 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003963 }
3964 }
3965
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003966 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3967 int last = 0;
3968 for (InetAddress dns : dnses) {
3969 ++last;
3970 String key = "net.dns" + last;
3971 String value = dns.getHostAddress();
3972 SystemProperties.set(key, value);
3973 }
3974 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3975 String key = "net.dns" + i;
3976 SystemProperties.set(key, "");
3977 }
3978 mNumDnsEntries = last;
3979 }
3980
Robert Greenwalt7b816022014-04-18 15:25:25 -07003981 private void updateCapabilities(NetworkAgentInfo networkAgent,
3982 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003983 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3984 synchronized (networkAgent) {
3985 networkAgent.networkCapabilities = networkCapabilities;
3986 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003987 if (networkAgent.lastValidated) {
3988 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
3989 // There's no need to remove the capability if we think the network is unvalidated,
3990 // because NetworkAgents don't set the validated capability.
3991 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003992 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003993 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003994 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003995 }
3996
Paul Jensenc8b9a742014-09-30 15:37:41 -04003997 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3998 for (int i = 0; i < nai.networkRequests.size(); i++) {
3999 NetworkRequest nr = nai.networkRequests.valueAt(i);
4000 // Don't send listening requests to factories. b/17393458
4001 if (!isRequest(nr)) continue;
4002 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4003 }
4004 }
4005
Robert Greenwalt7b816022014-04-18 15:25:25 -07004006 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4007 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004008 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004009 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4010 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004011 }
4012 }
4013
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004014 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4015 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004016 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004017 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004018 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4019 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004020 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004021 sendIntent(nri.mPendingIntent, intent);
4022 }
4023 // else not handled
4024 }
4025
4026 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4027 mPendingIntentWakeLock.acquire();
4028 try {
4029 if (DBG) log("Sending " + pendingIntent);
4030 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4031 } catch (PendingIntent.CanceledException e) {
4032 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4033 mPendingIntentWakeLock.release();
4034 releasePendingNetworkRequest(pendingIntent);
4035 }
4036 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4037 }
4038
4039 @Override
4040 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4041 String resultData, Bundle resultExtras) {
4042 if (DBG) log("Finished sending " + pendingIntent);
4043 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004044 // Release with a delay so the receiving client has an opportunity to put in its
4045 // own request.
4046 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004047 }
4048
Robert Greenwalt9258c642014-03-26 16:47:06 -07004049 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004050 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004051 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004052 Bundle bundle = new Bundle();
4053 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4054 new NetworkRequest(nri.request));
4055 Message msg = Message.obtain();
4056 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4057 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4058 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4059 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004060 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004061 case ConnectivityManager.CALLBACK_LOSING: {
4062 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4063 break;
4064 }
4065 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4066 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4067 new NetworkCapabilities(networkAgent.networkCapabilities));
4068 break;
4069 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004070 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004071 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4072 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004073 break;
4074 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004075 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004076 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004077 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004078 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004079 if (VDBG) {
4080 log("sending notification " + notifyTypeToName(notificationType) +
4081 " for " + nri.request);
4082 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004083 nri.messenger.send(msg);
4084 } catch (RemoteException e) {
4085 // may occur naturally in the race of binder death.
4086 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4087 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004088 }
4089
Paul Jensenc8b9a742014-09-30 15:37:41 -04004090 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4091 for (int i = 0; i < nai.networkRequests.size(); i++) {
4092 NetworkRequest nr = nai.networkRequests.valueAt(i);
4093 // Ignore listening requests.
4094 if (!isRequest(nr)) continue;
4095 loge("Dead network still had at least " + nr);
4096 break;
4097 }
4098 nai.asyncChannel.disconnect();
4099 }
4100
Robert Greenwalt7b816022014-04-18 15:25:25 -07004101 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4102 if (oldNetwork == null) {
4103 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4104 return;
4105 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004106 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4107 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004108 }
4109
Paul Jensen27b02b72014-07-14 12:03:33 -04004110 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004111 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004112 setupDataActivityTracking(newNetwork);
4113 try {
4114 mNetd.setDefaultNetId(newNetwork.network.netId);
4115 } catch (Exception e) {
4116 loge("Exception setting default network :" + e);
4117 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004118 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004119 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004120 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004121 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004122 }
4123
Paul Jensen2161a8e2014-09-11 11:00:39 -04004124 // Handles a network appearing or improving its score.
4125 //
4126 // - Evaluates all current NetworkRequests that can be
4127 // satisfied by newNetwork, and reassigns to newNetwork
4128 // any such requests for which newNetwork is the best.
4129 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004130 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004131 // needed. A network is needed if it is the best network for
4132 // one or more NetworkRequests, or if it is a VPN.
4133 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004134 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004135 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4136 //
4137 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4138 // networks that have no chance (i.e. even if validated)
4139 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004140 //
4141 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4142 // it does not remove NetworkRequests that other Networks could better satisfy.
4143 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4144 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4145 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004146 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004147 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004148 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004149 // torn down if unneeded.
4150 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4151 // performed to tear down unvalidated networks that have no chance (i.e. even if
4152 // validated) of becoming the highest scoring network.
4153 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4154 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004155 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004156 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004157 loge("ERROR: nascent network not validated.");
4158 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004159 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004160 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004161 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004162 if (DBG) log("rematching " + newNetwork.name());
4163 // Find and migrate to this Network any NetworkRequests for
4164 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004165 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004166 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004167 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004168 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4169 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004170 if (DBG) {
4171 log("Network " + newNetwork.name() + " was already satisfying" +
4172 " request " + nri.request.requestId + ". No change.");
4173 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004174 keep = true;
4175 continue;
4176 }
4177
4178 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004179 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004180 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004181 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004182 // This is not a request, it's a callback listener.
4183 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004184 newNetwork.addRequest(nri.request);
4185 continue;
4186 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004187
Robert Greenwalt7b816022014-04-18 15:25:25 -07004188 // next check if it's better than any current network we're using for
4189 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004190 if (VDBG) {
4191 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004192 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4193 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004194 }
4195 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004196 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004197 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004198 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004199 currentNetwork.networkRequests.remove(nri.request.requestId);
4200 currentNetwork.networkLingered.add(nri.request);
4201 affectedNetworks.add(currentNetwork);
4202 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004203 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004204 }
Paul Jensen573a0352015-01-08 10:49:34 -05004205 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004206 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004207 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004208 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004209 // Tell NetworkFactories about the new score, so they can stop
4210 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004211 // TODO - this could get expensive if we have alot of requests for this
4212 // network. Think about if there is a way to reduce this. Push
4213 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004214 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004215 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004216 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004217 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004218 }
4219 }
4220 }
4221 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004222 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004223 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004224 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004225 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4226 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4227 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004228 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004229 }
4230 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004231 if (keep) {
4232 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004233 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004234 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004235 synchronized (ConnectivityService.this) {
4236 // have a new default network, release the transition wakelock in
4237 // a second if it's held. The second pause is to allow apps
4238 // to reconnect over the new network
4239 if (mNetTransitionWakeLock.isHeld()) {
4240 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4241 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4242 mNetTransitionWakeLockSerialNumber, 0),
4243 1000);
4244 }
4245 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004246 }
4247
4248 // do this after the default net is switched, but
4249 // before LegacyTypeTracker sends legacy broadcasts
4250 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4251
4252 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004253 // Maintain the illusion: since the legacy API only
4254 // understands one network at a time, we must pretend
4255 // that the current default network disconnected before
4256 // the new one connected.
4257 if (oldDefaultNetwork != null) {
4258 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004259 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004260 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004261 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004262 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4263 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004264 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004265
4266 // Notify battery stats service about this network, both the normal
4267 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004268 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004269 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004270 final IBatteryStats bs = BatteryStatsService.getService();
4271 final int type = newNetwork.networkInfo.getType();
4272
4273 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4274 bs.noteNetworkInterfaceType(baseIface, type);
4275 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4276 final String stackedIface = stacked.getInterfaceName();
4277 bs.noteNetworkInterfaceType(stackedIface, type);
4278 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4279 }
4280 } catch (RemoteException ignored) {
4281 }
4282
Robert Greenwalt152ed372014-12-17 17:19:53 -08004283 // This has to happen after the notifyNetworkCallbacks as that tickles each
4284 // ConnectivityManager instance so that legacy requests correctly bind dns
4285 // requests to this network. The legacy users are listening for this bcast
4286 // and will generally do a dns request so they can ensureRouteToHost and if
4287 // they do that before the callbacks happen they'll use the default network.
4288 //
4289 // TODO: Is there still a race here? We send the broadcast
4290 // after sending the callback, but if the app can receive the
4291 // broadcast before the callback, it might still break.
4292 //
4293 // This *does* introduce a race where if the user uses the new api
4294 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4295 // they may get old info. Reverse this after the old startUsing api is removed.
4296 // This is on top of the multiple intent sequencing referenced in the todo above.
4297 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4298 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4299 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4300 // legacy type tracker filters out repeat adds
4301 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4302 }
4303 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004304
4305 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4306 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4307 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4308 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4309 if (newNetwork.isVPN()) {
4310 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4311 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004312 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004313 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004314 // validated (and get evaluated against peers, one losing here), or get reaped (see
4315 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4316 // network. Networks that have been up for a while and are validated should be torn
4317 // down via the lingering process so communication on that network is given time to
4318 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004319 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004320 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004321 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004322 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4323 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004324 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004325 if (DBG) log("Reaping " + nai.name());
4326 teardownUnneededNetwork(nai);
4327 }
4328 }
4329 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004330 }
4331
Paul Jensen2161a8e2014-09-11 11:00:39 -04004332 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4333 // being disconnected.
4334 // If only one Network's score or capabilities have been modified since the last time
4335 // this function was called, pass this Network in via the "changed" arugment, otherwise
4336 // pass null.
4337 // If only one Network has been changed but its NetworkCapabilities have not changed,
4338 // pass in the Network's score (from getCurrentScore()) prior to the change via
4339 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4340 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4341 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4342 // to avoid the slowness. It is not simply enough to process just "changed", for
4343 // example in the case where "changed"'s score decreases and another network should begin
4344 // satifying a NetworkRequest that "changed" currently satisfies.
4345
4346 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4347 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4348 // rematchNetworkAndRequests() handles.
4349 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004350 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4351 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004352 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004353 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4354 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4355 NascentState.NOT_JUST_VALIDATED,
4356 // Only reap the last time through the loop. Reaping before all rematching
4357 // is complete could incorrectly teardown a network that hasn't yet been
4358 // rematched.
4359 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4360 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004361 }
4362 }
4363 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004364
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004365 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004366 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004367 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004368 // For now only update icons for default connection.
4369 // TODO: Update WiFi and cellular icons separately. b/17237507
4370 if (!isDefaultNetwork(nai)) return;
4371
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004372 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004373 // Don't repeat publish.
4374 if (newInetCondition == mDefaultInetConditionPublished) return;
4375
4376 mDefaultInetConditionPublished = newInetCondition;
4377 sendInetConditionBroadcast(nai.networkInfo);
4378 }
4379
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004380 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4381 if (mLockdownTracker != null) {
4382 if (nai != null && nai.isVPN()) {
4383 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4384 } else {
4385 mLockdownTracker.onNetworkInfoChanged();
4386 }
4387 }
4388 }
4389
Robert Greenwalt7b816022014-04-18 15:25:25 -07004390 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4391 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004392 NetworkInfo oldInfo = null;
4393 synchronized (networkAgent) {
4394 oldInfo = networkAgent.networkInfo;
4395 networkAgent.networkInfo = newInfo;
4396 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004397 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398
4399 if (oldInfo != null && oldInfo.getState() == state) {
4400 if (VDBG) log("ignoring duplicate network state non-change");
4401 return;
4402 }
4403 if (DBG) {
4404 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4405 (oldInfo == null ? "null" : oldInfo.getState()) +
4406 " to " + state);
4407 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004408
Paul Jenseneec75412014-08-04 12:21:19 -04004409 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004410 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004411 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004412 if (networkAgent.isVPN()) {
4413 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004414 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4415 (networkAgent.networkMisc == null ||
4416 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004417 } else {
4418 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4419 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004420 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004421 loge("Error creating network " + networkAgent.network.netId + ": "
4422 + e.getMessage());
4423 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004424 }
Paul Jenseneec75412014-08-04 12:21:19 -04004425 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004426 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004427 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004428
Paul Jensenca8f16a2014-05-09 12:47:55 -04004429 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004430 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004431
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004432 if (networkAgent.isVPN()) {
4433 // Temporarily disable the default proxy (not global).
4434 synchronized (mProxyLock) {
4435 if (!mDefaultProxyDisabled) {
4436 mDefaultProxyDisabled = true;
4437 if (mGlobalProxy == null && mDefaultProxy != null) {
4438 sendProxyBroadcast(null);
4439 }
4440 }
4441 }
4442 // TODO: support proxy per network.
4443 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004444
Paul Jensen2161a8e2014-09-11 11:00:39 -04004445 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004446 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4447 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004448
4449 // This has to happen after matching the requests, because callbacks are just requests.
4450 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004451 } else if (state == NetworkInfo.State.DISCONNECTED ||
4452 state == NetworkInfo.State.SUSPENDED) {
4453 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004454 if (networkAgent.isVPN()) {
4455 synchronized (mProxyLock) {
4456 if (mDefaultProxyDisabled) {
4457 mDefaultProxyDisabled = false;
4458 if (mGlobalProxy == null && mDefaultProxy != null) {
4459 sendProxyBroadcast(mDefaultProxy);
4460 }
4461 }
4462 }
4463 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004464 }
4465 }
4466
Robert Greenwaltac96c522014-06-03 16:43:57 -07004467 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4468 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004469 if (score < 0) {
4470 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4471 "). Bumping score to min of 0");
4472 score = 0;
4473 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004474
Paul Jensen2161a8e2014-09-11 11:00:39 -04004475 final int oldScore = nai.getCurrentScore();
4476 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004477
Paul Jensen57a767f2014-11-19 13:01:46 -05004478 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004479
Paul Jensenc8b9a742014-09-30 15:37:41 -04004480 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004481 }
4482
Robert Greenwalt9258c642014-03-26 16:47:06 -07004483 // notify only this one new request of the current state
4484 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4485 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4486 // TODO - read state from monitor to decide what to send.
4487// if (nai.networkMonitor.isLingering()) {
4488// notifyType = NetworkCallbacks.LOSING;
4489// } else if (nai.networkMonitor.isEvaluating()) {
4490// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4491// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004492 if (nri.mPendingIntent == null) {
4493 callCallbackForRequest(nri, nai, notifyType);
4494 } else {
4495 sendPendingIntentForRequest(nri, nai, notifyType);
4496 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004497 }
4498
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004499 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004500 // The NetworkInfo we actually send out has no bearing on the real
4501 // state of affairs. For example, if the default connection is mobile,
4502 // and a request for HIPRI has just gone away, we need to pretend that
4503 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4504 // the state to DISCONNECTED, even though the network is of type MOBILE
4505 // and is still connected.
4506 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4507 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004508 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004509 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004510 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004511 } else {
Feixiong Zhang376133f2015-06-01 18:07:58 -07004512 info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004513 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4514 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4515 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4516 if (info.isFailover()) {
4517 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4518 nai.networkInfo.setFailover(false);
4519 }
4520 if (info.getReason() != null) {
4521 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4522 }
4523 if (info.getExtraInfo() != null) {
4524 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4525 }
4526 NetworkAgentInfo newDefaultAgent = null;
4527 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4528 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4529 if (newDefaultAgent != null) {
4530 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4531 newDefaultAgent.networkInfo);
4532 } else {
4533 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4534 }
4535 }
4536 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4537 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004538 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004539 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004540 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004541 }
4542 }
4543 }
4544
Robert Greenwalt7b816022014-04-18 15:25:25 -07004545 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004546 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004547 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004548 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4549 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4550 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004551 if (nri.mPendingIntent == null) {
4552 callCallbackForRequest(nri, networkAgent, notifyType);
4553 } else {
4554 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4555 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004556 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004557 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004558
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004559 private String notifyTypeToName(int notifyType) {
4560 switch (notifyType) {
4561 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4562 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4563 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4564 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4565 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4566 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4567 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4568 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4569 }
4570 return "UNKNOWN";
4571 }
4572
Jeff Sharkey69736342014-12-08 14:50:12 -08004573 /**
4574 * Notify other system services that set of active ifaces has changed.
4575 */
4576 private void notifyIfacesChanged() {
4577 try {
4578 mStatsService.forceUpdateIfaces();
4579 } catch (Exception ignored) {
4580 }
4581 }
4582
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004583 @Override
4584 public boolean addVpnAddress(String address, int prefixLength) {
4585 throwIfLockdownEnabled();
4586 int user = UserHandle.getUserId(Binder.getCallingUid());
4587 synchronized (mVpns) {
4588 return mVpns.get(user).addAddress(address, prefixLength);
4589 }
4590 }
4591
4592 @Override
4593 public boolean removeVpnAddress(String address, int prefixLength) {
4594 throwIfLockdownEnabled();
4595 int user = UserHandle.getUserId(Binder.getCallingUid());
4596 synchronized (mVpns) {
4597 return mVpns.get(user).removeAddress(address, prefixLength);
4598 }
4599 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004600
4601 @Override
4602 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4603 throwIfLockdownEnabled();
4604 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004605 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004606 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004607 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004608 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004609 if (success) {
4610 notifyIfacesChanged();
4611 }
4612 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004613 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004614
4615 @Override
4616 public void factoryReset() {
4617 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004618
4619 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4620 return;
4621 }
4622
Robin Lee3b3dd942015-05-12 18:14:58 +01004623 final int userId = UserHandle.getCallingUserId();
4624
Stuart Scottf1fb3972015-04-02 18:00:02 -07004625 // Turn airplane mode off
4626 setAirplaneMode(false);
4627
Stuart Scotte3e314d2015-04-20 14:07:45 -07004628 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4629 // Untether
4630 for (String tether : getTetheredIfaces()) {
4631 untether(tether);
4632 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004633 }
4634
Stuart Scotte3e314d2015-04-20 14:07:45 -07004635 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4636 // Turn VPN off
4637 VpnConfig vpnConfig = getVpnConfig(userId);
4638 if (vpnConfig != null) {
4639 if (vpnConfig.legacy) {
4640 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4641 } else {
4642 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4643 // in the future without user intervention.
4644 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004645
Stuart Scotte3e314d2015-04-20 14:07:45 -07004646 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4647 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004648 }
4649 }
4650 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004651}