blob: 8716101f4072301b5db558a372f41e290cff6f42 [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;
Erik Kline379747a2015-06-05 17:47:34 +0900115import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900116import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700117import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400118import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400119import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700120import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800121import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700122import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700123import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700124import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700125import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700126import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700127
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import org.xmlpull.v1.XmlPullParser;
129import org.xmlpull.v1.XmlPullParserException;
130
131import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800132import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700133import java.io.FileNotFoundException;
134import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700135import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700137import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700138import java.net.InetAddress;
139import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700140import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700141import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700142import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700143import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700144import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500145import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700146import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700147import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700148import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700149import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800150
151/**
152 * @hide
153 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800154public class ConnectivityService extends IConnectivityManager.Stub
155 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700156 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700158 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700159 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800160
Jake Hamby786e71a2014-02-06 14:43:50 -0800161 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700162
Jeff Sharkey899223b2012-08-04 15:24:58 -0700163 // TODO: create better separation between radio types and network types
164
Robert Greenwalt42acef32009-08-12 16:08:25 -0700165 // how long to wait before switching back to a radio's default network
166 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
167 // system property that can override the above value
168 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
169 "android.telephony.apn-restore";
170
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900171 // How long to wait before putting up a "This network doesn't have an Internet connection,
172 // connect anyway?" dialog after the user selects a network that doesn't validate.
173 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
174
Jeremy Joslin79294842014-12-03 17:15:28 -0800175 // How long to delay to removal of a pending intent based request.
176 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
177 private final int mReleasePendingIntentDelayMs;
178
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800179 private Tethering mTethering;
180
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700181 private final PermissionMonitor mPermissionMonitor;
182
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700183 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700184
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700185 @GuardedBy("mVpns")
186 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700187
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700188 private boolean mLockdownEnabled;
189 private LockdownVpnTracker mLockdownTracker;
190
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700191 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
192 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700193 /** Currently active network rules by UID. */
194 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700195 /** Set of ifaces that are costly. */
196 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700197
Erik Klineda4bfa82015-04-30 12:58:40 +0900198 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700200 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700201 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800203 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700206 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700208 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800209 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700211
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700212 private String mCurrentTcpBufferSizes;
213
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700214 private static final int ENABLED = 1;
215 private static final int DISABLED = 0;
216
Paul Jensenb10e37f2014-11-25 12:33:08 -0500217 // Arguments to rematchNetworkAndRequests()
218 private enum NascentState {
219 // Indicates a network was just validated for the first time. If the network is found to
220 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
221 JUST_VALIDATED,
222 // Indicates a network was not validated for the first time immediately prior to this call.
223 NOT_JUST_VALIDATED
224 };
225 private enum ReapUnvalidatedNetworks {
226 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
227 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
228 // known that there may be unvalidated networks that could potentially be reaped, and when
229 // all networks have been rematched against all NetworkRequests.
230 REAP,
231 // Don't reap unvalidated networks. This should be passed when it's known that there are
232 // no unvalidated networks that could potentially be reaped, and when some networks have
233 // not yet been rematched against all NetworkRequests.
234 DONT_REAP
235 };
236
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700238 * used internally to change our mobile data enabled flag
239 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700240 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241
242 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700244 * from one net to another. Clear happens when we get a new
245 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
246 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700248 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250 /**
251 * used internally to reload global proxy settings
252 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700253 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700255 /**
Wink Saville628b0852011-08-04 15:01:58 -0700256 * used internally to send a sticky broadcast delayed.
257 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700258 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700259
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700260 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400261 * PAC manager has received new port.
262 */
263 private static final int EVENT_PROXY_HAS_CHANGED = 16;
264
Robert Greenwalte049c232014-04-11 15:53:27 -0700265 /**
266 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700267 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700268 */
269 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
270
Robert Greenwalt7b816022014-04-18 15:25:25 -0700271 /**
272 * used internally when registering NetworkAgents
273 * obj = Messenger
274 */
275 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
276
Robert Greenwalt9258c642014-03-26 16:47:06 -0700277 /**
278 * used to add a network request
279 * includes a NetworkRequestInfo
280 */
281 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
282
283 /**
284 * indicates a timeout period is over - check if we had a network yet or not
285 * and if not, call the timeout calback (but leave the request live until they
286 * cancel it.
287 * includes a NetworkRequestInfo
288 */
289 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
290
291 /**
292 * used to add a network listener - no request
293 * includes a NetworkRequestInfo
294 */
295 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
296
297 /**
298 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400299 * arg1 = UID of caller
300 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 */
302 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
303
Robert Greenwalta67be032014-05-16 15:49:14 -0700304 /**
305 * used internally when registering NetworkFactories
306 * obj = Messenger
307 */
308 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
309
Robert Greenwalt27711812014-06-25 16:45:57 -0700310 /**
311 * used internally to expire a wakelock when transitioning
312 * from one net to another. Expire happens when we fail to find
313 * a new network (typically after 1 minute) -
314 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
315 * a replacement network.
316 */
317 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
318
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700319 /**
320 * Used internally to indicate the system is ready.
321 */
322 private static final int EVENT_SYSTEM_READY = 25;
323
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800324 /**
325 * used to add a network request with a pending intent
326 * includes a NetworkRequestInfo
327 */
328 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
329
330 /**
331 * used to remove a pending intent and its associated network request.
332 * arg1 = UID of caller
333 * obj = PendingIntent
334 */
335 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
336
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900337 /**
338 * used to specify whether a network should be used even if unvalidated.
339 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
340 * arg2 = whether to remember this choice in the future (1 or 0)
341 * obj = network
342 */
343 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
344
345 /**
346 * used to ask the user to confirm a connection to an unvalidated network.
347 * obj = network
348 */
349 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700350
Erik Klineda4bfa82015-04-30 12:58:40 +0900351 /**
352 * used internally to (re)configure mobile data always-on settings.
353 */
354 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
355
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700356 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700357 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700358 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700359 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700360
Mike Lockwood0f79b542009-08-14 14:18:49 -0400361 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800362 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400363
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700364 private PowerManager.WakeLock mNetTransitionWakeLock;
365 private String mNetTransitionWakeLockCausedBy = "";
366 private int mNetTransitionWakeLockSerialNumber;
367 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800368 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700369
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700370 private InetAddress mDefaultDns;
371
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700372 // used in DBG mode to track inet condition reports
373 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
374 private ArrayList mInetLog;
375
Robert Greenwalt434203a2010-10-11 16:00:27 -0700376 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400377 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700378 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700379 private boolean mDefaultProxyDisabled = false;
380
Robert Greenwalt434203a2010-10-11 16:00:27 -0700381 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400382 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700383
Jason Monk602b2322013-07-03 17:04:33 -0400384 private PacManager mPacManager = null;
385
Erik Klineda4bfa82015-04-30 12:58:40 +0900386 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400388 private UserManager mUserManager;
389
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700390 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700391 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700392
Robert Greenwalt50393202011-06-21 17:26:14 -0700393 // the set of network types that can only be enabled by system/sig apps
394 List mProtectedNetworks;
395
John Spurlockbf991a82013-06-24 14:20:23 -0400396 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700397
Wink Savilleab9321d2013-06-29 21:10:57 -0700398 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400399
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700400 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
401 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700402 private final static int MAX_NET_ID = 65535;
403 private int mNextNetId = MIN_NET_ID;
404
Robert Greenwalt34524f02014-05-18 16:22:10 -0700405 // sequence number of NetworkRequests
406 private int mNextNetworkRequestId = 1;
407
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700408 /**
409 * Implements support for the legacy "one network per network type" model.
410 *
411 * We used to have a static array of NetworkStateTrackers, one for each
412 * network type, but that doesn't work any more now that we can have,
413 * for example, more that one wifi network. This class stores all the
414 * NetworkAgentInfo objects that support a given type, but the legacy
415 * API will only see the first one.
416 *
417 * It serves two main purposes:
418 *
419 * 1. Provide information about "the network for a given type" (since this
420 * API only supports one).
421 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
422 * the first network for a given type changes, or if the default network
423 * changes.
424 */
425 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900426
427 private static final boolean DBG = true;
428 private static final boolean VDBG = false;
429 private static final String TAG = "CSLegacyTypeTracker";
430
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700431 /**
432 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
433 * Each list holds references to all NetworkAgentInfos that are used to
434 * satisfy requests for that network type.
435 *
436 * This array is built out at startup such that an unsupported network
437 * doesn't get an ArrayList instance, making this a tristate:
438 * unsupported, supported but not active and active.
439 *
440 * The actual lists are populated when we scan the network types that
441 * are supported on this device.
442 */
443 private ArrayList<NetworkAgentInfo> mTypeLists[];
444
445 public LegacyTypeTracker() {
446 mTypeLists = (ArrayList<NetworkAgentInfo>[])
447 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
448 }
449
450 public void addSupportedType(int type) {
451 if (mTypeLists[type] != null) {
452 throw new IllegalStateException(
453 "legacy list for type " + type + "already initialized");
454 }
455 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
456 }
457
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700458 public boolean isTypeSupported(int type) {
459 return isNetworkTypeValid(type) && mTypeLists[type] != null;
460 }
461
462 public NetworkAgentInfo getNetworkForType(int type) {
463 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
464 return mTypeLists[type].get(0);
465 } else {
466 return null;
467 }
468 }
469
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900470 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
471 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900472 if (DBG) {
473 log("Sending " + (connected ? "connected" : "disconnected") +
474 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900475 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900476 }
477 }
478
479 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700480 public void add(int type, NetworkAgentInfo nai) {
481 if (!isTypeSupported(type)) {
482 return; // Invalid network type.
483 }
484 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
485
486 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
487 if (list.contains(nai)) {
488 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
489 return;
490 }
491
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900492 list.add(nai);
493
494 // 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 +0900495 final boolean isDefaultNetwork = isDefaultNetwork(nai);
496 if (list.size() == 1 || isDefaultNetwork) {
497 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700498 sendLegacyNetworkBroadcast(nai, true, type);
499 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700500 }
501
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900503 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900504 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
505 if (list == null || list.isEmpty()) {
506 return;
507 }
508
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900509 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900510
511 if (!list.remove(nai)) {
512 return;
513 }
514
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900515 if (wasFirstNetwork || wasDefault) {
516 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900517 sendLegacyNetworkBroadcast(nai, false, type);
518 }
519
520 if (!list.isEmpty() && wasFirstNetwork) {
521 if (DBG) log("Other network available for type " + type +
522 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900523 final NetworkAgentInfo replacement = list.get(0);
524 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
525 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526 }
527 }
528
529 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900530 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
531 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700532 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700534 }
535 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700536
Lorenzo Colittia793a672014-07-31 23:20:17 +0900537 private String naiToString(NetworkAgentInfo nai) {
538 String name = (nai != null) ? nai.name() : "null";
539 String state = (nai.networkInfo != null) ?
540 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
541 "???/???";
542 return name + " " + state;
543 }
544
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700545 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900546 pw.println("mLegacyTypeTracker:");
547 pw.increaseIndent();
548 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700549 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900550 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700551 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900552 pw.println();
553 pw.println("Current state:");
554 pw.increaseIndent();
555 for (int type = 0; type < mTypeLists.length; type++) {
556 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
557 for (NetworkAgentInfo nai : mTypeLists[type]) {
558 pw.println(type + " " + naiToString(nai));
559 }
560 }
561 pw.decreaseIndent();
562 pw.decreaseIndent();
563 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700564 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900565
566 // This class needs its own log method because it has a different TAG.
567 private void log(String s) {
568 Slog.d(TAG, s);
569 }
570
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700571 }
572 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
573
Jeff Sharkey899223b2012-08-04 15:24:58 -0700574 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700575 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800576 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800577
Erik Klineda4bfa82015-04-30 12:58:40 +0900578 mDefaultRequest = createInternetRequestForTransport(-1);
579 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
580 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
581
582 mDefaultMobileDataRequest = createInternetRequestForTransport(
583 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700584
Wink Savillebb08caf2010-09-02 19:23:52 -0700585 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
586 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700587 mHandler = new InternalHandler(handlerThread.getLooper());
588 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700589
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800590 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800591 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
592 String id = Settings.Secure.getString(context.getContentResolver(),
593 Settings.Secure.ANDROID_ID);
594 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700595 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800596 SystemProperties.set("net.hostname", name);
597 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800598 }
599
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700600 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700601 String dns = Settings.Global.getString(context.getContentResolver(),
602 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700603 if (dns == null || dns.length() == 0) {
604 dns = context.getResources().getString(
605 com.android.internal.R.string.config_default_dns_server);
606 }
607 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800608 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
609 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800610 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700611 }
612
Jeremy Joslin79294842014-12-03 17:15:28 -0800613 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
614 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
615
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700616 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700617 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800618 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700619 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700620 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700621 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700622
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700623 try {
624 mPolicyManager.registerListener(mPolicyListener);
625 } catch (RemoteException e) {
626 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700627 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700628 }
629
630 final PowerManager powerManager = (PowerManager) context.getSystemService(
631 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700632 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
633 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
634 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800635 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700636
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700637 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700638
Wink Saville51f456f2013-04-23 14:26:51 -0700639 // TODO: What is the "correct" way to do determine if this is a wifi only device?
640 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
641 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700642 String[] naStrings = context.getResources().getStringArray(
643 com.android.internal.R.array.networkAttributes);
644 for (String naString : naStrings) {
645 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700646 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700647 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700648 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800649 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700650 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700651 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700652 }
Wink Saville51f456f2013-04-23 14:26:51 -0700653 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
654 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
655 n.type);
656 continue;
657 }
Wink Saville975c8482011-04-07 14:23:45 -0700658 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800659 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700660 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700661 continue;
662 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700663 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700664
Wink Saville975c8482011-04-07 14:23:45 -0700665 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700666 mNetworksDefined++;
667 } catch(Exception e) {
668 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700669 }
670 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700671
672 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
673 if (mNetConfigs[TYPE_VPN] == null) {
674 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
675 // don't need to add TYPE_VPN to mNetConfigs.
676 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
677 mNetworksDefined++; // used only in the log() statement below.
678 }
679
Wink Saville5e56bc52013-07-29 15:00:57 -0700680 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700681
Robert Greenwalt50393202011-06-21 17:26:14 -0700682 mProtectedNetworks = new ArrayList<Integer>();
683 int[] protectedNetworks = context.getResources().getIntArray(
684 com.android.internal.R.array.config_protectedNetworks);
685 for (int p : protectedNetworks) {
686 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
687 mProtectedNetworks.add(p);
688 } else {
689 if (DBG) loge("Ignoring protectedNetwork " + p);
690 }
691 }
692
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700693 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
694 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700695
Robert Greenwaltfab501672014-07-23 11:44:01 -0700696 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800697
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700698 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
699
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700700 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700701 IntentFilter intentFilter = new IntentFilter();
702 intentFilter.addAction(Intent.ACTION_USER_STARTING);
703 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
704 mContext.registerReceiverAsUser(
705 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900706
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700707 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700708 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700709 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700710 } catch (RemoteException e) {
711 loge("Error registering observer :" + e);
712 }
713
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700714 if (DBG) {
715 mInetLog = new ArrayList();
716 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700717
Erik Klineda4bfa82015-04-30 12:58:40 +0900718 mSettingsObserver = new SettingsObserver(mContext, mHandler);
719 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800720
John Spurlockbf991a82013-06-24 14:20:23 -0400721 mDataConnectionStats = new DataConnectionStats(mContext);
722 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400723
Jason Monkdecd2952013-10-10 14:02:51 -0400724 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700725
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400726 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700728
Erik Klineda4bfa82015-04-30 12:58:40 +0900729 private NetworkRequest createInternetRequestForTransport(int transportType) {
730 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900731 netCap.addCapability(NET_CAPABILITY_INTERNET);
732 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900733 if (transportType > -1) {
734 netCap.addTransportType(transportType);
735 }
736 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
737 }
738
739 private void handleMobileDataAlwaysOn() {
740 final boolean enable = (Settings.Global.getInt(
741 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
742 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
743 if (enable == isEnabled) {
744 return; // Nothing to do.
745 }
746
747 if (enable) {
748 handleRegisterNetworkRequest(new NetworkRequestInfo(
749 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
750 } else {
751 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
752 }
753 }
754
755 private void registerSettingsCallbacks() {
756 // Watch for global HTTP proxy changes.
757 mSettingsObserver.observe(
758 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
759 EVENT_APPLY_GLOBAL_HTTP_PROXY);
760
761 // Watch for whether or not to keep mobile data always on.
762 mSettingsObserver.observe(
763 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
764 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
765 }
766
Robert Greenwalt34524f02014-05-18 16:22:10 -0700767 private synchronized int nextNetworkRequestId() {
768 return mNextNetworkRequestId++;
769 }
770
Paul Jensen31a94f42015-02-13 14:18:39 -0500771 private int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400772 synchronized (mNetworkForNetId) {
773 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
774 int netId = mNextNetId;
775 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
776 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500777 if (!mNetIdInUse.get(netId)) {
778 mNetIdInUse.put(netId, true);
779 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400780 }
781 }
782 }
783 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700784 }
785
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800786 private NetworkState getFilteredNetworkState(int networkType, int uid) {
787 NetworkInfo info = null;
788 LinkProperties lp = null;
789 NetworkCapabilities nc = null;
790 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800791 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800792
793 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
794 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
795 if (nai != null) {
796 synchronized (nai) {
797 info = new NetworkInfo(nai.networkInfo);
798 lp = new LinkProperties(nai.linkProperties);
799 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400800 // Network objects are outwardly immutable so there is no point to duplicating.
801 // Duplicating also precludes sharing socket factories and connection pools.
802 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800803 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800804 }
805 info.setType(networkType);
806 } else {
807 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
808 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
809 info.setIsAvailable(true);
810 lp = new LinkProperties();
811 nc = new NetworkCapabilities();
812 network = null;
813 }
814 info = getFilteredNetworkInfo(info, lp, uid);
815 }
816
Jeff Sharkey32566012014-12-02 18:30:14 -0800817 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400818 }
819
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800820 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
821 if (network == null) {
822 return null;
823 }
824 synchronized (mNetworkForNetId) {
825 return mNetworkForNetId.get(network.netId);
826 }
827 };
828
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900829 private Network[] getVpnUnderlyingNetworks(int uid) {
830 if (!mLockdownEnabled) {
831 int user = UserHandle.getUserId(uid);
832 synchronized (mVpns) {
833 Vpn vpn = mVpns.get(user);
834 if (vpn != null && vpn.appliesToUid(uid)) {
835 return vpn.getUnderlyingNetworks();
836 }
837 }
838 }
839 return null;
840 }
841
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800842 private NetworkState getUnfilteredActiveNetworkState(int uid) {
843 NetworkInfo info = null;
844 LinkProperties lp = null;
845 NetworkCapabilities nc = null;
846 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800847 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800848
849 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800850
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900851 final Network[] networks = getVpnUnderlyingNetworks(uid);
852 if (networks != null) {
853 // getUnderlyingNetworks() returns:
854 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
855 // empty array => the VPN explicitly said "no default network".
856 // non-empty array => the VPN specified one or more default networks; we use the
857 // first one.
858 if (networks.length > 0) {
859 nai = getNetworkAgentInfoForNetwork(networks[0]);
860 } else {
861 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800862 }
863 }
864
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800865 if (nai != null) {
866 synchronized (nai) {
867 info = new NetworkInfo(nai.networkInfo);
868 lp = new LinkProperties(nai.linkProperties);
869 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400870 // Network objects are outwardly immutable so there is no point to duplicating.
871 // Duplicating also precludes sharing socket factories and connection pools.
872 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800873 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800874 }
875 }
876
Jeff Sharkey32566012014-12-02 18:30:14 -0800877 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400878 }
879
880 /**
881 * Check if UID should be blocked from using the network with the given LinkProperties.
882 */
883 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700884 final boolean networkCostly;
885 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700886
Robert Greenwalt12e67352014-05-13 21:41:06 -0700887 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700888 synchronized (mRulesLock) {
889 networkCostly = mMeteredIfaces.contains(iface);
890 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700891 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700892
Amith Yamasani15e472352015-04-24 19:06:07 -0700893 if ((uidRules & RULE_REJECT_ALL) != 0
894 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700895 return true;
896 }
897
898 // no restrictive rules; network is visible
899 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700900 }
901
902 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700903 * Return a filtered {@link NetworkInfo}, potentially marked
904 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800905 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700906 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800907 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
908 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400909 // network is blocked; clone and override state
910 info = new NetworkInfo(info);
911 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900912 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900913 log("returning Blocked NetworkInfo for ifname=" +
914 lp.getInterfaceName() + ", uid=" + uid);
915 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700916 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800917 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700918 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900919 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700920 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700921 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700922 }
923
924 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 * Return NetworkInfo for the active (i.e., connected) network interface.
926 * It is assumed that at most one network is active at a time. If more
927 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700928 * @return the info for the active network, or {@code null} if none is
929 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700931 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700933 enforceAccessPermission();
934 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935 NetworkState state = getUnfilteredActiveNetworkState(uid);
936 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 }
938
Paul Jensen31a94f42015-02-13 14:18:39 -0500939 @Override
940 public Network getActiveNetwork() {
941 enforceAccessPermission();
942 final int uid = Binder.getCallingUid();
943 final int user = UserHandle.getUserId(uid);
944 int vpnNetId = NETID_UNSET;
945 synchronized (mVpns) {
946 final Vpn vpn = mVpns.get(user);
947 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
948 }
949 NetworkAgentInfo nai;
950 if (vpnNetId != NETID_UNSET) {
951 synchronized (mNetworkForNetId) {
952 nai = mNetworkForNetId.get(vpnNetId);
953 }
954 if (nai != null) return nai.network;
955 }
956 nai = getDefaultNetwork();
957 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
958 return nai != null ? nai.network : null;
959 }
960
Wink Saville948282b2013-08-29 08:55:16 -0700961 /**
962 * Find the first Provisioning network.
963 *
964 * @return NetworkInfo or null if none.
965 */
966 private NetworkInfo getProvisioningNetworkInfo() {
967 enforceAccessPermission();
968
969 // Find the first Provisioning Network
970 NetworkInfo provNi = null;
971 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700972 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700973 provNi = ni;
974 break;
975 }
976 }
977 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
978 return provNi;
979 }
980
981 /**
982 * Find the first Provisioning network or the ActiveDefaultNetwork
983 * if there is no Provisioning network
984 *
985 * @return NetworkInfo or null if none.
986 */
987 @Override
988 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
989 enforceAccessPermission();
990
991 NetworkInfo provNi = getProvisioningNetworkInfo();
992 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700994 }
995 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
996 return provNi;
997 }
998
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700999 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1000 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001001 final int uid = Binder.getCallingUid();
1002 NetworkState state = getUnfilteredActiveNetworkState(uid);
1003 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001004 }
1005
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001006 @Override
1007 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1008 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001009 NetworkState state = getUnfilteredActiveNetworkState(uid);
1010 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001011 }
1012
1013 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 public NetworkInfo getNetworkInfo(int networkType) {
1015 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001016 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001017 if (getVpnUnderlyingNetworks(uid) != null) {
1018 // A VPN is active, so we may need to return one of its underlying networks. This
1019 // information is not available in LegacyTypeTracker, so we have to get it from
1020 // getUnfilteredActiveNetworkState.
1021 NetworkState state = getUnfilteredActiveNetworkState(uid);
1022 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1023 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1024 }
1025 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001026 NetworkState state = getFilteredNetworkState(networkType, uid);
1027 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 }
1029
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001030 @Override
1031 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1032 enforceAccessPermission();
1033 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001034 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001035 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1036 if (nai != null) {
1037 synchronized (nai) {
1038 info = new NetworkInfo(nai.networkInfo);
1039 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001040 }
1041 }
1042 return info;
1043 }
1044
1045 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 public NetworkInfo[] getAllNetworkInfo() {
1047 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001048 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001049 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1050 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001051 NetworkInfo info = getNetworkInfo(networkType);
1052 if (info != null) {
1053 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001056 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001059 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001060 public Network getNetworkForType(int networkType) {
1061 enforceAccessPermission();
1062 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001063 NetworkState state = getFilteredNetworkState(networkType, uid);
1064 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1065 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001066 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001067 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001068 }
1069
1070 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001071 public Network[] getAllNetworks() {
1072 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001073 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001074 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001075 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001076 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001077 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001078 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001079 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001080 }
1081
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001082 @Override
1083 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1084 // The basic principle is: if an app's traffic could possibly go over a
1085 // network, without the app doing anything multinetwork-specific,
1086 // (hence, by "default"), then include that network's capabilities in
1087 // the array.
1088 //
1089 // In the normal case, app traffic only goes over the system's default
1090 // network connection, so that's the only network returned.
1091 //
1092 // With a VPN in force, some app traffic may go into the VPN, and thus
1093 // over whatever underlying networks the VPN specifies, while other app
1094 // traffic may go over the system default network (e.g.: a split-tunnel
1095 // VPN, or an app disallowed by the VPN), so the set of networks
1096 // returned includes the VPN's underlying networks and the system
1097 // default.
1098 enforceAccessPermission();
1099
1100 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1101
1102 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001103 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001104 if (nc != null) {
1105 result.put(nai.network, nc);
1106 }
1107
1108 if (!mLockdownEnabled) {
1109 synchronized (mVpns) {
1110 Vpn vpn = mVpns.get(userId);
1111 if (vpn != null) {
1112 Network[] networks = vpn.getUnderlyingNetworks();
1113 if (networks != null) {
1114 for (Network network : networks) {
1115 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001116 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001117 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001118 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001119 }
1120 }
1121 }
1122 }
1123 }
1124 }
1125
1126 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1127 out = result.values().toArray(out);
1128 return out;
1129 }
1130
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001131 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001132 public boolean isNetworkSupported(int networkType) {
1133 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001134 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001135 }
1136
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001137 /**
1138 * Return LinkProperties for the active (i.e., connected) default
1139 * network interface. It is assumed that at most one default network
1140 * is active at a time. If more than one is active, it is indeterminate
1141 * which will be returned.
1142 * @return the ip properties for the active network, or {@code null} if
1143 * none is active
1144 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001145 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001146 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001147 enforceAccessPermission();
1148 final int uid = Binder.getCallingUid();
1149 NetworkState state = getUnfilteredActiveNetworkState(uid);
1150 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001151 }
1152
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001153 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001154 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001155 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001156 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1157 if (nai != null) {
1158 synchronized (nai) {
1159 return new LinkProperties(nai.linkProperties);
1160 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001161 }
1162 return null;
1163 }
1164
Robert Greenwalt12e67352014-05-13 21:41:06 -07001165 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001166 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001167 public LinkProperties getLinkProperties(Network network) {
1168 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001169 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001170 if (nai != null) {
1171 synchronized (nai) {
1172 return new LinkProperties(nai.linkProperties);
1173 }
1174 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001175 return null;
1176 }
1177
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001178 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001179 if (nai != null) {
1180 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001181 if (nai.networkCapabilities != null) {
1182 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001183 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001184 }
1185 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001186 return null;
1187 }
1188
1189 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001190 public NetworkCapabilities getNetworkCapabilities(Network network) {
1191 enforceAccessPermission();
1192 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1193 }
1194
1195 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001196 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001197 // Require internal since we're handing out IMSI details
1198 enforceConnectivityInternalPermission();
1199
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001200 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001201 for (Network network : getAllNetworks()) {
1202 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1203 if (nai != null) {
1204 synchronized (nai) {
1205 final String subscriberId = (nai.networkMisc != null)
1206 ? nai.networkMisc.subscriberId : null;
1207 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1208 nai.networkCapabilities, network, subscriberId, null));
1209 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001210 }
1211 }
1212 return result.toArray(new NetworkState[result.size()]);
1213 }
1214
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001215 @Override
1216 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1217 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001218 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001219 final long token = Binder.clearCallingIdentity();
1220 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1222 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001223 try {
1224 return mPolicyManager.getNetworkQuotaInfo(state);
1225 } catch (RemoteException e) {
1226 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001227 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001228 return null;
1229 } finally {
1230 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001231 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001232 }
1233
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001234 @Override
1235 public boolean isActiveNetworkMetered() {
1236 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001237 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001238 final long token = Binder.clearCallingIdentity();
1239 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001240 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001241 } finally {
1242 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001243 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001244 }
1245
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001246 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1247 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1248 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001249 try {
1250 return mPolicyManager.isNetworkMetered(state);
1251 } catch (RemoteException e) {
1252 }
1253 }
1254 return false;
1255 }
1256
Jeff Sharkey216c1812012-08-05 14:29:23 -07001257 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1258 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001259 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001260 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001261 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001262 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001263 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001264
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001265 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 * Ensure that a network route exists to deliver traffic to the specified
1267 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001268 * @param networkType the type of the network over which traffic to the
1269 * specified host is to be routed
1270 * @param hostAddress the IP address of the host to which the route is
1271 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 * @return {@code true} on success, {@code false} on failure
1273 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001274 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001276 if (mProtectedNetworks.contains(networkType)) {
1277 enforceConnectivityInternalPermission();
1278 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001279
Chad Brubakerc0234532014-02-14 13:24:29 -08001280 InetAddress addr;
1281 try {
1282 addr = InetAddress.getByAddress(hostAddress);
1283 } catch (UnknownHostException e) {
1284 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1285 return false;
1286 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001289 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 return false;
1291 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001292
1293 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1294 if (nai == null) {
1295 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1296 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1297 } else {
1298 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1299 }
1300 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001301 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001302
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001303 DetailedState netState;
1304 synchronized (nai) {
1305 netState = nai.networkInfo.getDetailedState();
1306 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001307
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001308 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001309 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001310 log("requestRouteToHostAddress on down network "
1311 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001312 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001313 }
1314 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001316
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001317 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001318 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001319 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001320 LinkProperties lp;
1321 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001322 synchronized (nai) {
1323 lp = nai.linkProperties;
1324 netId = nai.network.netId;
1325 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001326 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001327 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1328 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001329 } finally {
1330 Binder.restoreCallingIdentity(token);
1331 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001332 }
1333
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001334 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001335 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001336 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001337 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001338 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001339 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001340 if (bestRoute.getGateway().equals(addr)) {
1341 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001342 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001343 } else {
1344 // if we will connect to this through another route, add a direct route
1345 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001346 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001347 }
1348 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001349 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001350 try {
1351 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1352 } catch (Exception e) {
1353 // never crash - catch them all
1354 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001355 return false;
1356 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001357 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 }
1359
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1361 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001362 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001363 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001364 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001365 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001366 }
1367
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001368 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001369 // skip update when we've already applied rules
1370 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1371 if (oldRules == uidRules) return;
1372
1373 mUidRules.put(uid, uidRules);
1374 }
1375
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001376 // TODO: notify UID when it has requested targeted updates
1377 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001378
1379 @Override
1380 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001381 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001382 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001383 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001384 }
1385
1386 synchronized (mRulesLock) {
1387 mMeteredIfaces.clear();
1388 for (String iface : meteredIfaces) {
1389 mMeteredIfaces.add(iface);
1390 }
1391 }
1392 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001393
1394 @Override
1395 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1396 // caller is NPMS, since we only register with them
1397 if (LOGD_RULES) {
1398 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1399 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001400 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001401 };
1402
Robin Lee3b3dd942015-05-12 18:14:58 +01001403 /**
1404 * Require that the caller is either in the same user or has appropriate permission to interact
1405 * across users.
1406 *
1407 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1408 */
1409 private void enforceCrossUserPermission(int userId) {
1410 if (userId == UserHandle.getCallingUserId()) {
1411 // Not a cross-user call.
1412 return;
1413 }
1414 mContext.enforceCallingOrSelfPermission(
1415 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1416 "ConnectivityService");
1417 }
1418
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001419 private void enforceInternetPermission() {
1420 mContext.enforceCallingOrSelfPermission(
1421 android.Manifest.permission.INTERNET,
1422 "ConnectivityService");
1423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001426 mContext.enforceCallingOrSelfPermission(
1427 android.Manifest.permission.ACCESS_NETWORK_STATE,
1428 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430
1431 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001432 mContext.enforceCallingOrSelfPermission(
1433 android.Manifest.permission.CHANGE_NETWORK_STATE,
1434 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001437 private void enforceTetherAccessPermission() {
1438 mContext.enforceCallingOrSelfPermission(
1439 android.Manifest.permission.ACCESS_NETWORK_STATE,
1440 "ConnectivityService");
1441 }
1442
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001443 private void enforceConnectivityInternalPermission() {
1444 mContext.enforceCallingOrSelfPermission(
1445 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1446 "ConnectivityService");
1447 }
1448
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001449 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001450 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001451 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001452 }
1453
1454 private void sendInetConditionBroadcast(NetworkInfo info) {
1455 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1456 }
1457
Wink Saville628b0852011-08-04 15:01:58 -07001458 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001459 if (mLockdownTracker != null) {
1460 info = mLockdownTracker.augmentNetworkInfo(info);
1461 }
1462
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001463 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001464 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001465 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 if (info.isFailover()) {
1467 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1468 info.setFailover(false);
1469 }
1470 if (info.getReason() != null) {
1471 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1472 }
1473 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001474 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1475 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001477 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001478 return intent;
1479 }
1480
1481 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1482 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1483 }
1484
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001485 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001486 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1487 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1488 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001489 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001490 final long ident = Binder.clearCallingIdentity();
1491 try {
1492 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1493 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1494 } finally {
1495 Binder.restoreCallingIdentity(ident);
1496 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001497 }
1498
Mike Lockwood0f79b542009-08-14 14:18:49 -04001499 private void sendStickyBroadcast(Intent intent) {
1500 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001501 if (!mSystemReady) {
1502 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001503 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001504 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001505 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001506 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001507 }
1508
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001509 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001510 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1511 final IBatteryStats bs = BatteryStatsService.getService();
1512 try {
1513 NetworkInfo ni = intent.getParcelableExtra(
1514 ConnectivityManager.EXTRA_NETWORK_INFO);
1515 bs.noteConnectivityChanged(intent.getIntExtra(
1516 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1517 ni != null ? ni.getState().toString() : "?");
1518 } catch (RemoteException e) {
1519 }
1520 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001521 try {
1522 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1523 } finally {
1524 Binder.restoreCallingIdentity(ident);
1525 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001526 }
1527 }
1528
1529 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001530 loadGlobalProxy();
1531
Mike Lockwood0f79b542009-08-14 14:18:49 -04001532 synchronized(this) {
1533 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001534 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001535 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001536 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001537 }
1538 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001539 // load the global proxy at startup
1540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001541
1542 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1543 // for user to unlock device.
1544 if (!updateLockdownVpn()) {
1545 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1546 mContext.registerReceiver(mUserPresentReceiver, filter);
1547 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001548
Erik Klineda4bfa82015-04-30 12:58:40 +09001549 // Configure whether mobile data is always on.
1550 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1551
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001552 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001553
1554 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001557 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1558 @Override
1559 public void onReceive(Context context, Intent intent) {
1560 // Try creating lockdown tracker, since user present usually means
1561 // unlocked keystore.
1562 if (updateLockdownVpn()) {
1563 mContext.unregisterReceiver(this);
1564 }
1565 }
1566 };
1567
Wink Savilled747cbc2013-08-07 16:22:47 -07001568 /** @hide */
1569 @Override
1570 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1571 enforceConnectivityInternalPermission();
1572 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001573// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001574 }
1575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001577 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001578 *
1579 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001580 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001581 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001582 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1583 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001584
1585 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001586 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001587
Robert Greenwalt7b816022014-04-18 15:25:25 -07001588 if (networkAgent.networkCapabilities.hasTransport(
1589 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001590 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1591 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001592 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001593 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001594 } else if (networkAgent.networkCapabilities.hasTransport(
1595 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001596 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1597 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001598 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001599 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001600 } else {
1601 // do not track any other networks
1602 timeout = 0;
1603 }
1604
Robert Greenwalt7b816022014-04-18 15:25:25 -07001605 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001606 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001607 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001608 } catch (Exception e) {
1609 // You shall not crash!
1610 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001611 }
1612 }
1613 }
1614
1615 /**
1616 * Remove data activity tracking when network disconnects.
1617 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001618 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1619 final String iface = networkAgent.linkProperties.getInterfaceName();
1620 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001621
Robert Greenwalt7b816022014-04-18 15:25:25 -07001622 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1623 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001624 try {
1625 // the call fails silently if no idletimer setup for this interface
1626 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001627 } catch (Exception e) {
1628 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001629 }
1630 }
1631 }
1632
1633 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001634 * Reads the network specific MTU size from reources.
1635 * and set it on it's iface.
1636 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001637 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1638 final String iface = newLp.getInterfaceName();
1639 final int mtu = newLp.getMtu();
1640 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1641 if (VDBG) log("identical MTU - not setting");
1642 return;
1643 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001644
Robert Greenwalt43074032014-08-15 17:53:05 -07001645 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001646 loge("Unexpected mtu value: " + mtu + ", " + iface);
1647 return;
1648 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001649
w1997615afd812014-08-05 15:18:11 -07001650 // Cannot set MTU without interface name
1651 if (TextUtils.isEmpty(iface)) {
1652 loge("Setting MTU size with null iface.");
1653 return;
1654 }
1655
Robert Greenwalt7b816022014-04-18 15:25:25 -07001656 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001657 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001658 mNetd.setMtu(iface, mtu);
1659 } catch (Exception e) {
1660 Slog.e(TAG, "exception in setMtu()" + e);
1661 }
1662 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001663
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001664 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001665 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1666
1667 // Overridden for testing purposes to avoid writing to SystemProperties.
1668 protected int getDefaultTcpRwnd() {
1669 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1670 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001671
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001672 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1673 if (isDefaultNetwork(nai) == false) {
1674 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001675 }
1676
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001677 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1678 String[] values = null;
1679 if (tcpBufferSizes != null) {
1680 values = tcpBufferSizes.split(",");
1681 }
1682
1683 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001684 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001685 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1686 values = tcpBufferSizes.split(",");
1687 }
1688
1689 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1690
1691 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001692 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001693
1694 final String prefix = "/sys/kernel/ipv4/tcp_";
1695 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1696 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1697 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1698 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1699 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1700 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1701 mCurrentTcpBufferSizes = tcpBufferSizes;
1702 } catch (IOException e) {
1703 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001704 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001705
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001706 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001707 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001708 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1709 if (rwndValue != 0) {
1710 SystemProperties.set(sysctlKey, rwndValue.toString());
1711 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001712 }
1713
Mattias Falk8b47b362011-08-23 14:15:13 +02001714 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001715 /*
1716 * Tell the VMs to toss their DNS caches
1717 */
1718 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1719 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001720 /*
1721 * Connectivity events can happen before boot has completed ...
1722 */
1723 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001724 final long ident = Binder.clearCallingIdentity();
1725 try {
1726 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1727 } finally {
1728 Binder.restoreCallingIdentity(ident);
1729 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001730 }
1731
Robert Greenwalt562cc542014-05-15 18:07:26 -07001732 @Override
1733 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001734 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1735 NETWORK_RESTORE_DELAY_PROP_NAME);
1736 if(restoreDefaultNetworkDelayStr != null &&
1737 restoreDefaultNetworkDelayStr.length() != 0) {
1738 try {
1739 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1740 } catch (NumberFormatException e) {
1741 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001742 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001743 // if the system property isn't set, use the value for the apn type
1744 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1745
1746 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1747 (mNetConfigs[networkType] != null)) {
1748 ret = mNetConfigs[networkType].restoreTime;
1749 }
1750 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001751 }
1752
Erik Kline379747a2015-06-05 17:47:34 +09001753 private boolean shouldPerformDiagnostics(String[] args) {
1754 for (String arg : args) {
1755 if (arg.equals("--diag")) {
1756 return true;
1757 }
1758 }
1759 return false;
1760 }
1761
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001762 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001763 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1764 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001765 if (mContext.checkCallingOrSelfPermission(
1766 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001768 pw.println("Permission Denial: can't dump ConnectivityService " +
1769 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1770 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001771 return;
1772 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001773
Erik Kline379747a2015-06-05 17:47:34 +09001774 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
1775 if (shouldPerformDiagnostics(args)) {
1776 final long DIAG_TIME_MS = 5000;
1777 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1778 // Start gathering diagnostic information.
1779 netDiags.add(new NetworkDiagnostics(
1780 nai.network,
1781 new LinkProperties(nai.linkProperties),
1782 DIAG_TIME_MS));
1783 }
1784
1785 for (NetworkDiagnostics netDiag : netDiags) {
1786 pw.println();
1787 netDiag.waitForMeasurements();
1788 netDiag.dump(pw);
1789 }
1790
1791 return;
1792 }
1793
Lorenzo Colittie3805462015-06-03 11:18:24 +09001794 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001795 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001796 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001797 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001798 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001799 pw.println();
1800
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001801 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1802 pw.print("Active default network: ");
1803 if (defaultNai == null) {
1804 pw.println("none");
1805 } else {
1806 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001807 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001808 pw.println();
1809
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001810 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001811 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001812 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1813 pw.println(nai.toString());
1814 pw.increaseIndent();
1815 pw.println("Requests:");
1816 pw.increaseIndent();
1817 for (int i = 0; i < nai.networkRequests.size(); i++) {
1818 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001819 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001820 pw.decreaseIndent();
1821 pw.println("Lingered:");
1822 pw.increaseIndent();
1823 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1824 pw.decreaseIndent();
1825 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001826 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001827 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001828 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001829
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001830 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001831 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001832 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1833 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001834 }
1835 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001836 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001837
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001838 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001839
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001840 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001841 pw.print("mNetTransitionWakeLock: currently " +
1842 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1843 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1844 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1845 } else {
1846 pw.println(", last requested never");
1847 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001848 }
1849 pw.println();
1850
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001851 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001852
Lorenzo Colittie3805462015-06-03 11:18:24 +09001853 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001854 pw.println();
1855 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001856 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001857 for(int i = 0; i < mInetLog.size(); i++) {
1858 pw.println(mInetLog.get(i));
1859 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001860 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001861 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001862 }
1863
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001864 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001865 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001866 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001867 if (officialNai != null && officialNai.equals(nai)) return true;
1868 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001869 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001870 " - " + nai);
1871 }
1872 return false;
1873 }
1874
Paul Jensenc8b9a742014-09-30 15:37:41 -04001875 private boolean isRequest(NetworkRequest request) {
1876 return mNetworkRequests.get(request).isRequest;
1877 }
1878
Robert Greenwalt42acef32009-08-12 16:08:25 -07001879 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001880 private class NetworkStateTrackerHandler extends Handler {
1881 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001882 super(looper);
1883 }
1884
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001885 @Override
1886 public void handleMessage(Message msg) {
1887 NetworkInfo info;
1888 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001889 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001890 handleAsyncChannelHalfConnect(msg);
1891 break;
1892 }
1893 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1894 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1895 if (nai != null) nai.asyncChannel.disconnect();
1896 break;
1897 }
1898 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1899 handleAsyncChannelDisconnected(msg);
1900 break;
1901 }
1902 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1903 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1904 if (nai == null) {
1905 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1906 } else {
1907 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001908 }
1909 break;
1910 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001911 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1912 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1913 if (nai == null) {
1914 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1915 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001916 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001917 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001918 "; created=" + nai.created);
1919 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001920 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001921 synchronized (nai) {
1922 nai.linkProperties = (LinkProperties)msg.obj;
1923 }
Paul Jenseneec75412014-08-04 12:21:19 -04001924 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001925 }
1926 break;
1927 }
1928 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1929 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1930 if (nai == null) {
1931 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1932 break;
1933 }
1934 info = (NetworkInfo) msg.obj;
1935 updateNetworkInfo(nai, info);
1936 break;
1937 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001938 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1939 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1940 if (nai == null) {
1941 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1942 break;
1943 }
1944 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001945 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001946 break;
1947 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001948 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1949 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1950 if (nai == null) {
1951 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1952 break;
1953 }
1954 try {
1955 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001956 } catch (Exception e) {
1957 // Never crash!
1958 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001959 }
1960 break;
1961 }
1962 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1963 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1964 if (nai == null) {
1965 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1966 break;
1967 }
1968 try {
1969 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001970 } catch (Exception e) {
1971 // Never crash!
1972 loge("Exception in removeVpnUidRanges: " + e);
1973 }
1974 break;
1975 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001976 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1977 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1978 if (nai == null) {
1979 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1980 break;
1981 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001982 if (nai.created && !nai.networkMisc.explicitlySelected) {
1983 loge("ERROR: created network explicitly selected.");
1984 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001985 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001986 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001987 break;
1988 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001989 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001990 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001991 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1992 final boolean valid =
1993 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
1994 final boolean validationChanged = (valid != nai.lastValidated);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001995 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001996 if (valid) {
1997 if (DBG) log("Validated " + nai.name());
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001998 nai.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001999 if (!nai.everValidated) {
2000 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05002001 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
2002 ReapUnvalidatedNetworks.REAP);
2003 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04002004 sendUpdatedScoreToFactories(nai);
2005 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002006 } else {
2007 nai.networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002008 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002009 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002010 // Let the NetworkAgent know the state of its network
2011 nai.asyncChannel.sendMessage(
2012 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2013 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2014 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002015
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002016 if (validationChanged) {
2017 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
2018 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002019 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002020 break;
2021 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002022 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002023 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002024 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2025 handleLingerComplete(nai);
2026 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002027 break;
2028 }
Paul Jensen869868be2014-05-15 10:33:05 -04002029 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002030 if (msg.arg1 == 0) {
2031 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
2032 } else {
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002033 final NetworkAgentInfo nai;
Paul Jensen5df4bec2014-08-25 22:45:39 -04002034 synchronized (mNetworkForNetId) {
2035 nai = mNetworkForNetId.get(msg.arg2);
2036 }
2037 if (nai == null) {
2038 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2039 break;
2040 }
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002041 nai.captivePortalDetected = true;
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002042 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
2043 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04002044 }
Paul Jensen869868be2014-05-15 10:33:05 -04002045 break;
2046 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002047 }
2048 }
2049 }
2050
Paul Jensen0cc17322014-11-25 15:26:53 -05002051 // Cancel any lingering so the linger timeout doesn't teardown a network.
2052 // This should be called when a network begins satisfying a NetworkRequest.
2053 // Note: depending on what state the NetworkMonitor is in (e.g.,
2054 // if it's awaiting captive portal login, or if validation failed), this
2055 // may trigger a re-evaluation of the network.
2056 private void unlinger(NetworkAgentInfo nai) {
2057 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002058 // If network has never been validated, it cannot have been lingered, so don't bother
2059 // needlessly triggering a re-evaluation.
2060 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002061 nai.networkLingered.clear();
2062 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2063 }
2064
Robert Greenwalt7b816022014-04-18 15:25:25 -07002065 private void handleAsyncChannelHalfConnect(Message msg) {
2066 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002067 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002068 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2069 if (VDBG) log("NetworkFactory connected");
2070 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002071 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002072 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002073 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002074 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002075 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002076 }
2077 } else {
2078 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002079 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002080 }
2081 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2082 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2083 if (VDBG) log("NetworkAgent connected");
2084 // A network agent has requested a connection. Establish the connection.
2085 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2086 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2087 } else {
2088 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002089 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002090 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002091 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002092 synchronized (mNetworkForNetId) {
2093 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002094 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002095 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002096 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002097 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002098 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002099 }
2100 }
2101 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002102
Robert Greenwalt7b816022014-04-18 15:25:25 -07002103 private void handleAsyncChannelDisconnected(Message msg) {
2104 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2105 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002106 if (DBG) {
2107 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2108 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002109 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002110 if (nai.created) {
2111 // Tell netd to clean up the configuration for this network
2112 // (routing rules, DNS, etc).
2113 try {
2114 mNetd.removeNetwork(nai.network.netId);
2115 } catch (Exception e) {
2116 loge("Exception removing network: " + e);
2117 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002119 // TODO - if we move the logic to the network agent (have them disconnect
2120 // because they lost all their requests or because their score isn't good)
2121 // then they would disconnect organically, report their new state and then
2122 // disconnect the channel.
2123 if (nai.networkInfo.isConnected()) {
2124 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2125 null, null);
2126 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002127 final boolean wasDefault = isDefaultNetwork(nai);
2128 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002129 mDefaultInetConditionPublished = 0;
2130 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002131 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002132 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002133 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002134 mNetworkAgentInfos.remove(msg.replyTo);
2135 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002136 synchronized (mNetworkForNetId) {
2137 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002138 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002139 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 // Since we've lost the network, go through all the requests that
2141 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002142 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002143 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002144 for (int i = 0; i < nai.networkRequests.size(); i++) {
2145 NetworkRequest request = nai.networkRequests.valueAt(i);
2146 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2147 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002148 if (DBG) {
2149 log("Checking for replacement network to handle request " + request );
2150 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002151 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002152 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002153 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002154 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2155 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002156 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002157 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002158 alternative = existing;
2159 }
2160 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002161 if (alternative != null) {
2162 if (DBG) log(" found replacement in " + alternative.name());
2163 if (!toActivate.contains(alternative)) {
2164 toActivate.add(alternative);
2165 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002166 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002167 }
2168 }
2169 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2170 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002171 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002172 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002173 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002174 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002175 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002176 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002177 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2178 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002179 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002180 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302181 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2182 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002183 }
2184
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002185 // If this method proves to be too slow then we can maintain a separate
2186 // pendingIntent => NetworkRequestInfo map.
2187 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2188 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2189 Intent intent = pendingIntent.getIntent();
2190 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2191 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2192 if (existingPendingIntent != null &&
2193 existingPendingIntent.getIntent().filterEquals(intent)) {
2194 return entry.getValue();
2195 }
2196 }
2197 return null;
2198 }
2199
2200 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2201 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2202
2203 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2204 if (existingRequest != null) { // remove the existing request.
2205 if (DBG) log("Replacing " + existingRequest.request + " with "
2206 + nri.request + " because their intents matched.");
2207 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2208 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002209 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002210 }
2211
Erik Klineda4bfa82015-04-30 12:58:40 +09002212 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002213 mNetworkRequests.put(nri.request, nri);
2214
Paul Jensen0cc17322014-11-25 15:26:53 -05002215 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2216
Robert Greenwalt9258c642014-03-26 16:47:06 -07002217 // Check for the best currently alive network that satisfies this request
2218 NetworkAgentInfo bestNetwork = null;
2219 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002220 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002221 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002222 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002223 if (!nri.isRequest) {
2224 // Not setting bestNetwork here as a listening NetworkRequest may be
2225 // satisfied by multiple Networks. Instead the request is added to
2226 // each satisfying Network and notified about each.
2227 network.addRequest(nri.request);
2228 notifyNetworkCallback(network, nri);
2229 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002230 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002231 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002232 }
2233 }
2234 }
2235 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002236 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002237 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002238 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002239 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002240 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002241 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002242 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2243 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002244 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002245
Lorenzo Colittia793a672014-07-31 23:20:17 +09002246 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002247 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002248 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002249 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002250 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002251 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002252 }
2253 }
2254 }
2255
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002256 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2257 int callingUid) {
2258 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2259 if (nri != null) {
2260 handleReleaseNetworkRequest(nri.request, callingUid);
2261 }
2262 }
2263
Paul Jensen99364842014-12-09 11:43:45 -05002264 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2265 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2266 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2267 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2268 private boolean unneeded(NetworkAgentInfo nai) {
2269 if (!nai.created || nai.isVPN()) return false;
2270 boolean unneeded = true;
2271 if (nai.everValidated) {
2272 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2273 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2274 try {
2275 if (isRequest(nr)) unneeded = false;
2276 } catch (Exception e) {
2277 loge("Request " + nr + " not found in mNetworkRequests.");
2278 loge(" it came from request list of " + nai.name());
2279 }
2280 }
2281 } else {
2282 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2283 // If this Network is already the highest scoring Network for a request, or if
2284 // there is hope for it to become one if it validated, then it is needed.
2285 if (nri.isRequest && nai.satisfies(nri.request) &&
2286 (nai.networkRequests.get(nri.request.requestId) != null ||
2287 // Note that this catches two important cases:
2288 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2289 // is currently satisfying the request. This is desirable when
2290 // cellular ends up validating but WiFi does not.
2291 // 2. Unvalidated WiFi will not be reaped when validated cellular
2292 // is currently satsifying the request. This is desirable when
2293 // WiFi ends up validating and out scoring cellular.
2294 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2295 nai.getCurrentScoreAsValidated())) {
2296 unneeded = false;
2297 break;
2298 }
2299 }
2300 }
2301 return unneeded;
2302 }
2303
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002304 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2305 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002306 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002307 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002308 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2309 return;
2310 }
2311 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002312 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002313 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002314 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002315 // Find all networks that are satisfying this request and remove the request
2316 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002317 // TODO - it's my understanding that for a request there is only a single
2318 // network satisfying it, so this loop is wasteful
2319 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002320 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2321 if (nai.networkRequests.get(nri.request.requestId) != null) {
2322 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002323 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002324 log(" Removing from current network " + nai.name() +
2325 ", leaving " + nai.networkRequests.size() +
2326 " requests.");
2327 }
Paul Jensen99364842014-12-09 11:43:45 -05002328 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002329 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002330 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002331 } else {
2332 // suspect there should only be one pass through here
2333 // but if any were kept do the check below
2334 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002335 }
2336 }
2337 }
2338
Robert Greenwalt51481852015-01-08 14:43:31 -08002339 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2340 if (nai != null) {
2341 mNetworkForRequestId.remove(nri.request.requestId);
2342 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002343 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002344 // that a network connected to serve it, even though the network was already
2345 // connected. Now that this request has gone away, we might have to pretend
2346 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002347 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002348 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2349 boolean doRemove = true;
2350 if (wasKept) {
2351 // check if any of the remaining requests for this network are for the
2352 // same legacy type - if so, don't remove the nai
2353 for (int i = 0; i < nai.networkRequests.size(); i++) {
2354 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2355 if (otherRequest.legacyType == nri.request.legacyType &&
2356 isRequest(otherRequest)) {
2357 if (DBG) log(" still have other legacy request - leaving");
2358 doRemove = false;
2359 }
2360 }
2361 }
2362
2363 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002364 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002365 }
2366 }
2367
Robert Greenwalta67be032014-05-16 15:49:14 -07002368 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002369 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2370 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002371 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002372 } else {
2373 // listens don't have a singular affectedNetwork. Check all networks to see
2374 // if this listen request applies and remove it.
2375 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2376 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002377 }
2378 }
2379 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2380 }
2381 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002382
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002383 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2384 enforceConnectivityInternalPermission();
2385 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2386 accept ? 1 : 0, always ? 1: 0, network));
2387 }
2388
2389 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2390 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2391 " accept=" + accept + " always=" + always);
2392
2393 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2394 if (nai == null) {
2395 // Nothing to do.
2396 return;
2397 }
2398
2399 if (nai.everValidated) {
2400 // The network validated while the dialog box was up. Don't make any changes. There's a
2401 // TODO in the dialog code to make it go away if the network validates; once that's
2402 // implemented, taking action here will be confusing.
2403 return;
2404 }
2405
2406 if (!nai.networkMisc.explicitlySelected) {
2407 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2408 }
2409
2410 if (accept != nai.networkMisc.acceptUnvalidated) {
2411 int oldScore = nai.getCurrentScore();
2412 nai.networkMisc.acceptUnvalidated = accept;
2413 rematchAllNetworksAndRequests(nai, oldScore);
2414 sendUpdatedScoreToFactories(nai);
2415 }
2416
2417 if (always) {
2418 nai.asyncChannel.sendMessage(
2419 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2420 }
2421
2422 // TODO: should we also disconnect from the network if accept is false?
2423 }
2424
2425 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2426 mHandler.sendMessageDelayed(
2427 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2428 PROMPT_UNVALIDATED_DELAY_MS);
2429 }
2430
2431 private void handlePromptUnvalidated(Network network) {
2432 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2433
2434 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2435 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002436 // Also don't prompt on captive portals because we're already prompting the user to sign in.
2437 if (nai == null || nai.everValidated || nai.captivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002438 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2439 return;
2440 }
2441
2442 // TODO: What should we do if we've already switched to this network because we had no
2443 // better option? There are two obvious alternatives.
2444 //
2445 // 1. Decide that there's no point prompting because this is our only usable network.
2446 // However, because we didn't prompt, if later on a validated network comes along, we'll
2447 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2448 // unvalidated network - or b) prompt the user at that later time - bad because the user
2449 // might not understand why they are now being prompted.
2450 //
2451 // 2. Always prompt the user, even if we have no other network to use. The user could then
2452 // try to find an alternative network to join (remember, if we got here, then the user
2453 // selected this network manually). This is bad because the prompt isn't really very
2454 // useful.
2455 //
2456 // For now we do #1, but we can revisit that later.
2457 if (isDefaultNetwork(nai)) {
2458 return;
2459 }
2460
2461 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2462 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2463 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2464 intent.setClassName("com.android.settings",
2465 "com.android.settings.wifi.WifiNoInternetDialog");
2466 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2467 }
2468
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002469 private class InternalHandler extends Handler {
2470 public InternalHandler(Looper looper) {
2471 super(looper);
2472 }
2473
2474 @Override
2475 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002476 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002477 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002478 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002479 String causedBy = null;
2480 synchronized (ConnectivityService.this) {
2481 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2482 mNetTransitionWakeLock.isHeld()) {
2483 mNetTransitionWakeLock.release();
2484 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002485 } else {
2486 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002487 }
2488 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002489 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2490 log("Failed to find a new network - expiring NetTransition Wakelock");
2491 } else {
2492 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2493 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002494 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002495 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002496 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002497 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002498 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002499 break;
2500 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002501 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002502 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002503 sendStickyBroadcast(intent);
2504 break;
2505 }
Jason Monkdecd2952013-10-10 14:02:51 -04002506 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002507 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002508 break;
2509 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002510 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002511 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2512 break;
2513 }
2514 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2515 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002516 break;
2517 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002518 case EVENT_REGISTER_NETWORK_AGENT: {
2519 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2520 break;
2521 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002522 case EVENT_REGISTER_NETWORK_REQUEST:
2523 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002524 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002525 break;
2526 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002527 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2528 handleRegisterNetworkRequestWithIntent(msg);
2529 break;
2530 }
2531 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2532 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2533 break;
2534 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002535 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002536 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002537 break;
2538 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002539 case EVENT_SET_ACCEPT_UNVALIDATED: {
2540 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2541 break;
2542 }
2543 case EVENT_PROMPT_UNVALIDATED: {
2544 handlePromptUnvalidated((Network) msg.obj);
2545 break;
2546 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002547 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2548 handleMobileDataAlwaysOn();
2549 break;
2550 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002551 case EVENT_SYSTEM_READY: {
2552 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2553 nai.networkMonitor.systemReady = true;
2554 }
2555 break;
2556 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002557 }
2558 }
2559 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002560
2561 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002562 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002563 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002564 if (isTetheringSupported()) {
2565 return mTethering.tether(iface);
2566 } else {
2567 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2568 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002569 }
2570
2571 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002572 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002573 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002574
2575 if (isTetheringSupported()) {
2576 return mTethering.untether(iface);
2577 } else {
2578 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2579 }
2580 }
2581
2582 // javadoc from interface
2583 public int getLastTetherError(String iface) {
2584 enforceTetherAccessPermission();
2585
2586 if (isTetheringSupported()) {
2587 return mTethering.getLastTetherError(iface);
2588 } else {
2589 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2590 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002591 }
2592
2593 // TODO - proper iface API for selection by property, inspection, etc
2594 public String[] getTetherableUsbRegexs() {
2595 enforceTetherAccessPermission();
2596 if (isTetheringSupported()) {
2597 return mTethering.getTetherableUsbRegexs();
2598 } else {
2599 return new String[0];
2600 }
2601 }
2602
2603 public String[] getTetherableWifiRegexs() {
2604 enforceTetherAccessPermission();
2605 if (isTetheringSupported()) {
2606 return mTethering.getTetherableWifiRegexs();
2607 } else {
2608 return new String[0];
2609 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002610 }
2611
Danica Chang6fdd0c62010-08-11 14:54:43 -07002612 public String[] getTetherableBluetoothRegexs() {
2613 enforceTetherAccessPermission();
2614 if (isTetheringSupported()) {
2615 return mTethering.getTetherableBluetoothRegexs();
2616 } else {
2617 return new String[0];
2618 }
2619 }
2620
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002621 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002622 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002623 if (isTetheringSupported()) {
2624 return mTethering.setUsbTethering(enable);
2625 } else {
2626 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2627 }
2628 }
2629
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002630 // TODO - move iface listing, queries, etc to new module
2631 // javadoc from interface
2632 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002633 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002634 return mTethering.getTetherableIfaces();
2635 }
2636
2637 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002638 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002639 return mTethering.getTetheredIfaces();
2640 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002641
Robert Greenwalt5a735062010-03-02 17:25:02 -08002642 public String[] getTetheringErroredIfaces() {
2643 enforceTetherAccessPermission();
2644 return mTethering.getErroredIfaces();
2645 }
2646
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002647 public String[] getTetheredDhcpRanges() {
2648 enforceConnectivityInternalPermission();
2649 return mTethering.getTetheredDhcpRanges();
2650 }
2651
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002652 // if ro.tether.denied = true we default to no tethering
2653 // gservices could set the secure setting to 1 though to enable it on a build where it
2654 // had previously been turned off.
2655 public boolean isTetheringSupported() {
2656 enforceTetherAccessPermission();
2657 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002658 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002659 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2660 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002661 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2662 mTethering.getTetherableWifiRegexs().length != 0 ||
2663 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2664 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002665 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002666
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002667 // Called when we lose the default network and have no replacement yet.
2668 // This will automatically be cleared after X seconds or a new default network
2669 // becomes CONNECTED, whichever happens first. The timer is started by the
2670 // first caller and not restarted by subsequent callers.
2671 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002672 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002673 synchronized (this) {
2674 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002675 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002676 mNetTransitionWakeLock.acquire();
2677 mNetTransitionWakeLockCausedBy = forWhom;
2678 }
2679 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002680 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002681 mNetTransitionWakeLockTimeout);
2682 return;
2683 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002684
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002685 // 100 percent is full good, 0 is full bad.
2686 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002687 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002688 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002689 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002690 }
2691
Paul Jensenbfd17b72015-04-07 12:43:13 -04002692 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002693 enforceAccessPermission();
2694 enforceInternetPermission();
2695
Paul Jensenbfd17b72015-04-07 12:43:13 -04002696 NetworkAgentInfo nai;
2697 if (network == null) {
2698 nai = getDefaultNetwork();
2699 } else {
2700 nai = getNetworkAgentInfoForNetwork(network);
2701 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002702 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002703 // Revalidate if the app report does not match our current validated state.
2704 if (hasConnectivity == nai.lastValidated) return;
2705 final int uid = Binder.getCallingUid();
2706 if (DBG) {
2707 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2708 ") by " + uid);
2709 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002710 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002711 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2712 // which isn't meant to work on uncreated networks.
2713 if (!nai.created) return;
2714
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002715 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002716
2717 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2718 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002719 }
2720
Paul Jensen25a217c2015-02-27 22:55:47 -05002721 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2722 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2723 enforceConnectivityInternalPermission();
2724 }
2725 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2726 if (nai == null) return;
2727 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2728 actionToken);
2729 }
2730
Paul Jensencee9b512015-05-06 07:32:40 -04002731 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002732 // this information is already available as a world read/writable jvm property
2733 // so this API change wouldn't have a benifit. It also breaks the passing
2734 // of proxy info to all the JVMs.
2735 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002736 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002737 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002738 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2739 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002740 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002741 }
2742
Paul Jensencee9b512015-05-06 07:32:40 -04002743 public ProxyInfo getProxyForNetwork(Network network) {
2744 if (network == null) return getDefaultProxy();
2745 final ProxyInfo globalProxy = getGlobalProxy();
2746 if (globalProxy != null) return globalProxy;
2747 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2748 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2749 // caller may not have.
2750 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2751 if (nai == null) return null;
2752 synchronized (nai) {
2753 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2754 if (proxyInfo == null) return null;
2755 return new ProxyInfo(proxyInfo);
2756 }
2757 }
2758
Paul Jensene0bef712014-12-10 15:12:18 -05002759 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2760 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2761 // proxy is null then there is no proxy in place).
2762 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2763 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2764 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2765 proxy = null;
2766 }
2767 return proxy;
2768 }
2769
2770 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2771 // better for determining if a new proxy broadcast is necessary:
2772 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2773 // avoid unnecessary broadcasts.
2774 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2775 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2776 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2777 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2778 // all set.
2779 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2780 a = canonicalizeProxyInfo(a);
2781 b = canonicalizeProxyInfo(b);
2782 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2783 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2784 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2785 }
2786
Jason Monk207900c2014-04-25 15:00:09 -04002787 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002788 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002789
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002790 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002791 if (proxyProperties == mGlobalProxy) return;
2792 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2793 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2794
2795 String host = "";
2796 int port = 0;
2797 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002798 String pacFileUrl = "";
2799 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002800 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002801 if (!proxyProperties.isValid()) {
2802 if (DBG)
2803 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2804 return;
2805 }
Jason Monk207900c2014-04-25 15:00:09 -04002806 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002807 host = mGlobalProxy.getHost();
2808 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002809 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002810 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002811 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002812 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002813 } else {
2814 mGlobalProxy = null;
2815 }
2816 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002817 final long token = Binder.clearCallingIdentity();
2818 try {
2819 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2820 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2821 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2822 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002823 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002824 } finally {
2825 Binder.restoreCallingIdentity(token);
2826 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002827
Jason Monkcf0f97a2014-10-02 15:39:38 -04002828 if (mGlobalProxy == null) {
2829 proxyProperties = mDefaultProxy;
2830 }
2831 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002832 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002833 }
2834
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002835 private void loadGlobalProxy() {
2836 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002837 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2838 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2839 String exclList = Settings.Global.getString(res,
2840 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002841 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2842 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002843 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002844 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002845 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002846 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002847 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002848 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002849 if (!proxyProperties.isValid()) {
2850 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2851 return;
2852 }
2853
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002854 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002855 mGlobalProxy = proxyProperties;
2856 }
2857 }
2858 }
2859
Jason Monk207900c2014-04-25 15:00:09 -04002860 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002861 // this information is already available as a world read/writable jvm property
2862 // so this API change wouldn't have a benifit. It also breaks the passing
2863 // of proxy info to all the JVMs.
2864 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002865 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002866 return mGlobalProxy;
2867 }
2868 }
2869
Jason Monk207900c2014-04-25 15:00:09 -04002870 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002871 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002872 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002873 proxy = null;
2874 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002875 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002876 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002877 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002878 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002879 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2880 return;
2881 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002882
2883 // This call could be coming from the PacManager, containing the port of the local
2884 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2885 // global (to get the correct local port), and send a broadcast.
2886 // TODO: Switch PacManager to have its own message to send back rather than
2887 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002888 if ((mGlobalProxy != null) && (proxy != null)
2889 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002890 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2891 mGlobalProxy = proxy;
2892 sendProxyBroadcast(mGlobalProxy);
2893 return;
2894 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002895 mDefaultProxy = proxy;
2896
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002897 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002898 if (!mDefaultProxyDisabled) {
2899 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002900 }
2901 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002902 }
2903
Paul Jensene0bef712014-12-10 15:12:18 -05002904 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2905 // This method gets called when any network changes proxy, but the broadcast only ever contains
2906 // the default proxy (even if it hasn't changed).
2907 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2908 // world where an app might be bound to a non-default network.
2909 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2910 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2911 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2912
2913 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2914 sendProxyBroadcast(getDefaultProxy());
2915 }
2916 }
2917
Robert Greenwalt434203a2010-10-11 16:00:27 -07002918 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002919 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2920 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002921 if (!TextUtils.isEmpty(proxy)) {
2922 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002923 if (data.length == 0) {
2924 return;
2925 }
2926
Robert Greenwalt434203a2010-10-11 16:00:27 -07002927 String proxyHost = data[0];
2928 int proxyPort = 8080;
2929 if (data.length > 1) {
2930 try {
2931 proxyPort = Integer.parseInt(data[1]);
2932 } catch (NumberFormatException e) {
2933 return;
2934 }
2935 }
Jason Monk207900c2014-04-25 15:00:09 -04002936 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002937 setGlobalProxy(p);
2938 }
2939 }
2940
Jason Monk207900c2014-04-25 15:00:09 -04002941 private void sendProxyBroadcast(ProxyInfo proxy) {
2942 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002943 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002944 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002945 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002946 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2947 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002948 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002949 final long ident = Binder.clearCallingIdentity();
2950 try {
2951 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2952 } finally {
2953 Binder.restoreCallingIdentity(ident);
2954 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002955 }
2956
2957 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002958 final private HashMap<Uri, Integer> mUriEventMap;
2959 final private Context mContext;
2960 final private Handler mHandler;
2961
2962 SettingsObserver(Context context, Handler handler) {
2963 super(null);
2964 mUriEventMap = new HashMap<Uri, Integer>();
2965 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002966 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002967 }
2968
Erik Klineda4bfa82015-04-30 12:58:40 +09002969 void observe(Uri uri, int what) {
2970 mUriEventMap.put(uri, what);
2971 final ContentResolver resolver = mContext.getContentResolver();
2972 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002973 }
2974
2975 @Override
2976 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002977 Slog.wtf(TAG, "Should never be reached.");
2978 }
2979
2980 @Override
2981 public void onChange(boolean selfChange, Uri uri) {
2982 final Integer what = mUriEventMap.get(uri);
2983 if (what != null) {
2984 mHandler.obtainMessage(what.intValue()).sendToTarget();
2985 } else {
2986 loge("No matching event to send for URI=" + uri);
2987 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002988 }
2989 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002990
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002991 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002992 Slog.d(TAG, s);
2993 }
2994
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002995 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002996 Slog.e(TAG, s);
2997 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002998
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002999 private static <T> T checkNotNull(T value, String message) {
3000 if (value == null) {
3001 throw new NullPointerException(message);
3002 }
3003 return value;
3004 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003005
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003006 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003007 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003008 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3009 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3010 *
3011 * @param oldPackage Package name of the application which currently controls VPN, which will
3012 * be replaced. If there is no such application, this should should either be
3013 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3014 * @param newPackage Package name of the application which should gain control of VPN, or
3015 * {@code null} to disable.
3016 * @param userId User for whom to prepare the new VPN.
3017 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003018 * @hide
3019 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003020 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003021 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3022 int userId) {
3023 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003024 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003025
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003026 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003027 return mVpns.get(userId).prepare(oldPackage, newPackage);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003028 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003029 }
3030
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003031 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003032 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3033 * This method is used by system-privileged apps.
3034 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3035 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3036 *
3037 * @param packageName The package for which authorization state should change.
3038 * @param userId User for whom {@code packageName} is installed.
3039 * @param authorized {@code true} if this app should be able to start a VPN connection without
3040 * explicit user approval, {@code false} if not.
3041 *
Jeff Davidson05542602014-08-11 14:07:27 -07003042 * @hide
3043 */
3044 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003045 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3046 enforceCrossUserPermission(userId);
3047
Jeff Davidson05542602014-08-11 14:07:27 -07003048 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003049 mVpns.get(userId).setPackageAuthorization(packageName, authorized);
Jeff Davidson05542602014-08-11 14:07:27 -07003050 }
3051 }
3052
3053 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003054 * Configure a TUN interface and return its file descriptor. Parameters
3055 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003056 * and not available in ConnectivityManager. Permissions are checked in
3057 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003058 * @hide
3059 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003060 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003061 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003062 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003063 int user = UserHandle.getUserId(Binder.getCallingUid());
3064 synchronized(mVpns) {
3065 return mVpns.get(user).establish(config);
3066 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003067 }
3068
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003069 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003070 * Start legacy VPN, controlling native daemons as needed. Creates a
3071 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003072 */
3073 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003074 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003075 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003076 final LinkProperties egress = getActiveLinkProperties();
3077 if (egress == null) {
3078 throw new IllegalStateException("Missing active network connection");
3079 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003080 int user = UserHandle.getUserId(Binder.getCallingUid());
3081 synchronized(mVpns) {
3082 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3083 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003084 }
3085
3086 /**
3087 * Return the information of the ongoing legacy VPN. This method is used
3088 * by VpnSettings and not available in ConnectivityManager. Permissions
3089 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003090 */
3091 @Override
3092 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003093 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003094 int user = UserHandle.getUserId(Binder.getCallingUid());
3095 synchronized(mVpns) {
3096 return mVpns.get(user).getLegacyVpnInfo();
3097 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003098 }
3099
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003100 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003101 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3102 * and not available in ConnectivityManager.
3103 */
3104 @Override
3105 public VpnInfo[] getAllVpnInfo() {
3106 enforceConnectivityInternalPermission();
3107 if (mLockdownEnabled) {
3108 return new VpnInfo[0];
3109 }
3110
3111 synchronized(mVpns) {
3112 List<VpnInfo> infoList = new ArrayList<>();
3113 for (int i = 0; i < mVpns.size(); i++) {
3114 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3115 if (info != null) {
3116 infoList.add(info);
3117 }
3118 }
3119 return infoList.toArray(new VpnInfo[infoList.size()]);
3120 }
3121 }
3122
3123 /**
3124 * @return VPN information for accounting, or null if we can't retrieve all required
3125 * information, e.g primary underlying iface.
3126 */
3127 @Nullable
3128 private VpnInfo createVpnInfo(Vpn vpn) {
3129 VpnInfo info = vpn.getVpnInfo();
3130 if (info == null) {
3131 return null;
3132 }
3133 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3134 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3135 // the underlyingNetworks list.
3136 if (underlyingNetworks == null) {
3137 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3138 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3139 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3140 }
3141 } else if (underlyingNetworks.length > 0) {
3142 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3143 if (linkProperties != null) {
3144 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3145 }
3146 }
3147 return info.primaryUnderlyingIface == null ? null : info;
3148 }
3149
3150 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003151 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3152 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003153 * Permissions are checked in Vpn class.
3154 * @hide
3155 */
3156 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003157 public VpnConfig getVpnConfig(int userId) {
3158 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003159 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003160 return mVpns.get(userId).getVpnConfig();
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003161 }
3162 }
3163
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003164 @Override
3165 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003166 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3167 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3168 return false;
3169 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003170
3171 // Tear down existing lockdown if profile was removed
3172 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3173 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003174 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003175 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3176 return false;
3177 }
3178
3179 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3180 final VpnProfile profile = VpnProfile.decode(
3181 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003182 int user = UserHandle.getUserId(Binder.getCallingUid());
3183 synchronized(mVpns) {
3184 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3185 profile));
3186 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003187 } else {
3188 setLockdownTracker(null);
3189 }
3190
3191 return true;
3192 }
3193
3194 /**
3195 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3196 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3197 */
3198 private void setLockdownTracker(LockdownVpnTracker tracker) {
3199 // Shutdown any existing tracker
3200 final LockdownVpnTracker existing = mLockdownTracker;
3201 mLockdownTracker = null;
3202 if (existing != null) {
3203 existing.shutdown();
3204 }
3205
3206 try {
3207 if (tracker != null) {
3208 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003209 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003210 mLockdownTracker = tracker;
3211 mLockdownTracker.init();
3212 } else {
3213 mNetd.setFirewallEnabled(false);
3214 }
3215 } catch (RemoteException e) {
3216 // ignored; NMS lives inside system_server
3217 }
3218 }
3219
3220 private void throwIfLockdownEnabled() {
3221 if (mLockdownEnabled) {
3222 throw new IllegalStateException("Unavailable in lockdown mode");
3223 }
3224 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003225
Wink Savilleab9321d2013-06-29 21:10:57 -07003226 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003227 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003228 // TODO: Remove? Any reason to trigger a provisioning check?
3229 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003230 }
3231
3232 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3233 private volatile boolean mIsNotificationVisible = false;
3234
Paul Jensen89e0f092014-09-15 15:59:36 -04003235 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003236 if (DBG) {
3237 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003238 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003239 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003240 Intent intent = new Intent(action);
3241 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003242 // Concatenate the range of types onto the range of NetIDs.
3243 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003244 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003245 }
3246
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003247 /**
3248 * Show or hide network provisioning notificaitons.
3249 *
3250 * @param id an identifier that uniquely identifies this notification. This must match
3251 * between show and hide calls. We use the NetID value but for legacy callers
3252 * we concatenate the range of types with the range of NetIDs.
3253 */
3254 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003255 String extraInfo, PendingIntent intent) {
3256 if (DBG) {
3257 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3258 networkType + " extraInfo=" + extraInfo);
3259 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003260
3261 Resources r = Resources.getSystem();
3262 NotificationManager notificationManager = (NotificationManager) mContext
3263 .getSystemService(Context.NOTIFICATION_SERVICE);
3264
3265 if (visible) {
3266 CharSequence title;
3267 CharSequence details;
3268 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003269 Notification notification = new Notification();
3270 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003271 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003272 title = r.getString(R.string.wifi_available_sign_in, 0);
3273 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003274 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003275 icon = R.drawable.stat_notify_wifi_in_range;
3276 break;
3277 case ConnectivityManager.TYPE_MOBILE:
3278 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003279 title = r.getString(R.string.network_available_sign_in, 0);
3280 // TODO: Change this to pull from NetworkInfo once a printable
3281 // name has been added to it
3282 details = mTelephonyManager.getNetworkOperatorName();
3283 icon = R.drawable.stat_notify_rssi_in_range;
3284 break;
3285 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003286 title = r.getString(R.string.network_available_sign_in, 0);
3287 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003288 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003289 icon = R.drawable.stat_notify_rssi_in_range;
3290 break;
3291 }
3292
Wink Savilleab9321d2013-06-29 21:10:57 -07003293 notification.when = 0;
3294 notification.icon = icon;
3295 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003296 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003297 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003298 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003299 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003300 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003301
Wink Saville948282b2013-08-29 08:55:16 -07003302 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003303 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003304 } catch (NullPointerException npe) {
3305 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3306 npe.printStackTrace();
3307 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003308 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003309 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003310 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003311 } catch (NullPointerException npe) {
3312 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3313 npe.printStackTrace();
3314 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003315 }
Wink Saville948282b2013-08-29 08:55:16 -07003316 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003317 }
3318
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003319 /** Location to an updatable file listing carrier provisioning urls.
3320 * An example:
3321 *
3322 * <?xml version="1.0" encoding="utf-8"?>
3323 * <provisioningUrls>
3324 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3325 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3326 * </provisioningUrls>
3327 */
3328 private static final String PROVISIONING_URL_PATH =
3329 "/data/misc/radio/provisioning_urls.xml";
3330 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003331
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003332 /** XML tag for root element. */
3333 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3334 /** XML tag for individual url */
3335 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3336 /** XML tag for redirected url */
3337 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3338 /** XML attribute for mcc */
3339 private static final String ATTR_MCC = "mcc";
3340 /** XML attribute for mnc */
3341 private static final String ATTR_MNC = "mnc";
3342
3343 private static final int REDIRECTED_PROVISIONING = 1;
3344 private static final int PROVISIONING = 2;
3345
3346 private String getProvisioningUrlBaseFromFile(int type) {
3347 FileReader fileReader = null;
3348 XmlPullParser parser = null;
3349 Configuration config = mContext.getResources().getConfiguration();
3350 String tagType;
3351
3352 switch (type) {
3353 case PROVISIONING:
3354 tagType = TAG_PROVISIONING_URL;
3355 break;
3356 case REDIRECTED_PROVISIONING:
3357 tagType = TAG_REDIRECTED_URL;
3358 break;
3359 default:
3360 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3361 type);
3362 }
3363
3364 try {
3365 fileReader = new FileReader(mProvisioningUrlFile);
3366 parser = Xml.newPullParser();
3367 parser.setInput(fileReader);
3368 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3369
3370 while (true) {
3371 XmlUtils.nextElement(parser);
3372
3373 String element = parser.getName();
3374 if (element == null) break;
3375
3376 if (element.equals(tagType)) {
3377 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3378 try {
3379 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3380 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3381 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3382 parser.next();
3383 if (parser.getEventType() == XmlPullParser.TEXT) {
3384 return parser.getText();
3385 }
3386 }
3387 }
3388 } catch (NumberFormatException e) {
3389 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3390 }
3391 }
3392 }
3393 return null;
3394 } catch (FileNotFoundException e) {
3395 loge("Carrier Provisioning Urls file not found");
3396 } catch (XmlPullParserException e) {
3397 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3398 } catch (IOException e) {
3399 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3400 } finally {
3401 if (fileReader != null) {
3402 try {
3403 fileReader.close();
3404 } catch (IOException e) {}
3405 }
3406 }
3407 return null;
3408 }
3409
Wink Saville42d4f082013-07-20 20:31:59 -07003410 @Override
3411 public String getMobileRedirectedProvisioningUrl() {
3412 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003413 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3414 if (TextUtils.isEmpty(url)) {
3415 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3416 }
3417 return url;
3418 }
3419
Wink Saville42d4f082013-07-20 20:31:59 -07003420 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003421 public String getMobileProvisioningUrl() {
3422 enforceConnectivityInternalPermission();
3423 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3424 if (TextUtils.isEmpty(url)) {
3425 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003426 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003427 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003428 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003429 }
Wink Saville8cf35602013-07-10 23:00:07 -07003430 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003431 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003432 String phoneNumber = mTelephonyManager.getLine1Number();
3433 if (TextUtils.isEmpty(phoneNumber)) {
3434 phoneNumber = "0000000000";
3435 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003436 url = String.format(url,
3437 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3438 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003439 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003440 }
3441
Wink Savilleab9321d2013-06-29 21:10:57 -07003442 return url;
3443 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003444
Wink Saville948282b2013-08-29 08:55:16 -07003445 @Override
3446 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003447 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003448 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003449 final long ident = Binder.clearCallingIdentity();
3450 try {
3451 setProvNotificationVisible(visible, networkType, action);
3452 } finally {
3453 Binder.restoreCallingIdentity(ident);
3454 }
Wink Saville948282b2013-08-29 08:55:16 -07003455 }
Wink Saville7788c612013-08-29 14:57:08 -07003456
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003457 @Override
3458 public void setAirplaneMode(boolean enable) {
3459 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003460 final long ident = Binder.clearCallingIdentity();
3461 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003462 final ContentResolver cr = mContext.getContentResolver();
3463 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3464 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3465 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003466 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003467 } finally {
3468 Binder.restoreCallingIdentity(ident);
3469 }
3470 }
3471
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003472 private void onUserStart(int userId) {
3473 synchronized(mVpns) {
3474 Vpn userVpn = mVpns.get(userId);
3475 if (userVpn != null) {
3476 loge("Starting user already has a VPN");
3477 return;
3478 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003479 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003480 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003481 }
3482 }
3483
3484 private void onUserStop(int userId) {
3485 synchronized(mVpns) {
3486 Vpn userVpn = mVpns.get(userId);
3487 if (userVpn == null) {
3488 loge("Stopping user has no VPN");
3489 return;
3490 }
3491 mVpns.delete(userId);
3492 }
3493 }
3494
3495 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3496 @Override
3497 public void onReceive(Context context, Intent intent) {
3498 final String action = intent.getAction();
3499 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3500 if (userId == UserHandle.USER_NULL) return;
3501
3502 if (Intent.ACTION_USER_STARTING.equals(action)) {
3503 onUserStart(userId);
3504 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3505 onUserStop(userId);
3506 }
3507 }
3508 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003509
Robert Greenwalta67be032014-05-16 15:49:14 -07003510 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3511 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003512 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3513 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003514
Robert Greenwalta67be032014-05-16 15:49:14 -07003515 private static class NetworkFactoryInfo {
3516 public final String name;
3517 public final Messenger messenger;
3518 public final AsyncChannel asyncChannel;
3519
3520 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3521 this.name = name;
3522 this.messenger = messenger;
3523 this.asyncChannel = asyncChannel;
3524 }
3525 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003526
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003527 /**
3528 * Tracks info about the requester.
3529 * Also used to notice when the calling process dies so we can self-expire
3530 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003531 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3532 static final boolean REQUEST = true;
3533 static final boolean LISTEN = false;
3534
3535 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003536 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003537 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003538 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003539 final int mPid;
3540 final int mUid;
3541 final Messenger messenger;
3542 final boolean isRequest;
3543
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003544 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3545 request = r;
3546 mPendingIntent = pi;
3547 messenger = null;
3548 mBinder = null;
3549 mPid = getCallingPid();
3550 mUid = getCallingUid();
3551 this.isRequest = isRequest;
3552 }
3553
Robert Greenwalt9258c642014-03-26 16:47:06 -07003554 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3555 super();
3556 messenger = m;
3557 request = r;
3558 mBinder = binder;
3559 mPid = getCallingPid();
3560 mUid = getCallingUid();
3561 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003562 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003563
3564 try {
3565 mBinder.linkToDeath(this, 0);
3566 } catch (RemoteException e) {
3567 binderDied();
3568 }
3569 }
3570
3571 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003572 if (mBinder != null) {
3573 mBinder.unlinkToDeath(this, 0);
3574 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003575 }
3576
3577 public void binderDied() {
3578 log("ConnectivityService NetworkRequestInfo binderDied(" +
3579 request + ", " + mBinder + ")");
3580 releaseNetworkRequest(request);
3581 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003582
3583 public String toString() {
3584 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003585 mPid + " for " + request +
3586 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003587 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003588 }
3589
3590 @Override
3591 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003592 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003593 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003594 enforceNetworkRequestPermissions(networkCapabilities);
3595 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003596
Robert Greenwalt6078b502014-06-11 16:05:07 -07003597 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003598 throw new IllegalArgumentException("Bad timeout specified");
3599 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003600
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003601 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3602 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003603 if (DBG) log("requestNetwork for " + networkRequest);
3604 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3605 NetworkRequestInfo.REQUEST);
3606
3607 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003608 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003609 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003610 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003611 }
3612 return networkRequest;
3613 }
3614
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003615 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003616 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003617 enforceConnectivityInternalPermission();
3618 } else {
3619 enforceChangePermission();
3620 }
3621 }
3622
fenglub15e72b2015-03-20 11:29:56 -07003623 @Override
fengludb571472015-04-21 17:12:05 -07003624 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003625 enforceAccessPermission();
3626 NetworkAgentInfo nai = null;
3627 if (network == null) {
3628 return false;
3629 }
3630 synchronized (mNetworkForNetId) {
3631 nai = mNetworkForNetId.get(network.netId);
3632 }
3633 if (nai != null) {
3634 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3635 return true;
3636 }
3637 return false;
3638 }
3639
3640
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003641 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3642 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003643 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003644 final int uidRules;
3645 final int uid = Binder.getCallingUid();
3646 synchronized(mRulesLock) {
3647 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3648 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003649 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003650 // we could silently fail or we can filter the available nets to only give
3651 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003652 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003653 }
3654 }
3655 }
3656
Robert Greenwalt9258c642014-03-26 16:47:06 -07003657 @Override
3658 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3659 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003660 checkNotNull(operation, "PendingIntent cannot be null.");
3661 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3662 enforceNetworkRequestPermissions(networkCapabilities);
3663 enforceMeteredApnPolicy(networkCapabilities);
3664
3665 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3666 nextNetworkRequestId());
3667 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3668 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3669 NetworkRequestInfo.REQUEST);
3670 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3671 nri));
3672 return networkRequest;
3673 }
3674
Jeremy Joslin79294842014-12-03 17:15:28 -08003675 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3676 mHandler.sendMessageDelayed(
3677 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3678 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3679 }
3680
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003681 @Override
3682 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003683 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003684 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3685 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003686 }
3687
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003688 // In order to implement the compatibility measure for pre-M apps that call
3689 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3690 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3691 // This ensures it has permission to do so.
3692 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3693 if (nc == null) {
3694 return false;
3695 }
3696 int[] transportTypes = nc.getTransportTypes();
3697 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3698 return false;
3699 }
3700 try {
3701 mContext.enforceCallingOrSelfPermission(
3702 android.Manifest.permission.ACCESS_WIFI_STATE,
3703 "ConnectivityService");
3704 } catch (SecurityException e) {
3705 return false;
3706 }
3707 return true;
3708 }
3709
Robert Greenwalt9258c642014-03-26 16:47:06 -07003710 @Override
3711 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3712 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003713 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3714 enforceAccessPermission();
3715 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003716
3717 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003718 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003719 if (DBG) log("listenForNetwork for " + networkRequest);
3720 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3721 NetworkRequestInfo.LISTEN);
3722
3723 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3724 return networkRequest;
3725 }
3726
3727 @Override
3728 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3729 PendingIntent operation) {
3730 }
3731
3732 @Override
3733 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003734 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3735 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003736 }
3737
3738 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003739 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003740 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003741 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3742 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003743 }
3744
Robert Greenwalta67be032014-05-16 15:49:14 -07003745 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003746 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003747 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3748 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3749 }
3750
3751 @Override
3752 public void unregisterNetworkFactory(Messenger messenger) {
3753 enforceConnectivityInternalPermission();
3754 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3755 }
3756
3757 private void handleUnregisterNetworkFactory(Messenger messenger) {
3758 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3759 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003760 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003761 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003762 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003763 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003764 }
3765
Robert Greenwalt7b816022014-04-18 15:25:25 -07003766 /**
3767 * NetworkAgentInfo supporting a request by requestId.
3768 * These have already been vetted (their Capabilities satisfy the request)
3769 * and the are the highest scored network available.
3770 * the are keyed off the Requests requestId.
3771 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003772 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003773 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3774 new SparseArray<NetworkAgentInfo>();
3775
Paul Jensen31a94f42015-02-13 14:18:39 -05003776 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3777 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003778 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3779 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003780 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3781 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3782 // there may not be a strict 1:1 correlation between the two.
3783 @GuardedBy("mNetworkForNetId")
3784 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003785
Robert Greenwalt7b816022014-04-18 15:25:25 -07003786 // NetworkAgentInfo keyed off its connecting messenger
3787 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003788 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003789 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3790 new HashMap<Messenger, NetworkAgentInfo>();
3791
Paul Jensen2c311d62014-11-17 12:34:51 -05003792 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003793 private final NetworkRequest mDefaultRequest;
3794
Erik Klineda4bfa82015-04-30 12:58:40 +09003795 // Request used to optionally keep mobile data active even when higher
3796 // priority networks like Wi-Fi are active.
3797 private final NetworkRequest mDefaultMobileDataRequest;
3798
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003799 private NetworkAgentInfo getDefaultNetwork() {
3800 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3801 }
3802
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003803 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003804 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003805 }
3806
Paul Jensen31a94f42015-02-13 14:18:39 -05003807 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003808 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003809 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003810 enforceConnectivityInternalPermission();
3811
Paul Jensen2c311d62014-11-17 12:34:51 -05003812 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3813 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003814 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003815 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3816 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3817 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003818 synchronized (this) {
3819 nai.networkMonitor.systemReady = mSystemReady;
3820 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003821 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003822 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003823 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003824 }
3825
3826 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3827 if (VDBG) log("Got NetworkAgent Messenger");
3828 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003829 synchronized (mNetworkForNetId) {
3830 mNetworkForNetId.put(na.network.netId, na);
3831 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003832 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3833 NetworkInfo networkInfo = na.networkInfo;
3834 na.networkInfo = null;
3835 updateNetworkInfo(na, networkInfo);
3836 }
3837
3838 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3839 LinkProperties newLp = networkAgent.linkProperties;
3840 int netId = networkAgent.network.netId;
3841
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003842 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3843 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003844 if (networkAgent.clatd != null) {
3845 networkAgent.clatd.fixupLinkProperties(oldLp);
3846 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003847
Paul Jensen992f2522014-04-28 10:33:11 -04003848 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003849 updateMtu(newLp, oldLp);
3850 // TODO - figure out what to do for clat
3851// for (LinkProperties lp : newLp.getStackedLinks()) {
3852// updateMtu(lp, null);
3853// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003854 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003855
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003856 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3857 // In L, we used it only when the network had Internet access but provided no DNS servers.
3858 // For now, just disable it, and if disabling it doesn't break things, remove it.
3859 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3860 // NET_CAPABILITY_INTERNET);
3861 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003862 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003863 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3864
Paul Jensen3b759822014-05-13 11:44:01 -04003865 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003866 if (isDefaultNetwork(networkAgent)) {
3867 handleApplyDefaultProxy(newLp.getHttpProxy());
3868 } else {
3869 updateProxy(newLp, oldLp, networkAgent);
3870 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003871 // TODO - move this check to cover the whole function
3872 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003873 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003874 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3875 }
Paul Jensen3b759822014-05-13 11:44:01 -04003876 }
3877
Lorenzo Colitti95439462014-10-09 13:44:48 +09003878 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3879 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3880 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003881
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003882 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003883 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3884 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003885 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003886 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003887 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003888 }
Paul Jensen992f2522014-04-28 10:33:11 -04003889
3890 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3891 CompareResult<String> interfaceDiff = new CompareResult<String>();
3892 if (oldLp != null) {
3893 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3894 } else if (newLp != null) {
3895 interfaceDiff.added = newLp.getAllInterfaceNames();
3896 }
3897 for (String iface : interfaceDiff.added) {
3898 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003899 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003900 mNetd.addInterfaceToNetwork(iface, netId);
3901 } catch (Exception e) {
3902 loge("Exception adding interface: " + e);
3903 }
3904 }
3905 for (String iface : interfaceDiff.removed) {
3906 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003907 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003908 mNetd.removeInterfaceFromNetwork(iface, netId);
3909 } catch (Exception e) {
3910 loge("Exception removing interface: " + e);
3911 }
3912 }
3913 }
3914
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003915 /**
3916 * Have netd update routes from oldLp to newLp.
3917 * @return true if routes changed between oldLp and newLp
3918 */
3919 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003920 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3921 if (oldLp != null) {
3922 routeDiff = oldLp.compareAllRoutes(newLp);
3923 } else if (newLp != null) {
3924 routeDiff.added = newLp.getAllRoutes();
3925 }
3926
3927 // add routes before removing old in case it helps with continuous connectivity
3928
3929 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3930 for (RouteInfo route : routeDiff.added) {
3931 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003932 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003933 try {
3934 mNetd.addRoute(netId, route);
3935 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003936 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3937 loge("Exception in addRoute for non-gateway: " + e);
3938 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003939 }
3940 }
3941 for (RouteInfo route : routeDiff.added) {
3942 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003943 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003944 try {
3945 mNetd.addRoute(netId, route);
3946 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003947 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3948 loge("Exception in addRoute for gateway: " + e);
3949 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003950 }
3951 }
3952
3953 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003954 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003955 try {
3956 mNetd.removeRoute(netId, route);
3957 } catch (Exception e) {
3958 loge("Exception in removeRoute: " + e);
3959 }
3960 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003961 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003962 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003963 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3964 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003965 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003966 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003967 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003968 dnses = new ArrayList();
3969 dnses.add(mDefaultDns);
3970 if (DBG) {
3971 loge("no dns provided for netId " + netId + ", so using defaults");
3972 }
3973 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003974 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003975 try {
3976 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3977 newLp.getDomains());
3978 } catch (Exception e) {
3979 loge("Exception in setDnsServersForNetwork: " + e);
3980 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003981 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3982 if (defaultNai != null && defaultNai.network.netId == netId) {
3983 setDefaultDnsSystemProperties(dnses);
3984 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003985 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003986 } else if (flush) {
3987 try {
3988 mNetd.flushNetworkDnsCache(netId);
3989 } catch (Exception e) {
3990 loge("Exception in flushNetworkDnsCache: " + e);
3991 }
3992 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003993 }
3994 }
3995
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003996 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3997 int last = 0;
3998 for (InetAddress dns : dnses) {
3999 ++last;
4000 String key = "net.dns" + last;
4001 String value = dns.getHostAddress();
4002 SystemProperties.set(key, value);
4003 }
4004 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4005 String key = "net.dns" + i;
4006 SystemProperties.set(key, "");
4007 }
4008 mNumDnsEntries = last;
4009 }
4010
Robert Greenwalt7b816022014-04-18 15:25:25 -07004011 private void updateCapabilities(NetworkAgentInfo networkAgent,
4012 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004013 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4014 synchronized (networkAgent) {
4015 networkAgent.networkCapabilities = networkCapabilities;
4016 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004017 if (networkAgent.lastValidated) {
4018 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4019 // There's no need to remove the capability if we think the network is unvalidated,
4020 // because NetworkAgents don't set the validated capability.
4021 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08004022 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004023 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004024 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004025 }
4026
Paul Jensenc8b9a742014-09-30 15:37:41 -04004027 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4028 for (int i = 0; i < nai.networkRequests.size(); i++) {
4029 NetworkRequest nr = nai.networkRequests.valueAt(i);
4030 // Don't send listening requests to factories. b/17393458
4031 if (!isRequest(nr)) continue;
4032 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4033 }
4034 }
4035
Robert Greenwalt7b816022014-04-18 15:25:25 -07004036 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4037 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004038 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004039 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4040 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004041 }
4042 }
4043
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004044 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4045 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004046 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004047 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004048 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4049 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004050 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004051 sendIntent(nri.mPendingIntent, intent);
4052 }
4053 // else not handled
4054 }
4055
4056 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4057 mPendingIntentWakeLock.acquire();
4058 try {
4059 if (DBG) log("Sending " + pendingIntent);
4060 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4061 } catch (PendingIntent.CanceledException e) {
4062 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4063 mPendingIntentWakeLock.release();
4064 releasePendingNetworkRequest(pendingIntent);
4065 }
4066 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4067 }
4068
4069 @Override
4070 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4071 String resultData, Bundle resultExtras) {
4072 if (DBG) log("Finished sending " + pendingIntent);
4073 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004074 // Release with a delay so the receiving client has an opportunity to put in its
4075 // own request.
4076 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004077 }
4078
Robert Greenwalt9258c642014-03-26 16:47:06 -07004079 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004080 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004081 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004082 Bundle bundle = new Bundle();
4083 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4084 new NetworkRequest(nri.request));
4085 Message msg = Message.obtain();
4086 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4087 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4088 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4089 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004090 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004091 case ConnectivityManager.CALLBACK_LOSING: {
4092 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4093 break;
4094 }
4095 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4096 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4097 new NetworkCapabilities(networkAgent.networkCapabilities));
4098 break;
4099 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004100 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004101 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4102 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004103 break;
4104 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004105 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004106 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004107 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004108 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004109 if (VDBG) {
4110 log("sending notification " + notifyTypeToName(notificationType) +
4111 " for " + nri.request);
4112 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 nri.messenger.send(msg);
4114 } catch (RemoteException e) {
4115 // may occur naturally in the race of binder death.
4116 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4117 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004118 }
4119
Paul Jensenc8b9a742014-09-30 15:37:41 -04004120 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4121 for (int i = 0; i < nai.networkRequests.size(); i++) {
4122 NetworkRequest nr = nai.networkRequests.valueAt(i);
4123 // Ignore listening requests.
4124 if (!isRequest(nr)) continue;
4125 loge("Dead network still had at least " + nr);
4126 break;
4127 }
4128 nai.asyncChannel.disconnect();
4129 }
4130
Robert Greenwalt7b816022014-04-18 15:25:25 -07004131 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4132 if (oldNetwork == null) {
4133 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4134 return;
4135 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004136 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4137 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004138 }
4139
Paul Jensen27b02b72014-07-14 12:03:33 -04004140 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004141 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004142 setupDataActivityTracking(newNetwork);
4143 try {
4144 mNetd.setDefaultNetId(newNetwork.network.netId);
4145 } catch (Exception e) {
4146 loge("Exception setting default network :" + e);
4147 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004148 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004149 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004150 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004151 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004152 }
4153
Paul Jensen2161a8e2014-09-11 11:00:39 -04004154 // Handles a network appearing or improving its score.
4155 //
4156 // - Evaluates all current NetworkRequests that can be
4157 // satisfied by newNetwork, and reassigns to newNetwork
4158 // any such requests for which newNetwork is the best.
4159 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004160 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004161 // needed. A network is needed if it is the best network for
4162 // one or more NetworkRequests, or if it is a VPN.
4163 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004164 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004165 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4166 //
4167 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4168 // networks that have no chance (i.e. even if validated)
4169 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004170 //
4171 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4172 // it does not remove NetworkRequests that other Networks could better satisfy.
4173 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4174 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4175 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004176 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004177 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004178 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004179 // torn down if unneeded.
4180 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4181 // performed to tear down unvalidated networks that have no chance (i.e. even if
4182 // validated) of becoming the highest scoring network.
4183 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4184 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004185 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004186 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004187 loge("ERROR: nascent network not validated.");
4188 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004189 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004190 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004191 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004192 if (DBG) log("rematching " + newNetwork.name());
4193 // Find and migrate to this Network any NetworkRequests for
4194 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004195 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004196 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004197 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004198 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4199 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004200 if (DBG) {
4201 log("Network " + newNetwork.name() + " was already satisfying" +
4202 " request " + nri.request.requestId + ". No change.");
4203 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004204 keep = true;
4205 continue;
4206 }
4207
4208 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004209 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004210 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004211 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004212 // This is not a request, it's a callback listener.
4213 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004214 newNetwork.addRequest(nri.request);
4215 continue;
4216 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004217
Robert Greenwalt7b816022014-04-18 15:25:25 -07004218 // next check if it's better than any current network we're using for
4219 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004220 if (VDBG) {
4221 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004222 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4223 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004224 }
4225 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004226 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004227 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004228 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004229 currentNetwork.networkRequests.remove(nri.request.requestId);
4230 currentNetwork.networkLingered.add(nri.request);
4231 affectedNetworks.add(currentNetwork);
4232 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004233 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004234 }
Paul Jensen573a0352015-01-08 10:49:34 -05004235 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004236 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004237 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004238 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004239 // Tell NetworkFactories about the new score, so they can stop
4240 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004241 // TODO - this could get expensive if we have alot of requests for this
4242 // network. Think about if there is a way to reduce this. Push
4243 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004244 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004245 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004246 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004247 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004248 }
4249 }
4250 }
4251 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004252 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004253 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004254 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004255 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4256 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4257 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004258 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004259 }
4260 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004261 if (keep) {
4262 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004263 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004264 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004265 synchronized (ConnectivityService.this) {
4266 // have a new default network, release the transition wakelock in
4267 // a second if it's held. The second pause is to allow apps
4268 // to reconnect over the new network
4269 if (mNetTransitionWakeLock.isHeld()) {
4270 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4271 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4272 mNetTransitionWakeLockSerialNumber, 0),
4273 1000);
4274 }
4275 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004276 }
4277
4278 // do this after the default net is switched, but
4279 // before LegacyTypeTracker sends legacy broadcasts
4280 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4281
4282 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004283 // Maintain the illusion: since the legacy API only
4284 // understands one network at a time, we must pretend
4285 // that the current default network disconnected before
4286 // the new one connected.
4287 if (oldDefaultNetwork != null) {
4288 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004289 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004290 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004291 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004292 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4293 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004294 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004295
4296 // Notify battery stats service about this network, both the normal
4297 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004298 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004299 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004300 final IBatteryStats bs = BatteryStatsService.getService();
4301 final int type = newNetwork.networkInfo.getType();
4302
4303 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4304 bs.noteNetworkInterfaceType(baseIface, type);
4305 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4306 final String stackedIface = stacked.getInterfaceName();
4307 bs.noteNetworkInterfaceType(stackedIface, type);
4308 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4309 }
4310 } catch (RemoteException ignored) {
4311 }
4312
Robert Greenwalt152ed372014-12-17 17:19:53 -08004313 // This has to happen after the notifyNetworkCallbacks as that tickles each
4314 // ConnectivityManager instance so that legacy requests correctly bind dns
4315 // requests to this network. The legacy users are listening for this bcast
4316 // and will generally do a dns request so they can ensureRouteToHost and if
4317 // they do that before the callbacks happen they'll use the default network.
4318 //
4319 // TODO: Is there still a race here? We send the broadcast
4320 // after sending the callback, but if the app can receive the
4321 // broadcast before the callback, it might still break.
4322 //
4323 // This *does* introduce a race where if the user uses the new api
4324 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4325 // they may get old info. Reverse this after the old startUsing api is removed.
4326 // This is on top of the multiple intent sequencing referenced in the todo above.
4327 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4328 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4329 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4330 // legacy type tracker filters out repeat adds
4331 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4332 }
4333 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004334
4335 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4336 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4337 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4338 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4339 if (newNetwork.isVPN()) {
4340 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4341 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004342 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004343 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004344 // validated (and get evaluated against peers, one losing here), or get reaped (see
4345 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4346 // network. Networks that have been up for a while and are validated should be torn
4347 // down via the lingering process so communication on that network is given time to
4348 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004349 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004350 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004351 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004352 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4353 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004354 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004355 if (DBG) log("Reaping " + nai.name());
4356 teardownUnneededNetwork(nai);
4357 }
4358 }
4359 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004360 }
4361
Paul Jensen2161a8e2014-09-11 11:00:39 -04004362 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4363 // being disconnected.
4364 // If only one Network's score or capabilities have been modified since the last time
4365 // this function was called, pass this Network in via the "changed" arugment, otherwise
4366 // pass null.
4367 // If only one Network has been changed but its NetworkCapabilities have not changed,
4368 // pass in the Network's score (from getCurrentScore()) prior to the change via
4369 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4370 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4371 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4372 // to avoid the slowness. It is not simply enough to process just "changed", for
4373 // example in the case where "changed"'s score decreases and another network should begin
4374 // satifying a NetworkRequest that "changed" currently satisfies.
4375
4376 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4377 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4378 // rematchNetworkAndRequests() handles.
4379 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004380 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4381 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004382 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004383 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4384 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4385 NascentState.NOT_JUST_VALIDATED,
4386 // Only reap the last time through the loop. Reaping before all rematching
4387 // is complete could incorrectly teardown a network that hasn't yet been
4388 // rematched.
4389 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4390 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004391 }
4392 }
4393 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004394
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004395 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004396 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004397 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004398 // For now only update icons for default connection.
4399 // TODO: Update WiFi and cellular icons separately. b/17237507
4400 if (!isDefaultNetwork(nai)) return;
4401
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004402 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004403 // Don't repeat publish.
4404 if (newInetCondition == mDefaultInetConditionPublished) return;
4405
4406 mDefaultInetConditionPublished = newInetCondition;
4407 sendInetConditionBroadcast(nai.networkInfo);
4408 }
4409
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004410 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4411 if (mLockdownTracker != null) {
4412 if (nai != null && nai.isVPN()) {
4413 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4414 } else {
4415 mLockdownTracker.onNetworkInfoChanged();
4416 }
4417 }
4418 }
4419
Robert Greenwalt7b816022014-04-18 15:25:25 -07004420 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4421 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004422 NetworkInfo oldInfo = null;
4423 synchronized (networkAgent) {
4424 oldInfo = networkAgent.networkInfo;
4425 networkAgent.networkInfo = newInfo;
4426 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004427 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004428
4429 if (oldInfo != null && oldInfo.getState() == state) {
4430 if (VDBG) log("ignoring duplicate network state non-change");
4431 return;
4432 }
4433 if (DBG) {
4434 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4435 (oldInfo == null ? "null" : oldInfo.getState()) +
4436 " to " + state);
4437 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004438
Paul Jenseneec75412014-08-04 12:21:19 -04004439 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004440 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004441 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004442 if (networkAgent.isVPN()) {
4443 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004444 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4445 (networkAgent.networkMisc == null ||
4446 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004447 } else {
4448 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4449 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004450 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004451 loge("Error creating network " + networkAgent.network.netId + ": "
4452 + e.getMessage());
4453 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004454 }
Paul Jenseneec75412014-08-04 12:21:19 -04004455 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004456 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004457 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004458
Paul Jensenca8f16a2014-05-09 12:47:55 -04004459 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004460 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004461
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004462 if (networkAgent.isVPN()) {
4463 // Temporarily disable the default proxy (not global).
4464 synchronized (mProxyLock) {
4465 if (!mDefaultProxyDisabled) {
4466 mDefaultProxyDisabled = true;
4467 if (mGlobalProxy == null && mDefaultProxy != null) {
4468 sendProxyBroadcast(null);
4469 }
4470 }
4471 }
4472 // TODO: support proxy per network.
4473 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004474
Paul Jensen2161a8e2014-09-11 11:00:39 -04004475 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004476 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4477 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004478
4479 // This has to happen after matching the requests, because callbacks are just requests.
4480 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004481 } else if (state == NetworkInfo.State.DISCONNECTED ||
4482 state == NetworkInfo.State.SUSPENDED) {
4483 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004484 if (networkAgent.isVPN()) {
4485 synchronized (mProxyLock) {
4486 if (mDefaultProxyDisabled) {
4487 mDefaultProxyDisabled = false;
4488 if (mGlobalProxy == null && mDefaultProxy != null) {
4489 sendProxyBroadcast(mDefaultProxy);
4490 }
4491 }
4492 }
4493 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004494 }
4495 }
4496
Robert Greenwaltac96c522014-06-03 16:43:57 -07004497 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4498 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004499 if (score < 0) {
4500 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4501 "). Bumping score to min of 0");
4502 score = 0;
4503 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004504
Paul Jensen2161a8e2014-09-11 11:00:39 -04004505 final int oldScore = nai.getCurrentScore();
4506 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004507
Paul Jensen57a767f2014-11-19 13:01:46 -05004508 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004509
Paul Jensenc8b9a742014-09-30 15:37:41 -04004510 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004511 }
4512
Robert Greenwalt9258c642014-03-26 16:47:06 -07004513 // notify only this one new request of the current state
4514 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4515 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4516 // TODO - read state from monitor to decide what to send.
4517// if (nai.networkMonitor.isLingering()) {
4518// notifyType = NetworkCallbacks.LOSING;
4519// } else if (nai.networkMonitor.isEvaluating()) {
4520// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4521// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004522 if (nri.mPendingIntent == null) {
4523 callCallbackForRequest(nri, nai, notifyType);
4524 } else {
4525 sendPendingIntentForRequest(nri, nai, notifyType);
4526 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004527 }
4528
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004529 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004530 // The NetworkInfo we actually send out has no bearing on the real
4531 // state of affairs. For example, if the default connection is mobile,
4532 // and a request for HIPRI has just gone away, we need to pretend that
4533 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4534 // the state to DISCONNECTED, even though the network is of type MOBILE
4535 // and is still connected.
4536 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4537 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004538 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004539 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004540 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004541 } else {
Feixiong Zhang376133f2015-06-01 18:07:58 -07004542 info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004543 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4544 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4545 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4546 if (info.isFailover()) {
4547 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4548 nai.networkInfo.setFailover(false);
4549 }
4550 if (info.getReason() != null) {
4551 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4552 }
4553 if (info.getExtraInfo() != null) {
4554 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4555 }
4556 NetworkAgentInfo newDefaultAgent = null;
4557 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4558 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4559 if (newDefaultAgent != null) {
4560 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4561 newDefaultAgent.networkInfo);
4562 } else {
4563 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4564 }
4565 }
4566 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4567 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004568 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004569 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004570 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004571 }
4572 }
4573 }
4574
Robert Greenwalt7b816022014-04-18 15:25:25 -07004575 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004576 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004577 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004578 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4579 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4580 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004581 if (nri.mPendingIntent == null) {
4582 callCallbackForRequest(nri, networkAgent, notifyType);
4583 } else {
4584 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4585 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004586 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004587 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004588
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004589 private String notifyTypeToName(int notifyType) {
4590 switch (notifyType) {
4591 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4592 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4593 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4594 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4595 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4596 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4597 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4598 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4599 }
4600 return "UNKNOWN";
4601 }
4602
Jeff Sharkey69736342014-12-08 14:50:12 -08004603 /**
4604 * Notify other system services that set of active ifaces has changed.
4605 */
4606 private void notifyIfacesChanged() {
4607 try {
4608 mStatsService.forceUpdateIfaces();
4609 } catch (Exception ignored) {
4610 }
4611 }
4612
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004613 @Override
4614 public boolean addVpnAddress(String address, int prefixLength) {
4615 throwIfLockdownEnabled();
4616 int user = UserHandle.getUserId(Binder.getCallingUid());
4617 synchronized (mVpns) {
4618 return mVpns.get(user).addAddress(address, prefixLength);
4619 }
4620 }
4621
4622 @Override
4623 public boolean removeVpnAddress(String address, int prefixLength) {
4624 throwIfLockdownEnabled();
4625 int user = UserHandle.getUserId(Binder.getCallingUid());
4626 synchronized (mVpns) {
4627 return mVpns.get(user).removeAddress(address, prefixLength);
4628 }
4629 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004630
4631 @Override
4632 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4633 throwIfLockdownEnabled();
4634 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004635 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004636 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004637 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004638 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004639 if (success) {
4640 notifyIfacesChanged();
4641 }
4642 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004643 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004644
4645 @Override
4646 public void factoryReset() {
4647 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004648
4649 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4650 return;
4651 }
4652
Robin Lee3b3dd942015-05-12 18:14:58 +01004653 final int userId = UserHandle.getCallingUserId();
4654
Stuart Scottf1fb3972015-04-02 18:00:02 -07004655 // Turn airplane mode off
4656 setAirplaneMode(false);
4657
Stuart Scotte3e314d2015-04-20 14:07:45 -07004658 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4659 // Untether
4660 for (String tether : getTetheredIfaces()) {
4661 untether(tether);
4662 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004663 }
4664
Stuart Scotte3e314d2015-04-20 14:07:45 -07004665 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4666 // Turn VPN off
4667 VpnConfig vpnConfig = getVpnConfig(userId);
4668 if (vpnConfig != null) {
4669 if (vpnConfig.legacy) {
4670 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4671 } else {
4672 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4673 // in the future without user intervention.
4674 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004675
Stuart Scotte3e314d2015-04-20 14:07:45 -07004676 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4677 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004678 }
4679 }
4680 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004681}