blob: edca4b87842e7dc14c2cf6de557e57bc4f0403ce [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090026import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
27import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070030import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070031import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070033
Wenchao Tongf5ea3402015-03-04 13:26:38 -080034import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070035import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
49import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070050import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070051import android.net.INetworkPolicyListener;
52import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070053import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080054import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070055import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070056import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070057import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070058import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070062import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070063import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070065import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070066import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070067import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040068import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070069import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040071import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070073import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040074import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070076import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070077import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070078import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Looper;
80import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070081import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070082import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070083import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070084import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070085import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070086import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070088import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040089import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070091import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070092import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070093import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070094import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080095import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070096import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -050097import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070098import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070099import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Wink Savilleab9321d2013-06-29 21:10:57 -0700101import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400102import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700103import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700104import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700105import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700106import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800107import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700108import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700109import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700110import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700111import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700112import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700113import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400114import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900115import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700116import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400117import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700119import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800120import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700121import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700122import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700123import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700124import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700125import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700126
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700127import org.xmlpull.v1.XmlPullParser;
128import org.xmlpull.v1.XmlPullParserException;
129
130import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import java.io.FileNotFoundException;
133import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700134import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700136import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700137import java.net.InetAddress;
138import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700139import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700140import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700141import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700142import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700143import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500144import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700145import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700146import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700147import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700148import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150/**
151 * @hide
152 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800153public class ConnectivityService extends IConnectivityManager.Stub
154 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700155 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700157 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700158 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Jake Hamby786e71a2014-02-06 14:43:50 -0800160 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700161
Jeff Sharkey899223b2012-08-04 15:24:58 -0700162 // TODO: create better separation between radio types and network types
163
Robert Greenwalt42acef32009-08-12 16:08:25 -0700164 // how long to wait before switching back to a radio's default network
165 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
166 // system property that can override the above value
167 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
168 "android.telephony.apn-restore";
169
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900170 // How long to wait before putting up a "This network doesn't have an Internet connection,
171 // connect anyway?" dialog after the user selects a network that doesn't validate.
172 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
173
Jeremy Joslin79294842014-12-03 17:15:28 -0800174 // How long to delay to removal of a pending intent based request.
175 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
176 private final int mReleasePendingIntentDelayMs;
177
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800178 private Tethering mTethering;
179
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700180 private final PermissionMonitor mPermissionMonitor;
181
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700182 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700183
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700184 @GuardedBy("mVpns")
185 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700186
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700187 private boolean mLockdownEnabled;
188 private LockdownVpnTracker mLockdownTracker;
189
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700190 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
191 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192 /** Currently active network rules by UID. */
193 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700194 /** Set of ifaces that are costly. */
195 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700196
Erik Klineda4bfa82015-04-30 12:58:40 +0900197 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700199 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700200 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700202 private Object mDnsLock = new Object();
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) {
546 for (int type = 0; type < mTypeLists.length; type++) {
547 if (mTypeLists[type] == null) continue;
548 pw.print(type + " ");
549 pw.increaseIndent();
550 if (mTypeLists[type].size() == 0) pw.println("none");
551 for (NetworkAgentInfo nai : mTypeLists[type]) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900552 pw.println(naiToString(nai));
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700553 }
554 pw.decreaseIndent();
555 }
556 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900557
558 // This class needs its own log method because it has a different TAG.
559 private void log(String s) {
560 Slog.d(TAG, s);
561 }
562
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700563 }
564 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
565
Jeff Sharkey899223b2012-08-04 15:24:58 -0700566 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700567 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800568 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800569
Erik Klineda4bfa82015-04-30 12:58:40 +0900570 mDefaultRequest = createInternetRequestForTransport(-1);
571 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
572 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
573
574 mDefaultMobileDataRequest = createInternetRequestForTransport(
575 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700576
Wink Savillebb08caf2010-09-02 19:23:52 -0700577 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
578 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700579 mHandler = new InternalHandler(handlerThread.getLooper());
580 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700581
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800582 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800583 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
584 String id = Settings.Secure.getString(context.getContentResolver(),
585 Settings.Secure.ANDROID_ID);
586 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700587 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800588 SystemProperties.set("net.hostname", name);
589 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800590 }
591
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700592 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700593 String dns = Settings.Global.getString(context.getContentResolver(),
594 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700595 if (dns == null || dns.length() == 0) {
596 dns = context.getResources().getString(
597 com.android.internal.R.string.config_default_dns_server);
598 }
599 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800600 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
601 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800602 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700603 }
604
Jeremy Joslin79294842014-12-03 17:15:28 -0800605 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
606 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
607
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700608 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700609 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800610 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700611 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700612 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700613 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700614
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700615 try {
616 mPolicyManager.registerListener(mPolicyListener);
617 } catch (RemoteException e) {
618 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700619 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700620 }
621
622 final PowerManager powerManager = (PowerManager) context.getSystemService(
623 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700624 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
625 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
626 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800627 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700628
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700629 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700630
Wink Saville51f456f2013-04-23 14:26:51 -0700631 // TODO: What is the "correct" way to do determine if this is a wifi only device?
632 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
633 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700634 String[] naStrings = context.getResources().getStringArray(
635 com.android.internal.R.array.networkAttributes);
636 for (String naString : naStrings) {
637 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700638 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700639 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700640 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800641 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700642 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700643 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700644 }
Wink Saville51f456f2013-04-23 14:26:51 -0700645 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
646 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
647 n.type);
648 continue;
649 }
Wink Saville975c8482011-04-07 14:23:45 -0700650 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800651 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700652 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700653 continue;
654 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700655 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700656
Wink Saville975c8482011-04-07 14:23:45 -0700657 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700658 mNetworksDefined++;
659 } catch(Exception e) {
660 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700661 }
662 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700663
664 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
665 if (mNetConfigs[TYPE_VPN] == null) {
666 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
667 // don't need to add TYPE_VPN to mNetConfigs.
668 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
669 mNetworksDefined++; // used only in the log() statement below.
670 }
671
Wink Saville5e56bc52013-07-29 15:00:57 -0700672 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700673
Robert Greenwalt50393202011-06-21 17:26:14 -0700674 mProtectedNetworks = new ArrayList<Integer>();
675 int[] protectedNetworks = context.getResources().getIntArray(
676 com.android.internal.R.array.config_protectedNetworks);
677 for (int p : protectedNetworks) {
678 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
679 mProtectedNetworks.add(p);
680 } else {
681 if (DBG) loge("Ignoring protectedNetwork " + p);
682 }
683 }
684
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700685 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
686 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700687
Robert Greenwaltfab501672014-07-23 11:44:01 -0700688 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800689
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700690 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
691
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700692 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700693 IntentFilter intentFilter = new IntentFilter();
694 intentFilter.addAction(Intent.ACTION_USER_STARTING);
695 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
696 mContext.registerReceiverAsUser(
697 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900698
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700699 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700700 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700701 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700702 } catch (RemoteException e) {
703 loge("Error registering observer :" + e);
704 }
705
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700706 if (DBG) {
707 mInetLog = new ArrayList();
708 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700709
Erik Klineda4bfa82015-04-30 12:58:40 +0900710 mSettingsObserver = new SettingsObserver(mContext, mHandler);
711 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800712
John Spurlockbf991a82013-06-24 14:20:23 -0400713 mDataConnectionStats = new DataConnectionStats(mContext);
714 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400715
Jason Monkdecd2952013-10-10 14:02:51 -0400716 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700717
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400718 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800719 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700720
Erik Klineda4bfa82015-04-30 12:58:40 +0900721 private NetworkRequest createInternetRequestForTransport(int transportType) {
722 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900723 netCap.addCapability(NET_CAPABILITY_INTERNET);
724 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900725 if (transportType > -1) {
726 netCap.addTransportType(transportType);
727 }
728 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
729 }
730
731 private void handleMobileDataAlwaysOn() {
732 final boolean enable = (Settings.Global.getInt(
733 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
734 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
735 if (enable == isEnabled) {
736 return; // Nothing to do.
737 }
738
739 if (enable) {
740 handleRegisterNetworkRequest(new NetworkRequestInfo(
741 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
742 } else {
743 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
744 }
745 }
746
747 private void registerSettingsCallbacks() {
748 // Watch for global HTTP proxy changes.
749 mSettingsObserver.observe(
750 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
751 EVENT_APPLY_GLOBAL_HTTP_PROXY);
752
753 // Watch for whether or not to keep mobile data always on.
754 mSettingsObserver.observe(
755 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
756 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
757 }
758
Robert Greenwalt34524f02014-05-18 16:22:10 -0700759 private synchronized int nextNetworkRequestId() {
760 return mNextNetworkRequestId++;
761 }
762
Paul Jensen31a94f42015-02-13 14:18:39 -0500763 private int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400764 synchronized (mNetworkForNetId) {
765 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
766 int netId = mNextNetId;
767 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
768 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500769 if (!mNetIdInUse.get(netId)) {
770 mNetIdInUse.put(netId, true);
771 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400772 }
773 }
774 }
775 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700776 }
777
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800778 private NetworkState getFilteredNetworkState(int networkType, int uid) {
779 NetworkInfo info = null;
780 LinkProperties lp = null;
781 NetworkCapabilities nc = null;
782 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800783 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800784
785 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
786 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
787 if (nai != null) {
788 synchronized (nai) {
789 info = new NetworkInfo(nai.networkInfo);
790 lp = new LinkProperties(nai.linkProperties);
791 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400792 // Network objects are outwardly immutable so there is no point to duplicating.
793 // Duplicating also precludes sharing socket factories and connection pools.
794 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800795 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800796 }
797 info.setType(networkType);
798 } else {
799 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
800 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
801 info.setIsAvailable(true);
802 lp = new LinkProperties();
803 nc = new NetworkCapabilities();
804 network = null;
805 }
806 info = getFilteredNetworkInfo(info, lp, uid);
807 }
808
Jeff Sharkey32566012014-12-02 18:30:14 -0800809 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400810 }
811
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800812 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
813 if (network == null) {
814 return null;
815 }
816 synchronized (mNetworkForNetId) {
817 return mNetworkForNetId.get(network.netId);
818 }
819 };
820
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900821 private Network[] getVpnUnderlyingNetworks(int uid) {
822 if (!mLockdownEnabled) {
823 int user = UserHandle.getUserId(uid);
824 synchronized (mVpns) {
825 Vpn vpn = mVpns.get(user);
826 if (vpn != null && vpn.appliesToUid(uid)) {
827 return vpn.getUnderlyingNetworks();
828 }
829 }
830 }
831 return null;
832 }
833
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800834 private NetworkState getUnfilteredActiveNetworkState(int uid) {
835 NetworkInfo info = null;
836 LinkProperties lp = null;
837 NetworkCapabilities nc = null;
838 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800839 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800840
841 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800842
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900843 final Network[] networks = getVpnUnderlyingNetworks(uid);
844 if (networks != null) {
845 // getUnderlyingNetworks() returns:
846 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
847 // empty array => the VPN explicitly said "no default network".
848 // non-empty array => the VPN specified one or more default networks; we use the
849 // first one.
850 if (networks.length > 0) {
851 nai = getNetworkAgentInfoForNetwork(networks[0]);
852 } else {
853 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800854 }
855 }
856
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800857 if (nai != null) {
858 synchronized (nai) {
859 info = new NetworkInfo(nai.networkInfo);
860 lp = new LinkProperties(nai.linkProperties);
861 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400862 // Network objects are outwardly immutable so there is no point to duplicating.
863 // Duplicating also precludes sharing socket factories and connection pools.
864 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800865 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800866 }
867 }
868
Jeff Sharkey32566012014-12-02 18:30:14 -0800869 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400870 }
871
872 /**
873 * Check if UID should be blocked from using the network with the given LinkProperties.
874 */
875 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700876 final boolean networkCostly;
877 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700878
Robert Greenwalt12e67352014-05-13 21:41:06 -0700879 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700880 synchronized (mRulesLock) {
881 networkCostly = mMeteredIfaces.contains(iface);
882 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700883 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700884
Amith Yamasani15e472352015-04-24 19:06:07 -0700885 if ((uidRules & RULE_REJECT_ALL) != 0
886 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700887 return true;
888 }
889
890 // no restrictive rules; network is visible
891 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700892 }
893
894 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700895 * Return a filtered {@link NetworkInfo}, potentially marked
896 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800897 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700898 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800899 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
900 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400901 // network is blocked; clone and override state
902 info = new NetworkInfo(info);
903 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900904 if (DBG) {
905 log("returning Blocked NetworkInfo for ifname=" +
906 lp.getInterfaceName() + ", uid=" + uid);
907 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700908 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800909 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700910 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700911 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700912 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700913 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700914 }
915
916 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800917 * Return NetworkInfo for the active (i.e., connected) network interface.
918 * It is assumed that at most one network is active at a time. If more
919 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700920 * @return the info for the active network, or {@code null} if none is
921 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800922 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700923 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800924 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700925 enforceAccessPermission();
926 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800927 NetworkState state = getUnfilteredActiveNetworkState(uid);
928 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800929 }
930
Paul Jensen31a94f42015-02-13 14:18:39 -0500931 @Override
932 public Network getActiveNetwork() {
933 enforceAccessPermission();
934 final int uid = Binder.getCallingUid();
935 final int user = UserHandle.getUserId(uid);
936 int vpnNetId = NETID_UNSET;
937 synchronized (mVpns) {
938 final Vpn vpn = mVpns.get(user);
939 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
940 }
941 NetworkAgentInfo nai;
942 if (vpnNetId != NETID_UNSET) {
943 synchronized (mNetworkForNetId) {
944 nai = mNetworkForNetId.get(vpnNetId);
945 }
946 if (nai != null) return nai.network;
947 }
948 nai = getDefaultNetwork();
949 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
950 return nai != null ? nai.network : null;
951 }
952
Wink Saville948282b2013-08-29 08:55:16 -0700953 /**
954 * Find the first Provisioning network.
955 *
956 * @return NetworkInfo or null if none.
957 */
958 private NetworkInfo getProvisioningNetworkInfo() {
959 enforceAccessPermission();
960
961 // Find the first Provisioning Network
962 NetworkInfo provNi = null;
963 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700964 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700965 provNi = ni;
966 break;
967 }
968 }
969 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
970 return provNi;
971 }
972
973 /**
974 * Find the first Provisioning network or the ActiveDefaultNetwork
975 * if there is no Provisioning network
976 *
977 * @return NetworkInfo or null if none.
978 */
979 @Override
980 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
981 enforceAccessPermission();
982
983 NetworkInfo provNi = getProvisioningNetworkInfo();
984 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800985 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700986 }
987 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
988 return provNi;
989 }
990
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700991 public NetworkInfo getActiveNetworkInfoUnfiltered() {
992 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 final int uid = Binder.getCallingUid();
994 NetworkState state = getUnfilteredActiveNetworkState(uid);
995 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700996 }
997
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700998 @Override
999 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1000 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001001 NetworkState state = getUnfilteredActiveNetworkState(uid);
1002 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001003 }
1004
1005 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001006 public NetworkInfo getNetworkInfo(int networkType) {
1007 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001008 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001009 if (getVpnUnderlyingNetworks(uid) != null) {
1010 // A VPN is active, so we may need to return one of its underlying networks. This
1011 // information is not available in LegacyTypeTracker, so we have to get it from
1012 // getUnfilteredActiveNetworkState.
1013 NetworkState state = getUnfilteredActiveNetworkState(uid);
1014 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1015 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1016 }
1017 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 NetworkState state = getFilteredNetworkState(networkType, uid);
1019 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001020 }
1021
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001022 @Override
1023 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1024 enforceAccessPermission();
1025 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001026 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001027 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1028 if (nai != null) {
1029 synchronized (nai) {
1030 info = new NetworkInfo(nai.networkInfo);
1031 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001032 }
1033 }
1034 return info;
1035 }
1036
1037 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001038 public NetworkInfo[] getAllNetworkInfo() {
1039 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001040 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001041 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1042 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001043 NetworkInfo info = getNetworkInfo(networkType);
1044 if (info != null) {
1045 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001046 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001048 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001049 }
1050
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001051 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001052 public Network getNetworkForType(int networkType) {
1053 enforceAccessPermission();
1054 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001055 NetworkState state = getFilteredNetworkState(networkType, uid);
1056 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1057 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001058 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001059 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001060 }
1061
1062 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001063 public Network[] getAllNetworks() {
1064 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001065 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001066 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001067 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001068 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001069 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001070 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001071 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001072 }
1073
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001074 @Override
1075 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1076 // The basic principle is: if an app's traffic could possibly go over a
1077 // network, without the app doing anything multinetwork-specific,
1078 // (hence, by "default"), then include that network's capabilities in
1079 // the array.
1080 //
1081 // In the normal case, app traffic only goes over the system's default
1082 // network connection, so that's the only network returned.
1083 //
1084 // With a VPN in force, some app traffic may go into the VPN, and thus
1085 // over whatever underlying networks the VPN specifies, while other app
1086 // traffic may go over the system default network (e.g.: a split-tunnel
1087 // VPN, or an app disallowed by the VPN), so the set of networks
1088 // returned includes the VPN's underlying networks and the system
1089 // default.
1090 enforceAccessPermission();
1091
1092 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1093
1094 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001095 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001096 if (nc != null) {
1097 result.put(nai.network, nc);
1098 }
1099
1100 if (!mLockdownEnabled) {
1101 synchronized (mVpns) {
1102 Vpn vpn = mVpns.get(userId);
1103 if (vpn != null) {
1104 Network[] networks = vpn.getUnderlyingNetworks();
1105 if (networks != null) {
1106 for (Network network : networks) {
1107 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001108 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001109 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001110 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001111 }
1112 }
1113 }
1114 }
1115 }
1116 }
1117
1118 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1119 out = result.values().toArray(out);
1120 return out;
1121 }
1122
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001123 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001124 public boolean isNetworkSupported(int networkType) {
1125 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001126 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001127 }
1128
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001129 /**
1130 * Return LinkProperties for the active (i.e., connected) default
1131 * network interface. It is assumed that at most one default network
1132 * is active at a time. If more than one is active, it is indeterminate
1133 * which will be returned.
1134 * @return the ip properties for the active network, or {@code null} if
1135 * none is active
1136 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001137 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001138 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001139 enforceAccessPermission();
1140 final int uid = Binder.getCallingUid();
1141 NetworkState state = getUnfilteredActiveNetworkState(uid);
1142 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001143 }
1144
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001145 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001146 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001147 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001148 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1149 if (nai != null) {
1150 synchronized (nai) {
1151 return new LinkProperties(nai.linkProperties);
1152 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001153 }
1154 return null;
1155 }
1156
Robert Greenwalt12e67352014-05-13 21:41:06 -07001157 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001158 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001159 public LinkProperties getLinkProperties(Network network) {
1160 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001161 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001162 if (nai != null) {
1163 synchronized (nai) {
1164 return new LinkProperties(nai.linkProperties);
1165 }
1166 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001167 return null;
1168 }
1169
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001170 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001171 if (nai != null) {
1172 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001173 if (nai.networkCapabilities != null) {
1174 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001175 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001176 }
1177 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001178 return null;
1179 }
1180
1181 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001182 public NetworkCapabilities getNetworkCapabilities(Network network) {
1183 enforceAccessPermission();
1184 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1185 }
1186
1187 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001188 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001189 // Require internal since we're handing out IMSI details
1190 enforceConnectivityInternalPermission();
1191
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001192 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001193 for (Network network : getAllNetworks()) {
1194 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1195 if (nai != null) {
1196 synchronized (nai) {
1197 final String subscriberId = (nai.networkMisc != null)
1198 ? nai.networkMisc.subscriberId : null;
1199 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1200 nai.networkCapabilities, network, subscriberId, null));
1201 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001202 }
1203 }
1204 return result.toArray(new NetworkState[result.size()]);
1205 }
1206
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001207 @Override
1208 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1209 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001210 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001211 final long token = Binder.clearCallingIdentity();
1212 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001213 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1214 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001215 try {
1216 return mPolicyManager.getNetworkQuotaInfo(state);
1217 } catch (RemoteException e) {
1218 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001219 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001220 return null;
1221 } finally {
1222 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001223 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001224 }
1225
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001226 @Override
1227 public boolean isActiveNetworkMetered() {
1228 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001229 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001230 final long token = Binder.clearCallingIdentity();
1231 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001232 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001233 } finally {
1234 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001235 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001236 }
1237
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001238 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1239 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1240 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001241 try {
1242 return mPolicyManager.isNetworkMetered(state);
1243 } catch (RemoteException e) {
1244 }
1245 }
1246 return false;
1247 }
1248
Jeff Sharkey216c1812012-08-05 14:29:23 -07001249 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1250 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001251 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001252 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001253 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001254 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001255 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001256
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001257 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001258 * Ensure that a network route exists to deliver traffic to the specified
1259 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001260 * @param networkType the type of the network over which traffic to the
1261 * specified host is to be routed
1262 * @param hostAddress the IP address of the host to which the route is
1263 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001264 * @return {@code true} on success, {@code false} on failure
1265 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001266 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001268 if (mProtectedNetworks.contains(networkType)) {
1269 enforceConnectivityInternalPermission();
1270 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001271
Chad Brubakerc0234532014-02-14 13:24:29 -08001272 InetAddress addr;
1273 try {
1274 addr = InetAddress.getByAddress(hostAddress);
1275 } catch (UnknownHostException e) {
1276 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1277 return false;
1278 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001279
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001281 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001282 return false;
1283 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001284
1285 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1286 if (nai == null) {
1287 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1288 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1289 } else {
1290 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1291 }
1292 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001293 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001294
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001295 DetailedState netState;
1296 synchronized (nai) {
1297 netState = nai.networkInfo.getDetailedState();
1298 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001299
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001300 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001301 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001302 log("requestRouteToHostAddress on down network "
1303 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001304 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001305 }
1306 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001307 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001308
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001309 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001310 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001311 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001312 LinkProperties lp;
1313 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001314 synchronized (nai) {
1315 lp = nai.linkProperties;
1316 netId = nai.network.netId;
1317 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001318 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001319 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1320 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001321 } finally {
1322 Binder.restoreCallingIdentity(token);
1323 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001324 }
1325
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001326 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001327 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001328 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001329 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001330 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001331 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001332 if (bestRoute.getGateway().equals(addr)) {
1333 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001334 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001335 } else {
1336 // if we will connect to this through another route, add a direct route
1337 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001338 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001339 }
1340 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001341 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001342 try {
1343 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1344 } catch (Exception e) {
1345 // never crash - catch them all
1346 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001347 return false;
1348 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001349 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001350 }
1351
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001352 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1353 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001354 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001355 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001356 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001357 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001358 }
1359
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001360 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001361 // skip update when we've already applied rules
1362 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1363 if (oldRules == uidRules) return;
1364
1365 mUidRules.put(uid, uidRules);
1366 }
1367
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001368 // TODO: notify UID when it has requested targeted updates
1369 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001370
1371 @Override
1372 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001373 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001374 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001375 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001376 }
1377
1378 synchronized (mRulesLock) {
1379 mMeteredIfaces.clear();
1380 for (String iface : meteredIfaces) {
1381 mMeteredIfaces.add(iface);
1382 }
1383 }
1384 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001385
1386 @Override
1387 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1388 // caller is NPMS, since we only register with them
1389 if (LOGD_RULES) {
1390 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1391 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001392 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001393 };
1394
Robin Lee3b3dd942015-05-12 18:14:58 +01001395 /**
1396 * Require that the caller is either in the same user or has appropriate permission to interact
1397 * across users.
1398 *
1399 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1400 */
1401 private void enforceCrossUserPermission(int userId) {
1402 if (userId == UserHandle.getCallingUserId()) {
1403 // Not a cross-user call.
1404 return;
1405 }
1406 mContext.enforceCallingOrSelfPermission(
1407 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1408 "ConnectivityService");
1409 }
1410
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001411 private void enforceInternetPermission() {
1412 mContext.enforceCallingOrSelfPermission(
1413 android.Manifest.permission.INTERNET,
1414 "ConnectivityService");
1415 }
1416
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001417 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001418 mContext.enforceCallingOrSelfPermission(
1419 android.Manifest.permission.ACCESS_NETWORK_STATE,
1420 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
1422
1423 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001424 mContext.enforceCallingOrSelfPermission(
1425 android.Manifest.permission.CHANGE_NETWORK_STATE,
1426 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001427 }
1428
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001429 private void enforceTetherAccessPermission() {
1430 mContext.enforceCallingOrSelfPermission(
1431 android.Manifest.permission.ACCESS_NETWORK_STATE,
1432 "ConnectivityService");
1433 }
1434
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001435 private void enforceConnectivityInternalPermission() {
1436 mContext.enforceCallingOrSelfPermission(
1437 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1438 "ConnectivityService");
1439 }
1440
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001441 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001442 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001443 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001444 }
1445
1446 private void sendInetConditionBroadcast(NetworkInfo info) {
1447 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1448 }
1449
Wink Saville628b0852011-08-04 15:01:58 -07001450 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001451 if (mLockdownTracker != null) {
1452 info = mLockdownTracker.augmentNetworkInfo(info);
1453 }
1454
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001455 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001456 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001457 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001458 if (info.isFailover()) {
1459 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1460 info.setFailover(false);
1461 }
1462 if (info.getReason() != null) {
1463 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1464 }
1465 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001466 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1467 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001468 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001469 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001470 return intent;
1471 }
1472
1473 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1474 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1475 }
1476
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001477 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001478 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1479 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1480 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001481 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001482 final long ident = Binder.clearCallingIdentity();
1483 try {
1484 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1485 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1486 } finally {
1487 Binder.restoreCallingIdentity(ident);
1488 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001489 }
1490
Mike Lockwood0f79b542009-08-14 14:18:49 -04001491 private void sendStickyBroadcast(Intent intent) {
1492 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001493 if (!mSystemReady) {
1494 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001495 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001496 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001497 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001498 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001499 }
1500
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001501 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001502 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1503 final IBatteryStats bs = BatteryStatsService.getService();
1504 try {
1505 NetworkInfo ni = intent.getParcelableExtra(
1506 ConnectivityManager.EXTRA_NETWORK_INFO);
1507 bs.noteConnectivityChanged(intent.getIntExtra(
1508 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1509 ni != null ? ni.getState().toString() : "?");
1510 } catch (RemoteException e) {
1511 }
1512 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001513 try {
1514 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1515 } finally {
1516 Binder.restoreCallingIdentity(ident);
1517 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001518 }
1519 }
1520
1521 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001522 loadGlobalProxy();
1523
Mike Lockwood0f79b542009-08-14 14:18:49 -04001524 synchronized(this) {
1525 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001526 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001527 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001528 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001529 }
1530 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001531 // load the global proxy at startup
1532 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001533
1534 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1535 // for user to unlock device.
1536 if (!updateLockdownVpn()) {
1537 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1538 mContext.registerReceiver(mUserPresentReceiver, filter);
1539 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001540
Erik Klineda4bfa82015-04-30 12:58:40 +09001541 // Configure whether mobile data is always on.
1542 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1543
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001544 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001545
1546 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001547 }
1548
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001549 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1550 @Override
1551 public void onReceive(Context context, Intent intent) {
1552 // Try creating lockdown tracker, since user present usually means
1553 // unlocked keystore.
1554 if (updateLockdownVpn()) {
1555 mContext.unregisterReceiver(this);
1556 }
1557 }
1558 };
1559
Wink Savilled747cbc2013-08-07 16:22:47 -07001560 /** @hide */
1561 @Override
1562 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1563 enforceConnectivityInternalPermission();
1564 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001565// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001566 }
1567
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001568 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001569 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001570 *
1571 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001572 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001573 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001574 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1575 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001576
1577 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001578 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001579
Robert Greenwalt7b816022014-04-18 15:25:25 -07001580 if (networkAgent.networkCapabilities.hasTransport(
1581 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001582 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1583 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001584 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001585 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001586 } else if (networkAgent.networkCapabilities.hasTransport(
1587 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001588 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1589 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001590 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001591 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001592 } else {
1593 // do not track any other networks
1594 timeout = 0;
1595 }
1596
Robert Greenwalt7b816022014-04-18 15:25:25 -07001597 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001598 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001599 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001600 } catch (Exception e) {
1601 // You shall not crash!
1602 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001603 }
1604 }
1605 }
1606
1607 /**
1608 * Remove data activity tracking when network disconnects.
1609 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001610 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1611 final String iface = networkAgent.linkProperties.getInterfaceName();
1612 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001613
Robert Greenwalt7b816022014-04-18 15:25:25 -07001614 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1615 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001616 try {
1617 // the call fails silently if no idletimer setup for this interface
1618 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001619 } catch (Exception e) {
1620 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001621 }
1622 }
1623 }
1624
1625 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001626 * Reads the network specific MTU size from reources.
1627 * and set it on it's iface.
1628 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001629 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1630 final String iface = newLp.getInterfaceName();
1631 final int mtu = newLp.getMtu();
1632 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1633 if (VDBG) log("identical MTU - not setting");
1634 return;
1635 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001636
Robert Greenwalt43074032014-08-15 17:53:05 -07001637 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001638 loge("Unexpected mtu value: " + mtu + ", " + iface);
1639 return;
1640 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001641
w1997615afd812014-08-05 15:18:11 -07001642 // Cannot set MTU without interface name
1643 if (TextUtils.isEmpty(iface)) {
1644 loge("Setting MTU size with null iface.");
1645 return;
1646 }
1647
Robert Greenwalt7b816022014-04-18 15:25:25 -07001648 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001649 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001650 mNetd.setMtu(iface, mtu);
1651 } catch (Exception e) {
1652 Slog.e(TAG, "exception in setMtu()" + e);
1653 }
1654 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001655
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001656 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001657
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001658 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1659 if (isDefaultNetwork(nai) == false) {
1660 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001661 }
1662
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001663 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1664 String[] values = null;
1665 if (tcpBufferSizes != null) {
1666 values = tcpBufferSizes.split(",");
1667 }
1668
1669 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001670 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001671 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1672 values = tcpBufferSizes.split(",");
1673 }
1674
1675 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1676
1677 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001678 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001679
1680 final String prefix = "/sys/kernel/ipv4/tcp_";
1681 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1682 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1683 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1684 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1685 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1686 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1687 mCurrentTcpBufferSizes = tcpBufferSizes;
1688 } catch (IOException e) {
1689 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001690 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001691
1692 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1693 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1694 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1695 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1696 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1697 if (rwndValue != 0) {
1698 SystemProperties.set(sysctlKey, rwndValue.toString());
1699 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001700 }
1701
Mattias Falk8b47b362011-08-23 14:15:13 +02001702 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001703 /*
1704 * Tell the VMs to toss their DNS caches
1705 */
1706 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1707 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001708 /*
1709 * Connectivity events can happen before boot has completed ...
1710 */
1711 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001712 final long ident = Binder.clearCallingIdentity();
1713 try {
1714 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1715 } finally {
1716 Binder.restoreCallingIdentity(ident);
1717 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001718 }
1719
Robert Greenwalt562cc542014-05-15 18:07:26 -07001720 @Override
1721 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001722 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1723 NETWORK_RESTORE_DELAY_PROP_NAME);
1724 if(restoreDefaultNetworkDelayStr != null &&
1725 restoreDefaultNetworkDelayStr.length() != 0) {
1726 try {
1727 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1728 } catch (NumberFormatException e) {
1729 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001730 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001731 // if the system property isn't set, use the value for the apn type
1732 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1733
1734 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1735 (mNetConfigs[networkType] != null)) {
1736 ret = mNetConfigs[networkType].restoreTime;
1737 }
1738 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001739 }
1740
1741 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001742 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1743 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001744 if (mContext.checkCallingOrSelfPermission(
1745 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001746 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001747 pw.println("Permission Denial: can't dump ConnectivityService " +
1748 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1749 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001750 return;
1751 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001752
Robert Greenwalta67be032014-05-16 15:49:14 -07001753 pw.println("NetworkFactories for:");
1754 pw.increaseIndent();
1755 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1756 pw.println(nfi.name);
1757 }
1758 pw.decreaseIndent();
1759 pw.println();
1760
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001761 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1762 pw.print("Active default network: ");
1763 if (defaultNai == null) {
1764 pw.println("none");
1765 } else {
1766 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001767 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001768 pw.println();
1769
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001770 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001771 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001772 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1773 pw.println(nai.toString());
1774 pw.increaseIndent();
1775 pw.println("Requests:");
1776 pw.increaseIndent();
1777 for (int i = 0; i < nai.networkRequests.size(); i++) {
1778 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001779 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001780 pw.decreaseIndent();
1781 pw.println("Lingered:");
1782 pw.increaseIndent();
1783 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1784 pw.decreaseIndent();
1785 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001786 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001787 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001788 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001789
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001790 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001791 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001792 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1793 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001794 }
1795 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001796 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001797
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001798 pw.println("mLegacyTypeTracker:");
1799 pw.increaseIndent();
1800 mLegacyTypeTracker.dump(pw);
1801 pw.decreaseIndent();
1802 pw.println();
1803
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001804 synchronized (this) {
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001805 pw.println("NetworkTransitionWakeLock is currently " +
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001806 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1807 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1808 }
1809 pw.println();
1810
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001811 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001812
1813 if (mInetLog != null) {
1814 pw.println();
1815 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001816 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001817 for(int i = 0; i < mInetLog.size(); i++) {
1818 pw.println(mInetLog.get(i));
1819 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001820 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001821 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001822 }
1823
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001824 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001825 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001826 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001827 if (officialNai != null && officialNai.equals(nai)) return true;
1828 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001829 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001830 " - " + nai);
1831 }
1832 return false;
1833 }
1834
Paul Jensenc8b9a742014-09-30 15:37:41 -04001835 private boolean isRequest(NetworkRequest request) {
1836 return mNetworkRequests.get(request).isRequest;
1837 }
1838
Robert Greenwalt42acef32009-08-12 16:08:25 -07001839 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001840 private class NetworkStateTrackerHandler extends Handler {
1841 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001842 super(looper);
1843 }
1844
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001845 @Override
1846 public void handleMessage(Message msg) {
1847 NetworkInfo info;
1848 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001849 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001850 handleAsyncChannelHalfConnect(msg);
1851 break;
1852 }
1853 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1854 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1855 if (nai != null) nai.asyncChannel.disconnect();
1856 break;
1857 }
1858 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1859 handleAsyncChannelDisconnected(msg);
1860 break;
1861 }
1862 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1863 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1864 if (nai == null) {
1865 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1866 } else {
1867 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001868 }
1869 break;
1870 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001871 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1872 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1873 if (nai == null) {
1874 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1875 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001876 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001877 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001878 "; created=" + nai.created);
1879 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001880 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001881 synchronized (nai) {
1882 nai.linkProperties = (LinkProperties)msg.obj;
1883 }
Paul Jenseneec75412014-08-04 12:21:19 -04001884 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001885 }
1886 break;
1887 }
1888 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1889 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1890 if (nai == null) {
1891 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1892 break;
1893 }
1894 info = (NetworkInfo) msg.obj;
1895 updateNetworkInfo(nai, info);
1896 break;
1897 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001898 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1899 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1900 if (nai == null) {
1901 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1902 break;
1903 }
1904 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001905 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001906 break;
1907 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001908 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1909 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1910 if (nai == null) {
1911 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1912 break;
1913 }
1914 try {
1915 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001916 } catch (Exception e) {
1917 // Never crash!
1918 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001919 }
1920 break;
1921 }
1922 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1923 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1924 if (nai == null) {
1925 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1926 break;
1927 }
1928 try {
1929 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001930 } catch (Exception e) {
1931 // Never crash!
1932 loge("Exception in removeVpnUidRanges: " + e);
1933 }
1934 break;
1935 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001936 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1937 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1938 if (nai == null) {
1939 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1940 break;
1941 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001942 if (nai.created && !nai.networkMisc.explicitlySelected) {
1943 loge("ERROR: created network explicitly selected.");
1944 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001945 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001946 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001947 break;
1948 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001949 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001950 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001951 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1952 final boolean valid =
1953 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
1954 final boolean validationChanged = (valid != nai.lastValidated);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001955 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001956 if (valid) {
1957 if (DBG) log("Validated " + nai.name());
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001958 nai.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001959 if (!nai.everValidated) {
1960 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001961 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1962 ReapUnvalidatedNetworks.REAP);
1963 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001964 sendUpdatedScoreToFactories(nai);
1965 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001966 } else {
1967 nai.networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -04001968 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001969 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001970 // Let the NetworkAgent know the state of its network
1971 nai.asyncChannel.sendMessage(
1972 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1973 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1974 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001975
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001976 if (validationChanged) {
1977 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
1978 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001979 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001980 break;
1981 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001982 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001983 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001984 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1985 handleLingerComplete(nai);
1986 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001987 break;
1988 }
Paul Jensen869868be2014-05-15 10:33:05 -04001989 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001990 if (msg.arg1 == 0) {
1991 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1992 } else {
Lorenzo Colittid49159f2015-05-14 23:15:10 +09001993 final NetworkAgentInfo nai;
Paul Jensen5df4bec2014-08-25 22:45:39 -04001994 synchronized (mNetworkForNetId) {
1995 nai = mNetworkForNetId.get(msg.arg2);
1996 }
1997 if (nai == null) {
1998 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1999 break;
2000 }
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002001 nai.captivePortalDetected = true;
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002002 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
2003 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04002004 }
Paul Jensen869868be2014-05-15 10:33:05 -04002005 break;
2006 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002007 }
2008 }
2009 }
2010
Paul Jensen0cc17322014-11-25 15:26:53 -05002011 // Cancel any lingering so the linger timeout doesn't teardown a network.
2012 // This should be called when a network begins satisfying a NetworkRequest.
2013 // Note: depending on what state the NetworkMonitor is in (e.g.,
2014 // if it's awaiting captive portal login, or if validation failed), this
2015 // may trigger a re-evaluation of the network.
2016 private void unlinger(NetworkAgentInfo nai) {
2017 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002018 // If network has never been validated, it cannot have been lingered, so don't bother
2019 // needlessly triggering a re-evaluation.
2020 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002021 nai.networkLingered.clear();
2022 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2023 }
2024
Robert Greenwalt7b816022014-04-18 15:25:25 -07002025 private void handleAsyncChannelHalfConnect(Message msg) {
2026 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002027 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002028 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2029 if (VDBG) log("NetworkFactory connected");
2030 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002031 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002032 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002033 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002034 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002035 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002036 }
2037 } else {
2038 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002039 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002040 }
2041 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2042 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2043 if (VDBG) log("NetworkAgent connected");
2044 // A network agent has requested a connection. Establish the connection.
2045 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2046 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2047 } else {
2048 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002049 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002050 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002051 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002052 synchronized (mNetworkForNetId) {
2053 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002054 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002055 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002056 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002057 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002058 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002059 }
2060 }
2061 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002062
Robert Greenwalt7b816022014-04-18 15:25:25 -07002063 private void handleAsyncChannelDisconnected(Message msg) {
2064 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2065 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002066 if (DBG) {
2067 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2068 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002069 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002070 if (nai.created) {
2071 // Tell netd to clean up the configuration for this network
2072 // (routing rules, DNS, etc).
2073 try {
2074 mNetd.removeNetwork(nai.network.netId);
2075 } catch (Exception e) {
2076 loge("Exception removing network: " + e);
2077 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002078 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002079 // TODO - if we move the logic to the network agent (have them disconnect
2080 // because they lost all their requests or because their score isn't good)
2081 // then they would disconnect organically, report their new state and then
2082 // disconnect the channel.
2083 if (nai.networkInfo.isConnected()) {
2084 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2085 null, null);
2086 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002087 final boolean wasDefault = isDefaultNetwork(nai);
2088 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002089 mDefaultInetConditionPublished = 0;
2090 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002091 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002092 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002093 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002094 mNetworkAgentInfos.remove(msg.replyTo);
2095 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002096 synchronized (mNetworkForNetId) {
2097 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002098 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002099 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002100 // Since we've lost the network, go through all the requests that
2101 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002102 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002103 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002104 for (int i = 0; i < nai.networkRequests.size(); i++) {
2105 NetworkRequest request = nai.networkRequests.valueAt(i);
2106 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2107 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002108 if (DBG) {
2109 log("Checking for replacement network to handle request " + request );
2110 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002111 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002112 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002113 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002114 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2115 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002116 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002117 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002118 alternative = existing;
2119 }
2120 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002121 if (alternative != null) {
2122 if (DBG) log(" found replacement in " + alternative.name());
2123 if (!toActivate.contains(alternative)) {
2124 toActivate.add(alternative);
2125 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002126 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002127 }
2128 }
2129 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2130 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002131 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002132 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002133 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002134 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002135 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002136 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002137 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2138 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002139 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302141 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2142 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002143 }
2144
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002145 // If this method proves to be too slow then we can maintain a separate
2146 // pendingIntent => NetworkRequestInfo map.
2147 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2148 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2149 Intent intent = pendingIntent.getIntent();
2150 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2151 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2152 if (existingPendingIntent != null &&
2153 existingPendingIntent.getIntent().filterEquals(intent)) {
2154 return entry.getValue();
2155 }
2156 }
2157 return null;
2158 }
2159
2160 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2161 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2162
2163 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2164 if (existingRequest != null) { // remove the existing request.
2165 if (DBG) log("Replacing " + existingRequest.request + " with "
2166 + nri.request + " because their intents matched.");
2167 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2168 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002169 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002170 }
2171
Erik Klineda4bfa82015-04-30 12:58:40 +09002172 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002173 mNetworkRequests.put(nri.request, nri);
2174
Paul Jensen0cc17322014-11-25 15:26:53 -05002175 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2176
Robert Greenwalt9258c642014-03-26 16:47:06 -07002177 // Check for the best currently alive network that satisfies this request
2178 NetworkAgentInfo bestNetwork = null;
2179 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002180 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002181 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002182 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002183 if (!nri.isRequest) {
2184 // Not setting bestNetwork here as a listening NetworkRequest may be
2185 // satisfied by multiple Networks. Instead the request is added to
2186 // each satisfying Network and notified about each.
2187 network.addRequest(nri.request);
2188 notifyNetworkCallback(network, nri);
2189 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002190 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002191 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002192 }
2193 }
2194 }
2195 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002196 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002197 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002198 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002199 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002200 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002201 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002202 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2203 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002204 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002205
Lorenzo Colittia793a672014-07-31 23:20:17 +09002206 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002207 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002208 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002209 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002210 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002211 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002212 }
2213 }
2214 }
2215
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002216 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2217 int callingUid) {
2218 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2219 if (nri != null) {
2220 handleReleaseNetworkRequest(nri.request, callingUid);
2221 }
2222 }
2223
Paul Jensen99364842014-12-09 11:43:45 -05002224 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2225 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2226 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2227 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2228 private boolean unneeded(NetworkAgentInfo nai) {
2229 if (!nai.created || nai.isVPN()) return false;
2230 boolean unneeded = true;
2231 if (nai.everValidated) {
2232 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2233 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2234 try {
2235 if (isRequest(nr)) unneeded = false;
2236 } catch (Exception e) {
2237 loge("Request " + nr + " not found in mNetworkRequests.");
2238 loge(" it came from request list of " + nai.name());
2239 }
2240 }
2241 } else {
2242 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2243 // If this Network is already the highest scoring Network for a request, or if
2244 // there is hope for it to become one if it validated, then it is needed.
2245 if (nri.isRequest && nai.satisfies(nri.request) &&
2246 (nai.networkRequests.get(nri.request.requestId) != null ||
2247 // Note that this catches two important cases:
2248 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2249 // is currently satisfying the request. This is desirable when
2250 // cellular ends up validating but WiFi does not.
2251 // 2. Unvalidated WiFi will not be reaped when validated cellular
2252 // is currently satsifying the request. This is desirable when
2253 // WiFi ends up validating and out scoring cellular.
2254 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2255 nai.getCurrentScoreAsValidated())) {
2256 unneeded = false;
2257 break;
2258 }
2259 }
2260 }
2261 return unneeded;
2262 }
2263
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002264 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2265 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002266 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002267 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002268 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2269 return;
2270 }
2271 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002272 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002273 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002274 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002275 // Find all networks that are satisfying this request and remove the request
2276 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002277 // TODO - it's my understanding that for a request there is only a single
2278 // network satisfying it, so this loop is wasteful
2279 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002280 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2281 if (nai.networkRequests.get(nri.request.requestId) != null) {
2282 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002283 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002284 log(" Removing from current network " + nai.name() +
2285 ", leaving " + nai.networkRequests.size() +
2286 " requests.");
2287 }
Paul Jensen99364842014-12-09 11:43:45 -05002288 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002289 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002290 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002291 } else {
2292 // suspect there should only be one pass through here
2293 // but if any were kept do the check below
2294 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002295 }
2296 }
2297 }
2298
Robert Greenwalt51481852015-01-08 14:43:31 -08002299 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2300 if (nai != null) {
2301 mNetworkForRequestId.remove(nri.request.requestId);
2302 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002303 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002304 // that a network connected to serve it, even though the network was already
2305 // connected. Now that this request has gone away, we might have to pretend
2306 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002307 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002308 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2309 boolean doRemove = true;
2310 if (wasKept) {
2311 // check if any of the remaining requests for this network are for the
2312 // same legacy type - if so, don't remove the nai
2313 for (int i = 0; i < nai.networkRequests.size(); i++) {
2314 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2315 if (otherRequest.legacyType == nri.request.legacyType &&
2316 isRequest(otherRequest)) {
2317 if (DBG) log(" still have other legacy request - leaving");
2318 doRemove = false;
2319 }
2320 }
2321 }
2322
2323 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002324 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002325 }
2326 }
2327
Robert Greenwalta67be032014-05-16 15:49:14 -07002328 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002329 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2330 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002331 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002332 } else {
2333 // listens don't have a singular affectedNetwork. Check all networks to see
2334 // if this listen request applies and remove it.
2335 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2336 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002337 }
2338 }
2339 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2340 }
2341 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002342
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002343 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2344 enforceConnectivityInternalPermission();
2345 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2346 accept ? 1 : 0, always ? 1: 0, network));
2347 }
2348
2349 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2350 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2351 " accept=" + accept + " always=" + always);
2352
2353 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2354 if (nai == null) {
2355 // Nothing to do.
2356 return;
2357 }
2358
2359 if (nai.everValidated) {
2360 // The network validated while the dialog box was up. Don't make any changes. There's a
2361 // TODO in the dialog code to make it go away if the network validates; once that's
2362 // implemented, taking action here will be confusing.
2363 return;
2364 }
2365
2366 if (!nai.networkMisc.explicitlySelected) {
2367 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2368 }
2369
2370 if (accept != nai.networkMisc.acceptUnvalidated) {
2371 int oldScore = nai.getCurrentScore();
2372 nai.networkMisc.acceptUnvalidated = accept;
2373 rematchAllNetworksAndRequests(nai, oldScore);
2374 sendUpdatedScoreToFactories(nai);
2375 }
2376
2377 if (always) {
2378 nai.asyncChannel.sendMessage(
2379 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2380 }
2381
2382 // TODO: should we also disconnect from the network if accept is false?
2383 }
2384
2385 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2386 mHandler.sendMessageDelayed(
2387 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2388 PROMPT_UNVALIDATED_DELAY_MS);
2389 }
2390
2391 private void handlePromptUnvalidated(Network network) {
2392 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2393
2394 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2395 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002396 // Also don't prompt on captive portals because we're already prompting the user to sign in.
2397 if (nai == null || nai.everValidated || nai.captivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002398 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2399 return;
2400 }
2401
2402 // TODO: What should we do if we've already switched to this network because we had no
2403 // better option? There are two obvious alternatives.
2404 //
2405 // 1. Decide that there's no point prompting because this is our only usable network.
2406 // However, because we didn't prompt, if later on a validated network comes along, we'll
2407 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2408 // unvalidated network - or b) prompt the user at that later time - bad because the user
2409 // might not understand why they are now being prompted.
2410 //
2411 // 2. Always prompt the user, even if we have no other network to use. The user could then
2412 // try to find an alternative network to join (remember, if we got here, then the user
2413 // selected this network manually). This is bad because the prompt isn't really very
2414 // useful.
2415 //
2416 // For now we do #1, but we can revisit that later.
2417 if (isDefaultNetwork(nai)) {
2418 return;
2419 }
2420
2421 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2422 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2423 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2424 intent.setClassName("com.android.settings",
2425 "com.android.settings.wifi.WifiNoInternetDialog");
2426 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2427 }
2428
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002429 private class InternalHandler extends Handler {
2430 public InternalHandler(Looper looper) {
2431 super(looper);
2432 }
2433
2434 @Override
2435 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002436 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002437 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002438 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002439 String causedBy = null;
2440 synchronized (ConnectivityService.this) {
2441 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2442 mNetTransitionWakeLock.isHeld()) {
2443 mNetTransitionWakeLock.release();
2444 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002445 } else {
2446 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002447 }
2448 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002449 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2450 log("Failed to find a new network - expiring NetTransition Wakelock");
2451 } else {
2452 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2453 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002454 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002455 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002456 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002457 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002458 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002459 break;
2460 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002461 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002462 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002463 sendStickyBroadcast(intent);
2464 break;
2465 }
Jason Monkdecd2952013-10-10 14:02:51 -04002466 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002467 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002468 break;
2469 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002470 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002471 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2472 break;
2473 }
2474 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2475 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002476 break;
2477 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002478 case EVENT_REGISTER_NETWORK_AGENT: {
2479 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2480 break;
2481 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002482 case EVENT_REGISTER_NETWORK_REQUEST:
2483 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002484 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002485 break;
2486 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002487 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2488 handleRegisterNetworkRequestWithIntent(msg);
2489 break;
2490 }
2491 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2492 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2493 break;
2494 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002495 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002496 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002497 break;
2498 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002499 case EVENT_SET_ACCEPT_UNVALIDATED: {
2500 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2501 break;
2502 }
2503 case EVENT_PROMPT_UNVALIDATED: {
2504 handlePromptUnvalidated((Network) msg.obj);
2505 break;
2506 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002507 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2508 handleMobileDataAlwaysOn();
2509 break;
2510 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002511 case EVENT_SYSTEM_READY: {
2512 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2513 nai.networkMonitor.systemReady = true;
2514 }
2515 break;
2516 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002517 }
2518 }
2519 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002520
2521 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002522 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002523 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002524 if (isTetheringSupported()) {
2525 return mTethering.tether(iface);
2526 } else {
2527 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2528 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002529 }
2530
2531 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002532 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002533 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002534
2535 if (isTetheringSupported()) {
2536 return mTethering.untether(iface);
2537 } else {
2538 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2539 }
2540 }
2541
2542 // javadoc from interface
2543 public int getLastTetherError(String iface) {
2544 enforceTetherAccessPermission();
2545
2546 if (isTetheringSupported()) {
2547 return mTethering.getLastTetherError(iface);
2548 } else {
2549 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2550 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002551 }
2552
2553 // TODO - proper iface API for selection by property, inspection, etc
2554 public String[] getTetherableUsbRegexs() {
2555 enforceTetherAccessPermission();
2556 if (isTetheringSupported()) {
2557 return mTethering.getTetherableUsbRegexs();
2558 } else {
2559 return new String[0];
2560 }
2561 }
2562
2563 public String[] getTetherableWifiRegexs() {
2564 enforceTetherAccessPermission();
2565 if (isTetheringSupported()) {
2566 return mTethering.getTetherableWifiRegexs();
2567 } else {
2568 return new String[0];
2569 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002570 }
2571
Danica Chang6fdd0c62010-08-11 14:54:43 -07002572 public String[] getTetherableBluetoothRegexs() {
2573 enforceTetherAccessPermission();
2574 if (isTetheringSupported()) {
2575 return mTethering.getTetherableBluetoothRegexs();
2576 } else {
2577 return new String[0];
2578 }
2579 }
2580
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002581 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002582 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002583 if (isTetheringSupported()) {
2584 return mTethering.setUsbTethering(enable);
2585 } else {
2586 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2587 }
2588 }
2589
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002590 // TODO - move iface listing, queries, etc to new module
2591 // javadoc from interface
2592 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002593 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002594 return mTethering.getTetherableIfaces();
2595 }
2596
2597 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002598 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002599 return mTethering.getTetheredIfaces();
2600 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002601
Robert Greenwalt5a735062010-03-02 17:25:02 -08002602 public String[] getTetheringErroredIfaces() {
2603 enforceTetherAccessPermission();
2604 return mTethering.getErroredIfaces();
2605 }
2606
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002607 public String[] getTetheredDhcpRanges() {
2608 enforceConnectivityInternalPermission();
2609 return mTethering.getTetheredDhcpRanges();
2610 }
2611
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002612 // if ro.tether.denied = true we default to no tethering
2613 // gservices could set the secure setting to 1 though to enable it on a build where it
2614 // had previously been turned off.
2615 public boolean isTetheringSupported() {
2616 enforceTetherAccessPermission();
2617 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002618 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002619 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2620 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002621 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2622 mTethering.getTetherableWifiRegexs().length != 0 ||
2623 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2624 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002625 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002626
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002627 // Called when we lose the default network and have no replacement yet.
2628 // This will automatically be cleared after X seconds or a new default network
2629 // becomes CONNECTED, whichever happens first. The timer is started by the
2630 // first caller and not restarted by subsequent callers.
2631 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002632 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002633 synchronized (this) {
2634 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002635 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002636 mNetTransitionWakeLock.acquire();
2637 mNetTransitionWakeLockCausedBy = forWhom;
2638 }
2639 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002640 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002641 mNetTransitionWakeLockTimeout);
2642 return;
2643 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002644
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002645 // 100 percent is full good, 0 is full bad.
2646 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002647 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002648 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002649 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002650 }
2651
Paul Jensenbfd17b72015-04-07 12:43:13 -04002652 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002653 enforceAccessPermission();
2654 enforceInternetPermission();
2655
Paul Jensenbfd17b72015-04-07 12:43:13 -04002656 NetworkAgentInfo nai;
2657 if (network == null) {
2658 nai = getDefaultNetwork();
2659 } else {
2660 nai = getNetworkAgentInfoForNetwork(network);
2661 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002662 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002663 // Revalidate if the app report does not match our current validated state.
2664 if (hasConnectivity == nai.lastValidated) return;
2665 final int uid = Binder.getCallingUid();
2666 if (DBG) {
2667 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2668 ") by " + uid);
2669 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002670 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002671 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2672 // which isn't meant to work on uncreated networks.
2673 if (!nai.created) return;
2674
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002675 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002676
2677 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2678 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002679 }
2680
Paul Jensen25a217c2015-02-27 22:55:47 -05002681 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2682 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2683 enforceConnectivityInternalPermission();
2684 }
2685 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2686 if (nai == null) return;
2687 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2688 actionToken);
2689 }
2690
Paul Jensencee9b512015-05-06 07:32:40 -04002691 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002692 // this information is already available as a world read/writable jvm property
2693 // so this API change wouldn't have a benifit. It also breaks the passing
2694 // of proxy info to all the JVMs.
2695 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002696 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002697 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002698 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2699 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002700 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002701 }
2702
Paul Jensencee9b512015-05-06 07:32:40 -04002703 public ProxyInfo getProxyForNetwork(Network network) {
2704 if (network == null) return getDefaultProxy();
2705 final ProxyInfo globalProxy = getGlobalProxy();
2706 if (globalProxy != null) return globalProxy;
2707 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2708 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2709 // caller may not have.
2710 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2711 if (nai == null) return null;
2712 synchronized (nai) {
2713 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2714 if (proxyInfo == null) return null;
2715 return new ProxyInfo(proxyInfo);
2716 }
2717 }
2718
Paul Jensene0bef712014-12-10 15:12:18 -05002719 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2720 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2721 // proxy is null then there is no proxy in place).
2722 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2723 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2724 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2725 proxy = null;
2726 }
2727 return proxy;
2728 }
2729
2730 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2731 // better for determining if a new proxy broadcast is necessary:
2732 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2733 // avoid unnecessary broadcasts.
2734 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2735 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2736 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2737 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2738 // all set.
2739 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2740 a = canonicalizeProxyInfo(a);
2741 b = canonicalizeProxyInfo(b);
2742 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2743 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2744 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2745 }
2746
Jason Monk207900c2014-04-25 15:00:09 -04002747 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002748 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002749
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002750 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002751 if (proxyProperties == mGlobalProxy) return;
2752 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2753 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2754
2755 String host = "";
2756 int port = 0;
2757 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002758 String pacFileUrl = "";
2759 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002760 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002761 if (!proxyProperties.isValid()) {
2762 if (DBG)
2763 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2764 return;
2765 }
Jason Monk207900c2014-04-25 15:00:09 -04002766 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002767 host = mGlobalProxy.getHost();
2768 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002769 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002770 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002771 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002772 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002773 } else {
2774 mGlobalProxy = null;
2775 }
2776 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002777 final long token = Binder.clearCallingIdentity();
2778 try {
2779 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2780 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2781 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2782 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002783 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002784 } finally {
2785 Binder.restoreCallingIdentity(token);
2786 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002787
Jason Monkcf0f97a2014-10-02 15:39:38 -04002788 if (mGlobalProxy == null) {
2789 proxyProperties = mDefaultProxy;
2790 }
2791 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002792 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002793 }
2794
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002795 private void loadGlobalProxy() {
2796 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002797 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2798 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2799 String exclList = Settings.Global.getString(res,
2800 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002801 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2802 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002803 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002804 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002805 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002806 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002807 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002808 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002809 if (!proxyProperties.isValid()) {
2810 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2811 return;
2812 }
2813
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002814 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002815 mGlobalProxy = proxyProperties;
2816 }
2817 }
2818 }
2819
Jason Monk207900c2014-04-25 15:00:09 -04002820 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002821 // this information is already available as a world read/writable jvm property
2822 // so this API change wouldn't have a benifit. It also breaks the passing
2823 // of proxy info to all the JVMs.
2824 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002825 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002826 return mGlobalProxy;
2827 }
2828 }
2829
Jason Monk207900c2014-04-25 15:00:09 -04002830 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002831 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002832 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002833 proxy = null;
2834 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002835 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002836 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002837 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002838 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002839 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2840 return;
2841 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002842
2843 // This call could be coming from the PacManager, containing the port of the local
2844 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2845 // global (to get the correct local port), and send a broadcast.
2846 // TODO: Switch PacManager to have its own message to send back rather than
2847 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002848 if ((mGlobalProxy != null) && (proxy != null)
2849 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002850 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2851 mGlobalProxy = proxy;
2852 sendProxyBroadcast(mGlobalProxy);
2853 return;
2854 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002855 mDefaultProxy = proxy;
2856
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002857 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002858 if (!mDefaultProxyDisabled) {
2859 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002860 }
2861 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002862 }
2863
Paul Jensene0bef712014-12-10 15:12:18 -05002864 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2865 // This method gets called when any network changes proxy, but the broadcast only ever contains
2866 // the default proxy (even if it hasn't changed).
2867 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2868 // world where an app might be bound to a non-default network.
2869 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2870 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2871 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2872
2873 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2874 sendProxyBroadcast(getDefaultProxy());
2875 }
2876 }
2877
Robert Greenwalt434203a2010-10-11 16:00:27 -07002878 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002879 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2880 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002881 if (!TextUtils.isEmpty(proxy)) {
2882 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002883 if (data.length == 0) {
2884 return;
2885 }
2886
Robert Greenwalt434203a2010-10-11 16:00:27 -07002887 String proxyHost = data[0];
2888 int proxyPort = 8080;
2889 if (data.length > 1) {
2890 try {
2891 proxyPort = Integer.parseInt(data[1]);
2892 } catch (NumberFormatException e) {
2893 return;
2894 }
2895 }
Jason Monk207900c2014-04-25 15:00:09 -04002896 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002897 setGlobalProxy(p);
2898 }
2899 }
2900
Jason Monk207900c2014-04-25 15:00:09 -04002901 private void sendProxyBroadcast(ProxyInfo proxy) {
2902 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002903 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002904 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002905 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002906 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2907 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002908 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002909 final long ident = Binder.clearCallingIdentity();
2910 try {
2911 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2912 } finally {
2913 Binder.restoreCallingIdentity(ident);
2914 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 }
2916
2917 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002918 final private HashMap<Uri, Integer> mUriEventMap;
2919 final private Context mContext;
2920 final private Handler mHandler;
2921
2922 SettingsObserver(Context context, Handler handler) {
2923 super(null);
2924 mUriEventMap = new HashMap<Uri, Integer>();
2925 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002926 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002927 }
2928
Erik Klineda4bfa82015-04-30 12:58:40 +09002929 void observe(Uri uri, int what) {
2930 mUriEventMap.put(uri, what);
2931 final ContentResolver resolver = mContext.getContentResolver();
2932 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002933 }
2934
2935 @Override
2936 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002937 Slog.wtf(TAG, "Should never be reached.");
2938 }
2939
2940 @Override
2941 public void onChange(boolean selfChange, Uri uri) {
2942 final Integer what = mUriEventMap.get(uri);
2943 if (what != null) {
2944 mHandler.obtainMessage(what.intValue()).sendToTarget();
2945 } else {
2946 loge("No matching event to send for URI=" + uri);
2947 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002948 }
2949 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002950
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002951 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002952 Slog.d(TAG, s);
2953 }
2954
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002955 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002956 Slog.e(TAG, s);
2957 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002958
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002959 private static <T> T checkNotNull(T value, String message) {
2960 if (value == null) {
2961 throw new NullPointerException(message);
2962 }
2963 return value;
2964 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002965
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002966 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002967 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002968 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2969 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2970 *
2971 * @param oldPackage Package name of the application which currently controls VPN, which will
2972 * be replaced. If there is no such application, this should should either be
2973 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2974 * @param newPackage Package name of the application which should gain control of VPN, or
2975 * {@code null} to disable.
2976 * @param userId User for whom to prepare the new VPN.
2977 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002978 * @hide
2979 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002980 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002981 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2982 int userId) {
2983 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002984 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002985
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002986 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01002987 return mVpns.get(userId).prepare(oldPackage, newPackage);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002988 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002989 }
2990
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002991 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002992 * Set whether the VPN package has the ability to launch VPNs without user intervention.
2993 * This method is used by system-privileged apps.
2994 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2995 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2996 *
2997 * @param packageName The package for which authorization state should change.
2998 * @param userId User for whom {@code packageName} is installed.
2999 * @param authorized {@code true} if this app should be able to start a VPN connection without
3000 * explicit user approval, {@code false} if not.
3001 *
Jeff Davidson05542602014-08-11 14:07:27 -07003002 * @hide
3003 */
3004 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003005 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3006 enforceCrossUserPermission(userId);
3007
Jeff Davidson05542602014-08-11 14:07:27 -07003008 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003009 mVpns.get(userId).setPackageAuthorization(packageName, authorized);
Jeff Davidson05542602014-08-11 14:07:27 -07003010 }
3011 }
3012
3013 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003014 * Configure a TUN interface and return its file descriptor. Parameters
3015 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003016 * and not available in ConnectivityManager. Permissions are checked in
3017 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003018 * @hide
3019 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003020 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003021 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003022 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003023 int user = UserHandle.getUserId(Binder.getCallingUid());
3024 synchronized(mVpns) {
3025 return mVpns.get(user).establish(config);
3026 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003027 }
3028
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003029 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003030 * Start legacy VPN, controlling native daemons as needed. Creates a
3031 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003032 */
3033 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003034 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003035 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003036 final LinkProperties egress = getActiveLinkProperties();
3037 if (egress == null) {
3038 throw new IllegalStateException("Missing active network connection");
3039 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003040 int user = UserHandle.getUserId(Binder.getCallingUid());
3041 synchronized(mVpns) {
3042 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3043 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003044 }
3045
3046 /**
3047 * Return the information of the ongoing legacy VPN. This method is used
3048 * by VpnSettings and not available in ConnectivityManager. Permissions
3049 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003050 */
3051 @Override
3052 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003053 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003054 int user = UserHandle.getUserId(Binder.getCallingUid());
3055 synchronized(mVpns) {
3056 return mVpns.get(user).getLegacyVpnInfo();
3057 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003058 }
3059
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003060 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003061 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3062 * and not available in ConnectivityManager.
3063 */
3064 @Override
3065 public VpnInfo[] getAllVpnInfo() {
3066 enforceConnectivityInternalPermission();
3067 if (mLockdownEnabled) {
3068 return new VpnInfo[0];
3069 }
3070
3071 synchronized(mVpns) {
3072 List<VpnInfo> infoList = new ArrayList<>();
3073 for (int i = 0; i < mVpns.size(); i++) {
3074 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3075 if (info != null) {
3076 infoList.add(info);
3077 }
3078 }
3079 return infoList.toArray(new VpnInfo[infoList.size()]);
3080 }
3081 }
3082
3083 /**
3084 * @return VPN information for accounting, or null if we can't retrieve all required
3085 * information, e.g primary underlying iface.
3086 */
3087 @Nullable
3088 private VpnInfo createVpnInfo(Vpn vpn) {
3089 VpnInfo info = vpn.getVpnInfo();
3090 if (info == null) {
3091 return null;
3092 }
3093 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3094 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3095 // the underlyingNetworks list.
3096 if (underlyingNetworks == null) {
3097 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3098 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3099 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3100 }
3101 } else if (underlyingNetworks.length > 0) {
3102 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3103 if (linkProperties != null) {
3104 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3105 }
3106 }
3107 return info.primaryUnderlyingIface == null ? null : info;
3108 }
3109
3110 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003111 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3112 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003113 * Permissions are checked in Vpn class.
3114 * @hide
3115 */
3116 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003117 public VpnConfig getVpnConfig(int userId) {
3118 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003119 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003120 return mVpns.get(userId).getVpnConfig();
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003121 }
3122 }
3123
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003124 @Override
3125 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003126 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3127 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3128 return false;
3129 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003130
3131 // Tear down existing lockdown if profile was removed
3132 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3133 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003134 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003135 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3136 return false;
3137 }
3138
3139 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3140 final VpnProfile profile = VpnProfile.decode(
3141 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003142 int user = UserHandle.getUserId(Binder.getCallingUid());
3143 synchronized(mVpns) {
3144 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3145 profile));
3146 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003147 } else {
3148 setLockdownTracker(null);
3149 }
3150
3151 return true;
3152 }
3153
3154 /**
3155 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3156 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3157 */
3158 private void setLockdownTracker(LockdownVpnTracker tracker) {
3159 // Shutdown any existing tracker
3160 final LockdownVpnTracker existing = mLockdownTracker;
3161 mLockdownTracker = null;
3162 if (existing != null) {
3163 existing.shutdown();
3164 }
3165
3166 try {
3167 if (tracker != null) {
3168 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003169 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003170 mLockdownTracker = tracker;
3171 mLockdownTracker.init();
3172 } else {
3173 mNetd.setFirewallEnabled(false);
3174 }
3175 } catch (RemoteException e) {
3176 // ignored; NMS lives inside system_server
3177 }
3178 }
3179
3180 private void throwIfLockdownEnabled() {
3181 if (mLockdownEnabled) {
3182 throw new IllegalStateException("Unavailable in lockdown mode");
3183 }
3184 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003185
Wink Savilleab9321d2013-06-29 21:10:57 -07003186 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003187 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003188 // TODO: Remove? Any reason to trigger a provisioning check?
3189 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003190 }
3191
3192 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3193 private volatile boolean mIsNotificationVisible = false;
3194
Paul Jensen89e0f092014-09-15 15:59:36 -04003195 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003196 if (DBG) {
3197 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003198 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003199 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003200 Intent intent = new Intent(action);
3201 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003202 // Concatenate the range of types onto the range of NetIDs.
3203 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003204 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003205 }
3206
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003207 /**
3208 * Show or hide network provisioning notificaitons.
3209 *
3210 * @param id an identifier that uniquely identifies this notification. This must match
3211 * between show and hide calls. We use the NetID value but for legacy callers
3212 * we concatenate the range of types with the range of NetIDs.
3213 */
3214 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003215 String extraInfo, PendingIntent intent) {
3216 if (DBG) {
3217 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3218 networkType + " extraInfo=" + extraInfo);
3219 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003220
3221 Resources r = Resources.getSystem();
3222 NotificationManager notificationManager = (NotificationManager) mContext
3223 .getSystemService(Context.NOTIFICATION_SERVICE);
3224
3225 if (visible) {
3226 CharSequence title;
3227 CharSequence details;
3228 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003229 Notification notification = new Notification();
3230 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003231 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003232 title = r.getString(R.string.wifi_available_sign_in, 0);
3233 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003234 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003235 icon = R.drawable.stat_notify_wifi_in_range;
3236 break;
3237 case ConnectivityManager.TYPE_MOBILE:
3238 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003239 title = r.getString(R.string.network_available_sign_in, 0);
3240 // TODO: Change this to pull from NetworkInfo once a printable
3241 // name has been added to it
3242 details = mTelephonyManager.getNetworkOperatorName();
3243 icon = R.drawable.stat_notify_rssi_in_range;
3244 break;
3245 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003246 title = r.getString(R.string.network_available_sign_in, 0);
3247 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003248 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003249 icon = R.drawable.stat_notify_rssi_in_range;
3250 break;
3251 }
3252
Wink Savilleab9321d2013-06-29 21:10:57 -07003253 notification.when = 0;
3254 notification.icon = icon;
3255 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003256 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003257 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003258 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003259 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003260 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003261
Wink Saville948282b2013-08-29 08:55:16 -07003262 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003263 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003264 } catch (NullPointerException npe) {
3265 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3266 npe.printStackTrace();
3267 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003268 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003269 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003270 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003271 } catch (NullPointerException npe) {
3272 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3273 npe.printStackTrace();
3274 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003275 }
Wink Saville948282b2013-08-29 08:55:16 -07003276 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003277 }
3278
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003279 /** Location to an updatable file listing carrier provisioning urls.
3280 * An example:
3281 *
3282 * <?xml version="1.0" encoding="utf-8"?>
3283 * <provisioningUrls>
3284 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3285 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3286 * </provisioningUrls>
3287 */
3288 private static final String PROVISIONING_URL_PATH =
3289 "/data/misc/radio/provisioning_urls.xml";
3290 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003291
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003292 /** XML tag for root element. */
3293 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3294 /** XML tag for individual url */
3295 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3296 /** XML tag for redirected url */
3297 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3298 /** XML attribute for mcc */
3299 private static final String ATTR_MCC = "mcc";
3300 /** XML attribute for mnc */
3301 private static final String ATTR_MNC = "mnc";
3302
3303 private static final int REDIRECTED_PROVISIONING = 1;
3304 private static final int PROVISIONING = 2;
3305
3306 private String getProvisioningUrlBaseFromFile(int type) {
3307 FileReader fileReader = null;
3308 XmlPullParser parser = null;
3309 Configuration config = mContext.getResources().getConfiguration();
3310 String tagType;
3311
3312 switch (type) {
3313 case PROVISIONING:
3314 tagType = TAG_PROVISIONING_URL;
3315 break;
3316 case REDIRECTED_PROVISIONING:
3317 tagType = TAG_REDIRECTED_URL;
3318 break;
3319 default:
3320 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3321 type);
3322 }
3323
3324 try {
3325 fileReader = new FileReader(mProvisioningUrlFile);
3326 parser = Xml.newPullParser();
3327 parser.setInput(fileReader);
3328 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3329
3330 while (true) {
3331 XmlUtils.nextElement(parser);
3332
3333 String element = parser.getName();
3334 if (element == null) break;
3335
3336 if (element.equals(tagType)) {
3337 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3338 try {
3339 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3340 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3341 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3342 parser.next();
3343 if (parser.getEventType() == XmlPullParser.TEXT) {
3344 return parser.getText();
3345 }
3346 }
3347 }
3348 } catch (NumberFormatException e) {
3349 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3350 }
3351 }
3352 }
3353 return null;
3354 } catch (FileNotFoundException e) {
3355 loge("Carrier Provisioning Urls file not found");
3356 } catch (XmlPullParserException e) {
3357 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3358 } catch (IOException e) {
3359 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3360 } finally {
3361 if (fileReader != null) {
3362 try {
3363 fileReader.close();
3364 } catch (IOException e) {}
3365 }
3366 }
3367 return null;
3368 }
3369
Wink Saville42d4f082013-07-20 20:31:59 -07003370 @Override
3371 public String getMobileRedirectedProvisioningUrl() {
3372 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003373 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3374 if (TextUtils.isEmpty(url)) {
3375 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3376 }
3377 return url;
3378 }
3379
Wink Saville42d4f082013-07-20 20:31:59 -07003380 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003381 public String getMobileProvisioningUrl() {
3382 enforceConnectivityInternalPermission();
3383 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3384 if (TextUtils.isEmpty(url)) {
3385 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003386 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003387 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003388 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003389 }
Wink Saville8cf35602013-07-10 23:00:07 -07003390 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003391 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003392 String phoneNumber = mTelephonyManager.getLine1Number();
3393 if (TextUtils.isEmpty(phoneNumber)) {
3394 phoneNumber = "0000000000";
3395 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003396 url = String.format(url,
3397 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3398 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003399 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003400 }
3401
Wink Savilleab9321d2013-06-29 21:10:57 -07003402 return url;
3403 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003404
Wink Saville948282b2013-08-29 08:55:16 -07003405 @Override
3406 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003407 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003408 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003409 final long ident = Binder.clearCallingIdentity();
3410 try {
3411 setProvNotificationVisible(visible, networkType, action);
3412 } finally {
3413 Binder.restoreCallingIdentity(ident);
3414 }
Wink Saville948282b2013-08-29 08:55:16 -07003415 }
Wink Saville7788c612013-08-29 14:57:08 -07003416
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003417 @Override
3418 public void setAirplaneMode(boolean enable) {
3419 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003420 final long ident = Binder.clearCallingIdentity();
3421 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003422 final ContentResolver cr = mContext.getContentResolver();
3423 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3424 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3425 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003426 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003427 } finally {
3428 Binder.restoreCallingIdentity(ident);
3429 }
3430 }
3431
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003432 private void onUserStart(int userId) {
3433 synchronized(mVpns) {
3434 Vpn userVpn = mVpns.get(userId);
3435 if (userVpn != null) {
3436 loge("Starting user already has a VPN");
3437 return;
3438 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003439 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003440 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003441 }
3442 }
3443
3444 private void onUserStop(int userId) {
3445 synchronized(mVpns) {
3446 Vpn userVpn = mVpns.get(userId);
3447 if (userVpn == null) {
3448 loge("Stopping user has no VPN");
3449 return;
3450 }
3451 mVpns.delete(userId);
3452 }
3453 }
3454
3455 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3456 @Override
3457 public void onReceive(Context context, Intent intent) {
3458 final String action = intent.getAction();
3459 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3460 if (userId == UserHandle.USER_NULL) return;
3461
3462 if (Intent.ACTION_USER_STARTING.equals(action)) {
3463 onUserStart(userId);
3464 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3465 onUserStop(userId);
3466 }
3467 }
3468 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003469
Robert Greenwalta67be032014-05-16 15:49:14 -07003470 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3471 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003472 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3473 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003474
Robert Greenwalta67be032014-05-16 15:49:14 -07003475 private static class NetworkFactoryInfo {
3476 public final String name;
3477 public final Messenger messenger;
3478 public final AsyncChannel asyncChannel;
3479
3480 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3481 this.name = name;
3482 this.messenger = messenger;
3483 this.asyncChannel = asyncChannel;
3484 }
3485 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003486
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003487 /**
3488 * Tracks info about the requester.
3489 * Also used to notice when the calling process dies so we can self-expire
3490 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003491 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3492 static final boolean REQUEST = true;
3493 static final boolean LISTEN = false;
3494
3495 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003496 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003497 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003498 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003499 final int mPid;
3500 final int mUid;
3501 final Messenger messenger;
3502 final boolean isRequest;
3503
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003504 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3505 request = r;
3506 mPendingIntent = pi;
3507 messenger = null;
3508 mBinder = null;
3509 mPid = getCallingPid();
3510 mUid = getCallingUid();
3511 this.isRequest = isRequest;
3512 }
3513
Robert Greenwalt9258c642014-03-26 16:47:06 -07003514 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3515 super();
3516 messenger = m;
3517 request = r;
3518 mBinder = binder;
3519 mPid = getCallingPid();
3520 mUid = getCallingUid();
3521 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003522 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003523
3524 try {
3525 mBinder.linkToDeath(this, 0);
3526 } catch (RemoteException e) {
3527 binderDied();
3528 }
3529 }
3530
3531 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003532 if (mBinder != null) {
3533 mBinder.unlinkToDeath(this, 0);
3534 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003535 }
3536
3537 public void binderDied() {
3538 log("ConnectivityService NetworkRequestInfo binderDied(" +
3539 request + ", " + mBinder + ")");
3540 releaseNetworkRequest(request);
3541 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003542
3543 public String toString() {
3544 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003545 mPid + " for " + request +
3546 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003547 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003548 }
3549
3550 @Override
3551 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003552 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003553 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003554 enforceNetworkRequestPermissions(networkCapabilities);
3555 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003556
Robert Greenwalt6078b502014-06-11 16:05:07 -07003557 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003558 throw new IllegalArgumentException("Bad timeout specified");
3559 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003560
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003561 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3562 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003563 if (DBG) log("requestNetwork for " + networkRequest);
3564 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3565 NetworkRequestInfo.REQUEST);
3566
3567 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003568 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003569 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003570 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003571 }
3572 return networkRequest;
3573 }
3574
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003575 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003576 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003577 enforceConnectivityInternalPermission();
3578 } else {
3579 enforceChangePermission();
3580 }
3581 }
3582
fenglub15e72b2015-03-20 11:29:56 -07003583 @Override
fengludb571472015-04-21 17:12:05 -07003584 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003585 enforceAccessPermission();
3586 NetworkAgentInfo nai = null;
3587 if (network == null) {
3588 return false;
3589 }
3590 synchronized (mNetworkForNetId) {
3591 nai = mNetworkForNetId.get(network.netId);
3592 }
3593 if (nai != null) {
3594 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3595 return true;
3596 }
3597 return false;
3598 }
3599
3600
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003601 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3602 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003603 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003604 final int uidRules;
3605 final int uid = Binder.getCallingUid();
3606 synchronized(mRulesLock) {
3607 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3608 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003609 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003610 // we could silently fail or we can filter the available nets to only give
3611 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003612 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003613 }
3614 }
3615 }
3616
Robert Greenwalt9258c642014-03-26 16:47:06 -07003617 @Override
3618 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3619 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003620 checkNotNull(operation, "PendingIntent cannot be null.");
3621 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3622 enforceNetworkRequestPermissions(networkCapabilities);
3623 enforceMeteredApnPolicy(networkCapabilities);
3624
3625 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3626 nextNetworkRequestId());
3627 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3628 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3629 NetworkRequestInfo.REQUEST);
3630 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3631 nri));
3632 return networkRequest;
3633 }
3634
Jeremy Joslin79294842014-12-03 17:15:28 -08003635 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3636 mHandler.sendMessageDelayed(
3637 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3638 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3639 }
3640
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003641 @Override
3642 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003643 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003644 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3645 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003646 }
3647
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003648 // In order to implement the compatibility measure for pre-M apps that call
3649 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3650 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3651 // This ensures it has permission to do so.
3652 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3653 if (nc == null) {
3654 return false;
3655 }
3656 int[] transportTypes = nc.getTransportTypes();
3657 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3658 return false;
3659 }
3660 try {
3661 mContext.enforceCallingOrSelfPermission(
3662 android.Manifest.permission.ACCESS_WIFI_STATE,
3663 "ConnectivityService");
3664 } catch (SecurityException e) {
3665 return false;
3666 }
3667 return true;
3668 }
3669
Robert Greenwalt9258c642014-03-26 16:47:06 -07003670 @Override
3671 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3672 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003673 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3674 enforceAccessPermission();
3675 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003676
3677 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003678 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003679 if (DBG) log("listenForNetwork for " + networkRequest);
3680 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3681 NetworkRequestInfo.LISTEN);
3682
3683 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3684 return networkRequest;
3685 }
3686
3687 @Override
3688 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3689 PendingIntent operation) {
3690 }
3691
3692 @Override
3693 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003694 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3695 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003696 }
3697
3698 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003699 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003700 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003701 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3702 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003703 }
3704
Robert Greenwalta67be032014-05-16 15:49:14 -07003705 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003706 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003707 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3708 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3709 }
3710
3711 @Override
3712 public void unregisterNetworkFactory(Messenger messenger) {
3713 enforceConnectivityInternalPermission();
3714 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3715 }
3716
3717 private void handleUnregisterNetworkFactory(Messenger messenger) {
3718 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3719 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003720 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003721 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003722 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003723 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003724 }
3725
Robert Greenwalt7b816022014-04-18 15:25:25 -07003726 /**
3727 * NetworkAgentInfo supporting a request by requestId.
3728 * These have already been vetted (their Capabilities satisfy the request)
3729 * and the are the highest scored network available.
3730 * the are keyed off the Requests requestId.
3731 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003732 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003733 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3734 new SparseArray<NetworkAgentInfo>();
3735
Paul Jensen31a94f42015-02-13 14:18:39 -05003736 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3737 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003738 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3739 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003740 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3741 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3742 // there may not be a strict 1:1 correlation between the two.
3743 @GuardedBy("mNetworkForNetId")
3744 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003745
Robert Greenwalt7b816022014-04-18 15:25:25 -07003746 // NetworkAgentInfo keyed off its connecting messenger
3747 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003748 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003749 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3750 new HashMap<Messenger, NetworkAgentInfo>();
3751
Paul Jensen2c311d62014-11-17 12:34:51 -05003752 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003753 private final NetworkRequest mDefaultRequest;
3754
Erik Klineda4bfa82015-04-30 12:58:40 +09003755 // Request used to optionally keep mobile data active even when higher
3756 // priority networks like Wi-Fi are active.
3757 private final NetworkRequest mDefaultMobileDataRequest;
3758
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003759 private NetworkAgentInfo getDefaultNetwork() {
3760 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3761 }
3762
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003763 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003764 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003765 }
3766
Paul Jensen31a94f42015-02-13 14:18:39 -05003767 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003768 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003769 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003770 enforceConnectivityInternalPermission();
3771
Paul Jensen2c311d62014-11-17 12:34:51 -05003772 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3773 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003774 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003775 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3776 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3777 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003778 synchronized (this) {
3779 nai.networkMonitor.systemReady = mSystemReady;
3780 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003781 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003782 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003783 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003784 }
3785
3786 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3787 if (VDBG) log("Got NetworkAgent Messenger");
3788 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003789 synchronized (mNetworkForNetId) {
3790 mNetworkForNetId.put(na.network.netId, na);
3791 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003792 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3793 NetworkInfo networkInfo = na.networkInfo;
3794 na.networkInfo = null;
3795 updateNetworkInfo(na, networkInfo);
3796 }
3797
3798 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3799 LinkProperties newLp = networkAgent.linkProperties;
3800 int netId = networkAgent.network.netId;
3801
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003802 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3803 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003804 if (networkAgent.clatd != null) {
3805 networkAgent.clatd.fixupLinkProperties(oldLp);
3806 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003807
Paul Jensen992f2522014-04-28 10:33:11 -04003808 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003809 updateMtu(newLp, oldLp);
3810 // TODO - figure out what to do for clat
3811// for (LinkProperties lp : newLp.getStackedLinks()) {
3812// updateMtu(lp, null);
3813// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003814 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003815
3816 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3817 // For now, use it only when the network has Internet access. http://b/18327075
3818 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003819 NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003820 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003821 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3822
Paul Jensen3b759822014-05-13 11:44:01 -04003823 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003824 if (isDefaultNetwork(networkAgent)) {
3825 handleApplyDefaultProxy(newLp.getHttpProxy());
3826 } else {
3827 updateProxy(newLp, oldLp, networkAgent);
3828 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003829 // TODO - move this check to cover the whole function
3830 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003831 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003832 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3833 }
Paul Jensen3b759822014-05-13 11:44:01 -04003834 }
3835
Lorenzo Colitti95439462014-10-09 13:44:48 +09003836 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3837 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3838 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003839
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003840 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003841 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3842 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003843 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003844 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003845 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003846 }
Paul Jensen992f2522014-04-28 10:33:11 -04003847
3848 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3849 CompareResult<String> interfaceDiff = new CompareResult<String>();
3850 if (oldLp != null) {
3851 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3852 } else if (newLp != null) {
3853 interfaceDiff.added = newLp.getAllInterfaceNames();
3854 }
3855 for (String iface : interfaceDiff.added) {
3856 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003857 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003858 mNetd.addInterfaceToNetwork(iface, netId);
3859 } catch (Exception e) {
3860 loge("Exception adding interface: " + e);
3861 }
3862 }
3863 for (String iface : interfaceDiff.removed) {
3864 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003865 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003866 mNetd.removeInterfaceFromNetwork(iface, netId);
3867 } catch (Exception e) {
3868 loge("Exception removing interface: " + e);
3869 }
3870 }
3871 }
3872
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003873 /**
3874 * Have netd update routes from oldLp to newLp.
3875 * @return true if routes changed between oldLp and newLp
3876 */
3877 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003878 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3879 if (oldLp != null) {
3880 routeDiff = oldLp.compareAllRoutes(newLp);
3881 } else if (newLp != null) {
3882 routeDiff.added = newLp.getAllRoutes();
3883 }
3884
3885 // add routes before removing old in case it helps with continuous connectivity
3886
3887 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3888 for (RouteInfo route : routeDiff.added) {
3889 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003890 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003891 try {
3892 mNetd.addRoute(netId, route);
3893 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003894 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3895 loge("Exception in addRoute for non-gateway: " + e);
3896 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003897 }
3898 }
3899 for (RouteInfo route : routeDiff.added) {
3900 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003901 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003902 try {
3903 mNetd.addRoute(netId, route);
3904 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003905 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3906 loge("Exception in addRoute for gateway: " + e);
3907 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003908 }
3909 }
3910
3911 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003912 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003913 try {
3914 mNetd.removeRoute(netId, route);
3915 } catch (Exception e) {
3916 loge("Exception in removeRoute: " + e);
3917 }
3918 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003919 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003920 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003921 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3922 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003923 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003924 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003925 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003926 dnses = new ArrayList();
3927 dnses.add(mDefaultDns);
3928 if (DBG) {
3929 loge("no dns provided for netId " + netId + ", so using defaults");
3930 }
3931 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003932 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003933 try {
3934 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3935 newLp.getDomains());
3936 } catch (Exception e) {
3937 loge("Exception in setDnsServersForNetwork: " + e);
3938 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003939 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3940 if (defaultNai != null && defaultNai.network.netId == netId) {
3941 setDefaultDnsSystemProperties(dnses);
3942 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003943 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003944 } else if (flush) {
3945 try {
3946 mNetd.flushNetworkDnsCache(netId);
3947 } catch (Exception e) {
3948 loge("Exception in flushNetworkDnsCache: " + e);
3949 }
3950 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003951 }
3952 }
3953
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003954 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3955 int last = 0;
3956 for (InetAddress dns : dnses) {
3957 ++last;
3958 String key = "net.dns" + last;
3959 String value = dns.getHostAddress();
3960 SystemProperties.set(key, value);
3961 }
3962 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3963 String key = "net.dns" + i;
3964 SystemProperties.set(key, "");
3965 }
3966 mNumDnsEntries = last;
3967 }
3968
Robert Greenwalt7b816022014-04-18 15:25:25 -07003969 private void updateCapabilities(NetworkAgentInfo networkAgent,
3970 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003971 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3972 synchronized (networkAgent) {
3973 networkAgent.networkCapabilities = networkCapabilities;
3974 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003975 if (networkAgent.lastValidated) {
3976 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
3977 // There's no need to remove the capability if we think the network is unvalidated,
3978 // because NetworkAgents don't set the validated capability.
3979 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003980 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003981 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003982 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003983 }
3984
Paul Jensenc8b9a742014-09-30 15:37:41 -04003985 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3986 for (int i = 0; i < nai.networkRequests.size(); i++) {
3987 NetworkRequest nr = nai.networkRequests.valueAt(i);
3988 // Don't send listening requests to factories. b/17393458
3989 if (!isRequest(nr)) continue;
3990 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3991 }
3992 }
3993
Robert Greenwalt7b816022014-04-18 15:25:25 -07003994 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3995 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07003996 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07003997 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3998 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003999 }
4000 }
4001
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004002 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4003 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004004 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004005 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004006 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4007 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004008 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004009 sendIntent(nri.mPendingIntent, intent);
4010 }
4011 // else not handled
4012 }
4013
4014 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4015 mPendingIntentWakeLock.acquire();
4016 try {
4017 if (DBG) log("Sending " + pendingIntent);
4018 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4019 } catch (PendingIntent.CanceledException e) {
4020 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4021 mPendingIntentWakeLock.release();
4022 releasePendingNetworkRequest(pendingIntent);
4023 }
4024 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4025 }
4026
4027 @Override
4028 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4029 String resultData, Bundle resultExtras) {
4030 if (DBG) log("Finished sending " + pendingIntent);
4031 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004032 // Release with a delay so the receiving client has an opportunity to put in its
4033 // own request.
4034 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004035 }
4036
Robert Greenwalt9258c642014-03-26 16:47:06 -07004037 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004038 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004039 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004040 Bundle bundle = new Bundle();
4041 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4042 new NetworkRequest(nri.request));
4043 Message msg = Message.obtain();
4044 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4045 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4046 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4047 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004048 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004049 case ConnectivityManager.CALLBACK_LOSING: {
4050 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4051 break;
4052 }
4053 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4054 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4055 new NetworkCapabilities(networkAgent.networkCapabilities));
4056 break;
4057 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004058 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004059 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4060 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004061 break;
4062 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004063 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004064 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004065 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004066 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004067 if (VDBG) {
4068 log("sending notification " + notifyTypeToName(notificationType) +
4069 " for " + nri.request);
4070 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004071 nri.messenger.send(msg);
4072 } catch (RemoteException e) {
4073 // may occur naturally in the race of binder death.
4074 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4075 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004076 }
4077
Paul Jensenc8b9a742014-09-30 15:37:41 -04004078 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4079 for (int i = 0; i < nai.networkRequests.size(); i++) {
4080 NetworkRequest nr = nai.networkRequests.valueAt(i);
4081 // Ignore listening requests.
4082 if (!isRequest(nr)) continue;
4083 loge("Dead network still had at least " + nr);
4084 break;
4085 }
4086 nai.asyncChannel.disconnect();
4087 }
4088
Robert Greenwalt7b816022014-04-18 15:25:25 -07004089 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4090 if (oldNetwork == null) {
4091 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4092 return;
4093 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004094 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4095 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004096 }
4097
Paul Jensen27b02b72014-07-14 12:03:33 -04004098 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004099 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004100 setupDataActivityTracking(newNetwork);
4101 try {
4102 mNetd.setDefaultNetId(newNetwork.network.netId);
4103 } catch (Exception e) {
4104 loge("Exception setting default network :" + e);
4105 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004106 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004107 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004108 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004109 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004110 }
4111
Paul Jensen2161a8e2014-09-11 11:00:39 -04004112 // Handles a network appearing or improving its score.
4113 //
4114 // - Evaluates all current NetworkRequests that can be
4115 // satisfied by newNetwork, and reassigns to newNetwork
4116 // any such requests for which newNetwork is the best.
4117 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004118 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004119 // needed. A network is needed if it is the best network for
4120 // one or more NetworkRequests, or if it is a VPN.
4121 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004122 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004123 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4124 //
4125 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4126 // networks that have no chance (i.e. even if validated)
4127 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004128 //
4129 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4130 // it does not remove NetworkRequests that other Networks could better satisfy.
4131 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4132 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4133 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004134 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004135 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004136 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004137 // torn down if unneeded.
4138 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4139 // performed to tear down unvalidated networks that have no chance (i.e. even if
4140 // validated) of becoming the highest scoring network.
4141 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4142 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004143 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004144 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004145 loge("ERROR: nascent network not validated.");
4146 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004147 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004148 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004149 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004150 if (DBG) log("rematching " + newNetwork.name());
4151 // Find and migrate to this Network any NetworkRequests for
4152 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004153 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004154 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004155 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004156 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4157 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004158 if (DBG) {
4159 log("Network " + newNetwork.name() + " was already satisfying" +
4160 " request " + nri.request.requestId + ". No change.");
4161 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004162 keep = true;
4163 continue;
4164 }
4165
4166 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004167 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004168 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004169 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004170 // This is not a request, it's a callback listener.
4171 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004172 newNetwork.addRequest(nri.request);
4173 continue;
4174 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004175
Robert Greenwalt7b816022014-04-18 15:25:25 -07004176 // next check if it's better than any current network we're using for
4177 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004178 if (VDBG) {
4179 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004180 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4181 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004182 }
4183 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004184 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004185 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004186 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004187 currentNetwork.networkRequests.remove(nri.request.requestId);
4188 currentNetwork.networkLingered.add(nri.request);
4189 affectedNetworks.add(currentNetwork);
4190 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004191 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004192 }
Paul Jensen573a0352015-01-08 10:49:34 -05004193 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004195 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004196 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004197 // Tell NetworkFactories about the new score, so they can stop
4198 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004199 // TODO - this could get expensive if we have alot of requests for this
4200 // network. Think about if there is a way to reduce this. Push
4201 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004202 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004203 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004204 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004205 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004206 }
4207 }
4208 }
4209 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004210 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004211 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004212 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004213 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4214 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4215 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004216 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004217 }
4218 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004219 if (keep) {
4220 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004221 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004222 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004223 synchronized (ConnectivityService.this) {
4224 // have a new default network, release the transition wakelock in
4225 // a second if it's held. The second pause is to allow apps
4226 // to reconnect over the new network
4227 if (mNetTransitionWakeLock.isHeld()) {
4228 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4229 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4230 mNetTransitionWakeLockSerialNumber, 0),
4231 1000);
4232 }
4233 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004234 }
4235
4236 // do this after the default net is switched, but
4237 // before LegacyTypeTracker sends legacy broadcasts
4238 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4239
4240 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004241 // Maintain the illusion: since the legacy API only
4242 // understands one network at a time, we must pretend
4243 // that the current default network disconnected before
4244 // the new one connected.
4245 if (oldDefaultNetwork != null) {
4246 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004247 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004248 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004249 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004250 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4251 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004252 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004253
4254 // Notify battery stats service about this network, both the normal
4255 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004256 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004257 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004258 final IBatteryStats bs = BatteryStatsService.getService();
4259 final int type = newNetwork.networkInfo.getType();
4260
4261 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4262 bs.noteNetworkInterfaceType(baseIface, type);
4263 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4264 final String stackedIface = stacked.getInterfaceName();
4265 bs.noteNetworkInterfaceType(stackedIface, type);
4266 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4267 }
4268 } catch (RemoteException ignored) {
4269 }
4270
Robert Greenwalt152ed372014-12-17 17:19:53 -08004271 // This has to happen after the notifyNetworkCallbacks as that tickles each
4272 // ConnectivityManager instance so that legacy requests correctly bind dns
4273 // requests to this network. The legacy users are listening for this bcast
4274 // and will generally do a dns request so they can ensureRouteToHost and if
4275 // they do that before the callbacks happen they'll use the default network.
4276 //
4277 // TODO: Is there still a race here? We send the broadcast
4278 // after sending the callback, but if the app can receive the
4279 // broadcast before the callback, it might still break.
4280 //
4281 // This *does* introduce a race where if the user uses the new api
4282 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4283 // they may get old info. Reverse this after the old startUsing api is removed.
4284 // This is on top of the multiple intent sequencing referenced in the todo above.
4285 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4286 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4287 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4288 // legacy type tracker filters out repeat adds
4289 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4290 }
4291 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004292
4293 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4294 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4295 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4296 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4297 if (newNetwork.isVPN()) {
4298 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4299 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004300 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004301 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004302 // validated (and get evaluated against peers, one losing here), or get reaped (see
4303 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4304 // network. Networks that have been up for a while and are validated should be torn
4305 // down via the lingering process so communication on that network is given time to
4306 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004307 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004308 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004309 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004310 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4311 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004312 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004313 if (DBG) log("Reaping " + nai.name());
4314 teardownUnneededNetwork(nai);
4315 }
4316 }
4317 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004318 }
4319
Paul Jensen2161a8e2014-09-11 11:00:39 -04004320 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4321 // being disconnected.
4322 // If only one Network's score or capabilities have been modified since the last time
4323 // this function was called, pass this Network in via the "changed" arugment, otherwise
4324 // pass null.
4325 // If only one Network has been changed but its NetworkCapabilities have not changed,
4326 // pass in the Network's score (from getCurrentScore()) prior to the change via
4327 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4328 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4329 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4330 // to avoid the slowness. It is not simply enough to process just "changed", for
4331 // example in the case where "changed"'s score decreases and another network should begin
4332 // satifying a NetworkRequest that "changed" currently satisfies.
4333
4334 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4335 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4336 // rematchNetworkAndRequests() handles.
4337 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004338 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4339 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004340 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004341 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4342 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4343 NascentState.NOT_JUST_VALIDATED,
4344 // Only reap the last time through the loop. Reaping before all rematching
4345 // is complete could incorrectly teardown a network that hasn't yet been
4346 // rematched.
4347 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4348 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004349 }
4350 }
4351 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004352
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004353 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004354 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004355 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004356 // For now only update icons for default connection.
4357 // TODO: Update WiFi and cellular icons separately. b/17237507
4358 if (!isDefaultNetwork(nai)) return;
4359
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004360 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004361 // Don't repeat publish.
4362 if (newInetCondition == mDefaultInetConditionPublished) return;
4363
4364 mDefaultInetConditionPublished = newInetCondition;
4365 sendInetConditionBroadcast(nai.networkInfo);
4366 }
4367
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004368 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4369 if (mLockdownTracker != null) {
4370 if (nai != null && nai.isVPN()) {
4371 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4372 } else {
4373 mLockdownTracker.onNetworkInfoChanged();
4374 }
4375 }
4376 }
4377
Robert Greenwalt7b816022014-04-18 15:25:25 -07004378 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4379 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004380 NetworkInfo oldInfo = null;
4381 synchronized (networkAgent) {
4382 oldInfo = networkAgent.networkInfo;
4383 networkAgent.networkInfo = newInfo;
4384 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004385 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004386
4387 if (oldInfo != null && oldInfo.getState() == state) {
4388 if (VDBG) log("ignoring duplicate network state non-change");
4389 return;
4390 }
4391 if (DBG) {
4392 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4393 (oldInfo == null ? "null" : oldInfo.getState()) +
4394 " to " + state);
4395 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004396
Paul Jenseneec75412014-08-04 12:21:19 -04004397 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004398 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004399 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004400 if (networkAgent.isVPN()) {
4401 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004402 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4403 (networkAgent.networkMisc == null ||
4404 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004405 } else {
4406 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4407 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004408 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004409 loge("Error creating network " + networkAgent.network.netId + ": "
4410 + e.getMessage());
4411 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004412 }
Paul Jenseneec75412014-08-04 12:21:19 -04004413 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004414 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004415 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004416
Paul Jensenca8f16a2014-05-09 12:47:55 -04004417 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004418 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004419
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004420 if (networkAgent.isVPN()) {
4421 // Temporarily disable the default proxy (not global).
4422 synchronized (mProxyLock) {
4423 if (!mDefaultProxyDisabled) {
4424 mDefaultProxyDisabled = true;
4425 if (mGlobalProxy == null && mDefaultProxy != null) {
4426 sendProxyBroadcast(null);
4427 }
4428 }
4429 }
4430 // TODO: support proxy per network.
4431 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004432
Paul Jensen2161a8e2014-09-11 11:00:39 -04004433 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004434 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4435 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004436
4437 // This has to happen after matching the requests, because callbacks are just requests.
4438 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004439 } else if (state == NetworkInfo.State.DISCONNECTED ||
4440 state == NetworkInfo.State.SUSPENDED) {
4441 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004442 if (networkAgent.isVPN()) {
4443 synchronized (mProxyLock) {
4444 if (mDefaultProxyDisabled) {
4445 mDefaultProxyDisabled = false;
4446 if (mGlobalProxy == null && mDefaultProxy != null) {
4447 sendProxyBroadcast(mDefaultProxy);
4448 }
4449 }
4450 }
4451 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004452 }
4453 }
4454
Robert Greenwaltac96c522014-06-03 16:43:57 -07004455 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4456 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004457 if (score < 0) {
4458 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4459 "). Bumping score to min of 0");
4460 score = 0;
4461 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004462
Paul Jensen2161a8e2014-09-11 11:00:39 -04004463 final int oldScore = nai.getCurrentScore();
4464 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004465
Paul Jensen57a767f2014-11-19 13:01:46 -05004466 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004467
Paul Jensenc8b9a742014-09-30 15:37:41 -04004468 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004469 }
4470
Robert Greenwalt9258c642014-03-26 16:47:06 -07004471 // notify only this one new request of the current state
4472 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4473 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4474 // TODO - read state from monitor to decide what to send.
4475// if (nai.networkMonitor.isLingering()) {
4476// notifyType = NetworkCallbacks.LOSING;
4477// } else if (nai.networkMonitor.isEvaluating()) {
4478// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4479// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004480 if (nri.mPendingIntent == null) {
4481 callCallbackForRequest(nri, nai, notifyType);
4482 } else {
4483 sendPendingIntentForRequest(nri, nai, notifyType);
4484 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004485 }
4486
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004487 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004488 // The NetworkInfo we actually send out has no bearing on the real
4489 // state of affairs. For example, if the default connection is mobile,
4490 // and a request for HIPRI has just gone away, we need to pretend that
4491 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4492 // the state to DISCONNECTED, even though the network is of type MOBILE
4493 // and is still connected.
4494 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4495 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004496 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004497 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004498 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004499 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004500 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004501 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4502 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4503 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4504 if (info.isFailover()) {
4505 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4506 nai.networkInfo.setFailover(false);
4507 }
4508 if (info.getReason() != null) {
4509 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4510 }
4511 if (info.getExtraInfo() != null) {
4512 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4513 }
4514 NetworkAgentInfo newDefaultAgent = null;
4515 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4516 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4517 if (newDefaultAgent != null) {
4518 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4519 newDefaultAgent.networkInfo);
4520 } else {
4521 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4522 }
4523 }
4524 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4525 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004526 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004527 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004528 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004529 }
4530 }
4531 }
4532
Robert Greenwalt7b816022014-04-18 15:25:25 -07004533 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004534 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004535 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004536 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4537 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4538 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004539 if (nri.mPendingIntent == null) {
4540 callCallbackForRequest(nri, networkAgent, notifyType);
4541 } else {
4542 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4543 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004544 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004545 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004546
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004547 private String notifyTypeToName(int notifyType) {
4548 switch (notifyType) {
4549 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4550 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4551 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4552 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4553 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4554 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4555 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4556 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4557 }
4558 return "UNKNOWN";
4559 }
4560
Jeff Sharkey69736342014-12-08 14:50:12 -08004561 /**
4562 * Notify other system services that set of active ifaces has changed.
4563 */
4564 private void notifyIfacesChanged() {
4565 try {
4566 mStatsService.forceUpdateIfaces();
4567 } catch (Exception ignored) {
4568 }
4569 }
4570
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004571 @Override
4572 public boolean addVpnAddress(String address, int prefixLength) {
4573 throwIfLockdownEnabled();
4574 int user = UserHandle.getUserId(Binder.getCallingUid());
4575 synchronized (mVpns) {
4576 return mVpns.get(user).addAddress(address, prefixLength);
4577 }
4578 }
4579
4580 @Override
4581 public boolean removeVpnAddress(String address, int prefixLength) {
4582 throwIfLockdownEnabled();
4583 int user = UserHandle.getUserId(Binder.getCallingUid());
4584 synchronized (mVpns) {
4585 return mVpns.get(user).removeAddress(address, prefixLength);
4586 }
4587 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004588
4589 @Override
4590 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4591 throwIfLockdownEnabled();
4592 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004593 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004594 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004595 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004596 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004597 if (success) {
4598 notifyIfacesChanged();
4599 }
4600 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004601 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004602
4603 @Override
4604 public void factoryReset() {
4605 enforceConnectivityInternalPermission();
Robin Lee3b3dd942015-05-12 18:14:58 +01004606 final int userId = UserHandle.getCallingUserId();
4607
Stuart Scottf1fb3972015-04-02 18:00:02 -07004608 // Turn airplane mode off
4609 setAirplaneMode(false);
4610
4611 // Untether
4612 for (String tether : getTetheredIfaces()) {
4613 untether(tether);
4614 }
4615
4616 // Turn VPN off
Robin Lee3b3dd942015-05-12 18:14:58 +01004617 VpnConfig vpnConfig = getVpnConfig(userId);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004618 if (vpnConfig != null) {
4619 if (vpnConfig.legacy) {
Robin Lee3b3dd942015-05-12 18:14:58 +01004620 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004621 } else {
Robin Lee3b3dd942015-05-12 18:14:58 +01004622 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4623 // in the future without user intervention.
4624 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004625
Robin Lee3b3dd942015-05-12 18:14:58 +01004626 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004627 }
4628 }
4629 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004630}