blob: 16b3dcfa8b851401e31d43d24028fedeac723309 [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;
26import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070027import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070028import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070029
Wenchao Tongf5ea3402015-03-04 13:26:38 -080030import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070031import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070032import android.app.Notification;
33import android.app.NotificationManager;
34import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070035import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070041import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090042import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070043import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.net.ConnectivityManager;
45import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070046import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070047import android.net.INetworkPolicyListener;
48import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070049import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080050import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070051import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070052import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070053import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070054import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070055import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070058import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070059import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070061import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070062import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070063import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040064import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070065import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040066import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040067import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070069import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040070import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070072import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070073import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070074import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Looper;
76import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070077import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070078import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070079import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070080import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070082import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070084import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040085import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070087import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070088import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070089import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080091import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070092import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -050093import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070094import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070095import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Wink Savilleab9321d2013-06-29 21:10:57 -070097import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -040098import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070099import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700100import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700101import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700102import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800103import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700106import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700107import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700108import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700109import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400110import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900111import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700112import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400113import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400114import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700115import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800116import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700118import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700119import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700120import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700121import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700122
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700123import org.xmlpull.v1.XmlPullParser;
124import org.xmlpull.v1.XmlPullParserException;
125
126import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import java.io.FileNotFoundException;
129import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700130import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700132import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700133import java.net.InetAddress;
134import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700135import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700136import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700137import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700138import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700139import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500140import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700142import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700143import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700144import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146/**
147 * @hide
148 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800149public class ConnectivityService extends IConnectivityManager.Stub
150 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700151 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700153 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700154 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
Jake Hamby786e71a2014-02-06 14:43:50 -0800156 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700157
Jeff Sharkey899223b2012-08-04 15:24:58 -0700158 // TODO: create better separation between radio types and network types
159
Robert Greenwalt42acef32009-08-12 16:08:25 -0700160 // how long to wait before switching back to a radio's default network
161 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
162 // system property that can override the above value
163 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
164 "android.telephony.apn-restore";
165
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900166 // How long to wait before putting up a "This network doesn't have an Internet connection,
167 // connect anyway?" dialog after the user selects a network that doesn't validate.
168 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
169
Jeremy Joslin79294842014-12-03 17:15:28 -0800170 // How long to delay to removal of a pending intent based request.
171 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
172 private final int mReleasePendingIntentDelayMs;
173
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800174 private Tethering mTethering;
175
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700176 private final PermissionMonitor mPermissionMonitor;
177
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700178 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700179
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700180 @GuardedBy("mVpns")
181 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700182
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700183 private boolean mLockdownEnabled;
184 private LockdownVpnTracker mLockdownTracker;
185
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700186 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
187 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700188 /** Currently active network rules by UID. */
189 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700190 /** Set of ifaces that are costly. */
191 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192
Erik Klineda4bfa82015-04-30 12:58:40 +0900193 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800194 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700195 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700196 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700198 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800199 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
201 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700202 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700204 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800205 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700206 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700207
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700208 private String mCurrentTcpBufferSizes;
209
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700210 private static final int ENABLED = 1;
211 private static final int DISABLED = 0;
212
Paul Jensenb10e37f2014-11-25 12:33:08 -0500213 // Arguments to rematchNetworkAndRequests()
214 private enum NascentState {
215 // Indicates a network was just validated for the first time. If the network is found to
216 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
217 JUST_VALIDATED,
218 // Indicates a network was not validated for the first time immediately prior to this call.
219 NOT_JUST_VALIDATED
220 };
221 private enum ReapUnvalidatedNetworks {
222 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
223 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
224 // known that there may be unvalidated networks that could potentially be reaped, and when
225 // all networks have been rematched against all NetworkRequests.
226 REAP,
227 // Don't reap unvalidated networks. This should be passed when it's known that there are
228 // no unvalidated networks that could potentially be reaped, and when some networks have
229 // not yet been rematched against all NetworkRequests.
230 DONT_REAP
231 };
232
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700233 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700234 * used internally to change our mobile data enabled flag
235 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700236 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237
238 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700239 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700240 * from one net to another. Clear happens when we get a new
241 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
242 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700245
Robert Greenwalt434203a2010-10-11 16:00:27 -0700246 /**
247 * used internally to reload global proxy settings
248 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700249 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700251 /**
Wink Saville628b0852011-08-04 15:01:58 -0700252 * used internally to send a sticky broadcast delayed.
253 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700254 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700255
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700256 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400257 * PAC manager has received new port.
258 */
259 private static final int EVENT_PROXY_HAS_CHANGED = 16;
260
Robert Greenwalte049c232014-04-11 15:53:27 -0700261 /**
262 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700263 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 */
265 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
266
Robert Greenwalt7b816022014-04-18 15:25:25 -0700267 /**
268 * used internally when registering NetworkAgents
269 * obj = Messenger
270 */
271 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
272
Robert Greenwalt9258c642014-03-26 16:47:06 -0700273 /**
274 * used to add a network request
275 * includes a NetworkRequestInfo
276 */
277 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
278
279 /**
280 * indicates a timeout period is over - check if we had a network yet or not
281 * and if not, call the timeout calback (but leave the request live until they
282 * cancel it.
283 * includes a NetworkRequestInfo
284 */
285 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
286
287 /**
288 * used to add a network listener - no request
289 * includes a NetworkRequestInfo
290 */
291 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
292
293 /**
294 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400295 * arg1 = UID of caller
296 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700297 */
298 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
299
Robert Greenwalta67be032014-05-16 15:49:14 -0700300 /**
301 * used internally when registering NetworkFactories
302 * obj = Messenger
303 */
304 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
305
Robert Greenwalt27711812014-06-25 16:45:57 -0700306 /**
307 * used internally to expire a wakelock when transitioning
308 * from one net to another. Expire happens when we fail to find
309 * a new network (typically after 1 minute) -
310 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
311 * a replacement network.
312 */
313 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
314
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700315 /**
316 * Used internally to indicate the system is ready.
317 */
318 private static final int EVENT_SYSTEM_READY = 25;
319
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800320 /**
321 * used to add a network request with a pending intent
322 * includes a NetworkRequestInfo
323 */
324 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
325
326 /**
327 * used to remove a pending intent and its associated network request.
328 * arg1 = UID of caller
329 * obj = PendingIntent
330 */
331 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
332
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900333 /**
334 * used to specify whether a network should be used even if unvalidated.
335 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
336 * arg2 = whether to remember this choice in the future (1 or 0)
337 * obj = network
338 */
339 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
340
341 /**
342 * used to ask the user to confirm a connection to an unvalidated network.
343 * obj = network
344 */
345 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700346
Erik Klineda4bfa82015-04-30 12:58:40 +0900347 /**
348 * used internally to (re)configure mobile data always-on settings.
349 */
350 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
351
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700352 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700353 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700354 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700355 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700356
Mike Lockwood0f79b542009-08-14 14:18:49 -0400357 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800358 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400359
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700360 private PowerManager.WakeLock mNetTransitionWakeLock;
361 private String mNetTransitionWakeLockCausedBy = "";
362 private int mNetTransitionWakeLockSerialNumber;
363 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800364 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700365
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700366 private InetAddress mDefaultDns;
367
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700368 // used in DBG mode to track inet condition reports
369 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
370 private ArrayList mInetLog;
371
Robert Greenwalt434203a2010-10-11 16:00:27 -0700372 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400373 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700374 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700375 private boolean mDefaultProxyDisabled = false;
376
Robert Greenwalt434203a2010-10-11 16:00:27 -0700377 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400378 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700379
Jason Monk602b2322013-07-03 17:04:33 -0400380 private PacManager mPacManager = null;
381
Erik Klineda4bfa82015-04-30 12:58:40 +0900382 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700383
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400384 private UserManager mUserManager;
385
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700386 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700387 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700388
Robert Greenwalt50393202011-06-21 17:26:14 -0700389 // the set of network types that can only be enabled by system/sig apps
390 List mProtectedNetworks;
391
John Spurlockbf991a82013-06-24 14:20:23 -0400392 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700393
Wink Savilleab9321d2013-06-29 21:10:57 -0700394 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400395
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700396 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
397 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700398 private final static int MAX_NET_ID = 65535;
399 private int mNextNetId = MIN_NET_ID;
400
Robert Greenwalt34524f02014-05-18 16:22:10 -0700401 // sequence number of NetworkRequests
402 private int mNextNetworkRequestId = 1;
403
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700404 /**
405 * Implements support for the legacy "one network per network type" model.
406 *
407 * We used to have a static array of NetworkStateTrackers, one for each
408 * network type, but that doesn't work any more now that we can have,
409 * for example, more that one wifi network. This class stores all the
410 * NetworkAgentInfo objects that support a given type, but the legacy
411 * API will only see the first one.
412 *
413 * It serves two main purposes:
414 *
415 * 1. Provide information about "the network for a given type" (since this
416 * API only supports one).
417 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
418 * the first network for a given type changes, or if the default network
419 * changes.
420 */
421 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900422
423 private static final boolean DBG = true;
424 private static final boolean VDBG = false;
425 private static final String TAG = "CSLegacyTypeTracker";
426
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700427 /**
428 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
429 * Each list holds references to all NetworkAgentInfos that are used to
430 * satisfy requests for that network type.
431 *
432 * This array is built out at startup such that an unsupported network
433 * doesn't get an ArrayList instance, making this a tristate:
434 * unsupported, supported but not active and active.
435 *
436 * The actual lists are populated when we scan the network types that
437 * are supported on this device.
438 */
439 private ArrayList<NetworkAgentInfo> mTypeLists[];
440
441 public LegacyTypeTracker() {
442 mTypeLists = (ArrayList<NetworkAgentInfo>[])
443 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
444 }
445
446 public void addSupportedType(int type) {
447 if (mTypeLists[type] != null) {
448 throw new IllegalStateException(
449 "legacy list for type " + type + "already initialized");
450 }
451 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
452 }
453
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700454 public boolean isTypeSupported(int type) {
455 return isNetworkTypeValid(type) && mTypeLists[type] != null;
456 }
457
458 public NetworkAgentInfo getNetworkForType(int type) {
459 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
460 return mTypeLists[type].get(0);
461 } else {
462 return null;
463 }
464 }
465
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900466 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
467 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900468 if (DBG) {
469 log("Sending " + (connected ? "connected" : "disconnected") +
470 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900471 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900472 }
473 }
474
475 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700476 public void add(int type, NetworkAgentInfo nai) {
477 if (!isTypeSupported(type)) {
478 return; // Invalid network type.
479 }
480 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
481
482 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
483 if (list.contains(nai)) {
484 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
485 return;
486 }
487
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900488 list.add(nai);
489
490 // 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 +0900491 final boolean isDefaultNetwork = isDefaultNetwork(nai);
492 if (list.size() == 1 || isDefaultNetwork) {
493 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700494 sendLegacyNetworkBroadcast(nai, true, type);
495 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700496 }
497
Lorenzo Colittia793a672014-07-31 23:20:17 +0900498 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900499 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900500 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
501 if (list == null || list.isEmpty()) {
502 return;
503 }
504
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900505 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900506
507 if (!list.remove(nai)) {
508 return;
509 }
510
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900511 if (wasFirstNetwork || wasDefault) {
512 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900513 sendLegacyNetworkBroadcast(nai, false, type);
514 }
515
516 if (!list.isEmpty() && wasFirstNetwork) {
517 if (DBG) log("Other network available for type " + type +
518 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900519 final NetworkAgentInfo replacement = list.get(0);
520 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
521 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900522 }
523 }
524
525 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900526 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
527 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700528 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900529 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700530 }
531 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700532
Lorenzo Colittia793a672014-07-31 23:20:17 +0900533 private String naiToString(NetworkAgentInfo nai) {
534 String name = (nai != null) ? nai.name() : "null";
535 String state = (nai.networkInfo != null) ?
536 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
537 "???/???";
538 return name + " " + state;
539 }
540
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700541 public void dump(IndentingPrintWriter pw) {
542 for (int type = 0; type < mTypeLists.length; type++) {
543 if (mTypeLists[type] == null) continue;
544 pw.print(type + " ");
545 pw.increaseIndent();
546 if (mTypeLists[type].size() == 0) pw.println("none");
547 for (NetworkAgentInfo nai : mTypeLists[type]) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900548 pw.println(naiToString(nai));
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700549 }
550 pw.decreaseIndent();
551 }
552 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553
554 // This class needs its own log method because it has a different TAG.
555 private void log(String s) {
556 Slog.d(TAG, s);
557 }
558
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 }
560 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
561
Jeff Sharkey899223b2012-08-04 15:24:58 -0700562 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700563 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800564 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800565
Erik Klineda4bfa82015-04-30 12:58:40 +0900566 mDefaultRequest = createInternetRequestForTransport(-1);
567 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
568 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
569
570 mDefaultMobileDataRequest = createInternetRequestForTransport(
571 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700572
Wink Savillebb08caf2010-09-02 19:23:52 -0700573 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
574 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700575 mHandler = new InternalHandler(handlerThread.getLooper());
576 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700577
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800578 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800579 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
580 String id = Settings.Secure.getString(context.getContentResolver(),
581 Settings.Secure.ANDROID_ID);
582 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700583 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800584 SystemProperties.set("net.hostname", name);
585 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800586 }
587
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700588 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700589 String dns = Settings.Global.getString(context.getContentResolver(),
590 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700591 if (dns == null || dns.length() == 0) {
592 dns = context.getResources().getString(
593 com.android.internal.R.string.config_default_dns_server);
594 }
595 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800596 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
597 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800598 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700599 }
600
Jeremy Joslin79294842014-12-03 17:15:28 -0800601 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
602 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
603
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700604 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700605 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800606 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700607 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700608 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700609 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700610
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700611 try {
612 mPolicyManager.registerListener(mPolicyListener);
613 } catch (RemoteException e) {
614 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700615 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700616 }
617
618 final PowerManager powerManager = (PowerManager) context.getSystemService(
619 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700620 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
621 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
622 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800623 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700624
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700625 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700626
Wink Saville51f456f2013-04-23 14:26:51 -0700627 // TODO: What is the "correct" way to do determine if this is a wifi only device?
628 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
629 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700630 String[] naStrings = context.getResources().getStringArray(
631 com.android.internal.R.array.networkAttributes);
632 for (String naString : naStrings) {
633 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700634 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700635 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700636 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800637 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700638 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700639 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700640 }
Wink Saville51f456f2013-04-23 14:26:51 -0700641 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
642 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
643 n.type);
644 continue;
645 }
Wink Saville975c8482011-04-07 14:23:45 -0700646 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800647 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700648 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700649 continue;
650 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700651 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700652
Wink Saville975c8482011-04-07 14:23:45 -0700653 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700654 mNetworksDefined++;
655 } catch(Exception e) {
656 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700657 }
658 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700659
660 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
661 if (mNetConfigs[TYPE_VPN] == null) {
662 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
663 // don't need to add TYPE_VPN to mNetConfigs.
664 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
665 mNetworksDefined++; // used only in the log() statement below.
666 }
667
Wink Saville5e56bc52013-07-29 15:00:57 -0700668 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700669
Robert Greenwalt50393202011-06-21 17:26:14 -0700670 mProtectedNetworks = new ArrayList<Integer>();
671 int[] protectedNetworks = context.getResources().getIntArray(
672 com.android.internal.R.array.config_protectedNetworks);
673 for (int p : protectedNetworks) {
674 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
675 mProtectedNetworks.add(p);
676 } else {
677 if (DBG) loge("Ignoring protectedNetwork " + p);
678 }
679 }
680
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700681 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
682 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700683
Robert Greenwaltfab501672014-07-23 11:44:01 -0700684 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800685
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700686 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
687
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700688 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700689 IntentFilter intentFilter = new IntentFilter();
690 intentFilter.addAction(Intent.ACTION_USER_STARTING);
691 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
692 mContext.registerReceiverAsUser(
693 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900694
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700695 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700696 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700697 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700698 } catch (RemoteException e) {
699 loge("Error registering observer :" + e);
700 }
701
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700702 if (DBG) {
703 mInetLog = new ArrayList();
704 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700705
Erik Klineda4bfa82015-04-30 12:58:40 +0900706 mSettingsObserver = new SettingsObserver(mContext, mHandler);
707 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800708
John Spurlockbf991a82013-06-24 14:20:23 -0400709 mDataConnectionStats = new DataConnectionStats(mContext);
710 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400711
Jason Monkdecd2952013-10-10 14:02:51 -0400712 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700713
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400714 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800715 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700716
Erik Klineda4bfa82015-04-30 12:58:40 +0900717 private NetworkRequest createInternetRequestForTransport(int transportType) {
718 NetworkCapabilities netCap = new NetworkCapabilities();
719 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
720 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
721 if (transportType > -1) {
722 netCap.addTransportType(transportType);
723 }
724 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
725 }
726
727 private void handleMobileDataAlwaysOn() {
728 final boolean enable = (Settings.Global.getInt(
729 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
730 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
731 if (enable == isEnabled) {
732 return; // Nothing to do.
733 }
734
735 if (enable) {
736 handleRegisterNetworkRequest(new NetworkRequestInfo(
737 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
738 } else {
739 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
740 }
741 }
742
743 private void registerSettingsCallbacks() {
744 // Watch for global HTTP proxy changes.
745 mSettingsObserver.observe(
746 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
747 EVENT_APPLY_GLOBAL_HTTP_PROXY);
748
749 // Watch for whether or not to keep mobile data always on.
750 mSettingsObserver.observe(
751 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
752 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
753 }
754
Robert Greenwalt34524f02014-05-18 16:22:10 -0700755 private synchronized int nextNetworkRequestId() {
756 return mNextNetworkRequestId++;
757 }
758
Paul Jensen31a94f42015-02-13 14:18:39 -0500759 private int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400760 synchronized (mNetworkForNetId) {
761 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
762 int netId = mNextNetId;
763 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
764 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500765 if (!mNetIdInUse.get(netId)) {
766 mNetIdInUse.put(netId, true);
767 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400768 }
769 }
770 }
771 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700772 }
773
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800774 private NetworkState getFilteredNetworkState(int networkType, int uid) {
775 NetworkInfo info = null;
776 LinkProperties lp = null;
777 NetworkCapabilities nc = null;
778 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800779 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800780
781 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
782 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
783 if (nai != null) {
784 synchronized (nai) {
785 info = new NetworkInfo(nai.networkInfo);
786 lp = new LinkProperties(nai.linkProperties);
787 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400788 // Network objects are outwardly immutable so there is no point to duplicating.
789 // Duplicating also precludes sharing socket factories and connection pools.
790 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800791 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800792 }
793 info.setType(networkType);
794 } else {
795 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
796 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
797 info.setIsAvailable(true);
798 lp = new LinkProperties();
799 nc = new NetworkCapabilities();
800 network = null;
801 }
802 info = getFilteredNetworkInfo(info, lp, uid);
803 }
804
Jeff Sharkey32566012014-12-02 18:30:14 -0800805 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400806 }
807
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800808 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
809 if (network == null) {
810 return null;
811 }
812 synchronized (mNetworkForNetId) {
813 return mNetworkForNetId.get(network.netId);
814 }
815 };
816
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900817 private Network[] getVpnUnderlyingNetworks(int uid) {
818 if (!mLockdownEnabled) {
819 int user = UserHandle.getUserId(uid);
820 synchronized (mVpns) {
821 Vpn vpn = mVpns.get(user);
822 if (vpn != null && vpn.appliesToUid(uid)) {
823 return vpn.getUnderlyingNetworks();
824 }
825 }
826 }
827 return null;
828 }
829
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800830 private NetworkState getUnfilteredActiveNetworkState(int uid) {
831 NetworkInfo info = null;
832 LinkProperties lp = null;
833 NetworkCapabilities nc = null;
834 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800835 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800836
837 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800838
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900839 final Network[] networks = getVpnUnderlyingNetworks(uid);
840 if (networks != null) {
841 // getUnderlyingNetworks() returns:
842 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
843 // empty array => the VPN explicitly said "no default network".
844 // non-empty array => the VPN specified one or more default networks; we use the
845 // first one.
846 if (networks.length > 0) {
847 nai = getNetworkAgentInfoForNetwork(networks[0]);
848 } else {
849 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800850 }
851 }
852
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800853 if (nai != null) {
854 synchronized (nai) {
855 info = new NetworkInfo(nai.networkInfo);
856 lp = new LinkProperties(nai.linkProperties);
857 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400858 // Network objects are outwardly immutable so there is no point to duplicating.
859 // Duplicating also precludes sharing socket factories and connection pools.
860 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800861 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800862 }
863 }
864
Jeff Sharkey32566012014-12-02 18:30:14 -0800865 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400866 }
867
868 /**
869 * Check if UID should be blocked from using the network with the given LinkProperties.
870 */
871 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700872 final boolean networkCostly;
873 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700874
Robert Greenwalt12e67352014-05-13 21:41:06 -0700875 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700876 synchronized (mRulesLock) {
877 networkCostly = mMeteredIfaces.contains(iface);
878 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700879 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700880
Amith Yamasani15e472352015-04-24 19:06:07 -0700881 if ((uidRules & RULE_REJECT_ALL) != 0
882 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700883 return true;
884 }
885
886 // no restrictive rules; network is visible
887 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700888 }
889
890 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700891 * Return a filtered {@link NetworkInfo}, potentially marked
892 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800893 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700894 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800895 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
896 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400897 // network is blocked; clone and override state
898 info = new NetworkInfo(info);
899 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900900 if (DBG) {
901 log("returning Blocked NetworkInfo for ifname=" +
902 lp.getInterfaceName() + ", uid=" + uid);
903 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700904 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800905 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700906 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700907 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700908 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700909 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700910 }
911
912 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800913 * Return NetworkInfo for the active (i.e., connected) network interface.
914 * It is assumed that at most one network is active at a time. If more
915 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700916 * @return the info for the active network, or {@code null} if none is
917 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800918 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700919 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800920 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700921 enforceAccessPermission();
922 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800923 NetworkState state = getUnfilteredActiveNetworkState(uid);
924 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
926
Paul Jensen31a94f42015-02-13 14:18:39 -0500927 @Override
928 public Network getActiveNetwork() {
929 enforceAccessPermission();
930 final int uid = Binder.getCallingUid();
931 final int user = UserHandle.getUserId(uid);
932 int vpnNetId = NETID_UNSET;
933 synchronized (mVpns) {
934 final Vpn vpn = mVpns.get(user);
935 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
936 }
937 NetworkAgentInfo nai;
938 if (vpnNetId != NETID_UNSET) {
939 synchronized (mNetworkForNetId) {
940 nai = mNetworkForNetId.get(vpnNetId);
941 }
942 if (nai != null) return nai.network;
943 }
944 nai = getDefaultNetwork();
945 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
946 return nai != null ? nai.network : null;
947 }
948
Wink Saville948282b2013-08-29 08:55:16 -0700949 /**
950 * Find the first Provisioning network.
951 *
952 * @return NetworkInfo or null if none.
953 */
954 private NetworkInfo getProvisioningNetworkInfo() {
955 enforceAccessPermission();
956
957 // Find the first Provisioning Network
958 NetworkInfo provNi = null;
959 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700960 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700961 provNi = ni;
962 break;
963 }
964 }
965 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
966 return provNi;
967 }
968
969 /**
970 * Find the first Provisioning network or the ActiveDefaultNetwork
971 * if there is no Provisioning network
972 *
973 * @return NetworkInfo or null if none.
974 */
975 @Override
976 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
977 enforceAccessPermission();
978
979 NetworkInfo provNi = getProvisioningNetworkInfo();
980 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800981 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700982 }
983 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
984 return provNi;
985 }
986
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700987 public NetworkInfo getActiveNetworkInfoUnfiltered() {
988 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800989 final int uid = Binder.getCallingUid();
990 NetworkState state = getUnfilteredActiveNetworkState(uid);
991 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700992 }
993
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700994 @Override
995 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
996 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800997 NetworkState state = getUnfilteredActiveNetworkState(uid);
998 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700999 }
1000
1001 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001002 public NetworkInfo getNetworkInfo(int networkType) {
1003 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001004 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001005 if (getVpnUnderlyingNetworks(uid) != null) {
1006 // A VPN is active, so we may need to return one of its underlying networks. This
1007 // information is not available in LegacyTypeTracker, so we have to get it from
1008 // getUnfilteredActiveNetworkState.
1009 NetworkState state = getUnfilteredActiveNetworkState(uid);
1010 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1011 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1012 }
1013 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001014 NetworkState state = getFilteredNetworkState(networkType, uid);
1015 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001016 }
1017
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001018 @Override
1019 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1020 enforceAccessPermission();
1021 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001022 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001023 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1024 if (nai != null) {
1025 synchronized (nai) {
1026 info = new NetworkInfo(nai.networkInfo);
1027 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001028 }
1029 }
1030 return info;
1031 }
1032
1033 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001034 public NetworkInfo[] getAllNetworkInfo() {
1035 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001036 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001037 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1038 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001039 NetworkInfo info = getNetworkInfo(networkType);
1040 if (info != null) {
1041 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001042 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001043 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001044 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
1046
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001047 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001048 public Network getNetworkForType(int networkType) {
1049 enforceAccessPermission();
1050 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001051 NetworkState state = getFilteredNetworkState(networkType, uid);
1052 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1053 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001054 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001055 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001056 }
1057
1058 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001059 public Network[] getAllNetworks() {
1060 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001061 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001062 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001063 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001064 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001065 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001066 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001067 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001068 }
1069
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001070 private NetworkCapabilities getNetworkCapabilitiesAndValidation(NetworkAgentInfo nai) {
1071 if (nai != null) {
1072 synchronized (nai) {
1073 if (nai.created) {
1074 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001075 if (nai.lastValidated) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001076 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1077 } else {
1078 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1079 }
1080 return nc;
1081 }
1082 }
1083 }
1084 return null;
1085 }
1086
1087 @Override
1088 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1089 // The basic principle is: if an app's traffic could possibly go over a
1090 // network, without the app doing anything multinetwork-specific,
1091 // (hence, by "default"), then include that network's capabilities in
1092 // the array.
1093 //
1094 // In the normal case, app traffic only goes over the system's default
1095 // network connection, so that's the only network returned.
1096 //
1097 // With a VPN in force, some app traffic may go into the VPN, and thus
1098 // over whatever underlying networks the VPN specifies, while other app
1099 // traffic may go over the system default network (e.g.: a split-tunnel
1100 // VPN, or an app disallowed by the VPN), so the set of networks
1101 // returned includes the VPN's underlying networks and the system
1102 // default.
1103 enforceAccessPermission();
1104
1105 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1106
1107 NetworkAgentInfo nai = getDefaultNetwork();
1108 NetworkCapabilities nc = getNetworkCapabilitiesAndValidation(getDefaultNetwork());
1109 if (nc != null) {
1110 result.put(nai.network, nc);
1111 }
1112
1113 if (!mLockdownEnabled) {
1114 synchronized (mVpns) {
1115 Vpn vpn = mVpns.get(userId);
1116 if (vpn != null) {
1117 Network[] networks = vpn.getUnderlyingNetworks();
1118 if (networks != null) {
1119 for (Network network : networks) {
1120 nai = getNetworkAgentInfoForNetwork(network);
1121 nc = getNetworkCapabilitiesAndValidation(nai);
1122 if (nc != null) {
1123 result.put(nai.network, nc);
1124 }
1125 }
1126 }
1127 }
1128 }
1129 }
1130
1131 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1132 out = result.values().toArray(out);
1133 return out;
1134 }
1135
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001136 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001137 public boolean isNetworkSupported(int networkType) {
1138 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001139 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001140 }
1141
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001142 /**
1143 * Return LinkProperties for the active (i.e., connected) default
1144 * network interface. It is assumed that at most one default network
1145 * is active at a time. If more than one is active, it is indeterminate
1146 * which will be returned.
1147 * @return the ip properties for the active network, or {@code null} if
1148 * none is active
1149 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001150 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001151 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001152 enforceAccessPermission();
1153 final int uid = Binder.getCallingUid();
1154 NetworkState state = getUnfilteredActiveNetworkState(uid);
1155 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001156 }
1157
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001158 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001159 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001160 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001161 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1162 if (nai != null) {
1163 synchronized (nai) {
1164 return new LinkProperties(nai.linkProperties);
1165 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001166 }
1167 return null;
1168 }
1169
Robert Greenwalt12e67352014-05-13 21:41:06 -07001170 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001171 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001172 public LinkProperties getLinkProperties(Network network) {
1173 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001175 if (nai != null) {
1176 synchronized (nai) {
1177 return new LinkProperties(nai.linkProperties);
1178 }
1179 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001180 return null;
1181 }
1182
1183 @Override
1184 public NetworkCapabilities getNetworkCapabilities(Network network) {
1185 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001186 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001187 if (nai != null) {
1188 synchronized (nai) {
Sanket Padawe7094d222015-05-01 16:55:00 -07001189 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
1190 if (nai.lastValidated) {
1191 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1192 } else {
1193 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1194 }
1195 return nc;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001196 }
1197 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001198 return null;
1199 }
1200
1201 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001202 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001203 // Require internal since we're handing out IMSI details
1204 enforceConnectivityInternalPermission();
1205
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001206 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001207 for (Network network : getAllNetworks()) {
1208 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1209 if (nai != null) {
1210 synchronized (nai) {
1211 final String subscriberId = (nai.networkMisc != null)
1212 ? nai.networkMisc.subscriberId : null;
1213 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1214 nai.networkCapabilities, network, subscriberId, null));
1215 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001216 }
1217 }
1218 return result.toArray(new NetworkState[result.size()]);
1219 }
1220
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001221 @Override
1222 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1223 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001224 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001225 final long token = Binder.clearCallingIdentity();
1226 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001227 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1228 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001229 try {
1230 return mPolicyManager.getNetworkQuotaInfo(state);
1231 } catch (RemoteException e) {
1232 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001233 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001234 return null;
1235 } finally {
1236 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001237 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001238 }
1239
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001240 @Override
1241 public boolean isActiveNetworkMetered() {
1242 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001243 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001244 final long token = Binder.clearCallingIdentity();
1245 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001246 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001247 } finally {
1248 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001249 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001250 }
1251
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001252 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1253 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1254 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001255 try {
1256 return mPolicyManager.isNetworkMetered(state);
1257 } catch (RemoteException e) {
1258 }
1259 }
1260 return false;
1261 }
1262
Jeff Sharkey216c1812012-08-05 14:29:23 -07001263 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1264 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001265 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001266 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001267 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001268 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001269 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001270
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001271 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 * Ensure that a network route exists to deliver traffic to the specified
1273 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001274 * @param networkType the type of the network over which traffic to the
1275 * specified host is to be routed
1276 * @param hostAddress the IP address of the host to which the route is
1277 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 * @return {@code true} on success, {@code false} on failure
1279 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001280 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001281 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001282 if (mProtectedNetworks.contains(networkType)) {
1283 enforceConnectivityInternalPermission();
1284 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001285
Chad Brubakerc0234532014-02-14 13:24:29 -08001286 InetAddress addr;
1287 try {
1288 addr = InetAddress.getByAddress(hostAddress);
1289 } catch (UnknownHostException e) {
1290 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1291 return false;
1292 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001293
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001294 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001295 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001296 return false;
1297 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001298
1299 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1300 if (nai == null) {
1301 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1302 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1303 } else {
1304 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1305 }
1306 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001307 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001308
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001309 DetailedState netState;
1310 synchronized (nai) {
1311 netState = nai.networkInfo.getDetailedState();
1312 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001313
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001314 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001315 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001316 log("requestRouteToHostAddress on down network "
1317 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001318 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001319 }
1320 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001321 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001322
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001323 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001324 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001325 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001326 LinkProperties lp;
1327 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001328 synchronized (nai) {
1329 lp = nai.linkProperties;
1330 netId = nai.network.netId;
1331 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001332 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001333 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1334 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001335 } finally {
1336 Binder.restoreCallingIdentity(token);
1337 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001338 }
1339
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001340 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001341 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001342 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001343 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001344 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001345 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001346 if (bestRoute.getGateway().equals(addr)) {
1347 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001348 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001349 } else {
1350 // if we will connect to this through another route, add a direct route
1351 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001352 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001353 }
1354 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001355 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001356 try {
1357 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1358 } catch (Exception e) {
1359 // never crash - catch them all
1360 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001361 return false;
1362 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001363 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001364 }
1365
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001366 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1367 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001368 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001369 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001370 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001371 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001372 }
1373
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001374 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001375 // skip update when we've already applied rules
1376 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1377 if (oldRules == uidRules) return;
1378
1379 mUidRules.put(uid, uidRules);
1380 }
1381
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001382 // TODO: notify UID when it has requested targeted updates
1383 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001384
1385 @Override
1386 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001387 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001388 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001389 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001390 }
1391
1392 synchronized (mRulesLock) {
1393 mMeteredIfaces.clear();
1394 for (String iface : meteredIfaces) {
1395 mMeteredIfaces.add(iface);
1396 }
1397 }
1398 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001399
1400 @Override
1401 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1402 // caller is NPMS, since we only register with them
1403 if (LOGD_RULES) {
1404 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1405 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001406 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001407 };
1408
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001409 private void enforceInternetPermission() {
1410 mContext.enforceCallingOrSelfPermission(
1411 android.Manifest.permission.INTERNET,
1412 "ConnectivityService");
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001416 mContext.enforceCallingOrSelfPermission(
1417 android.Manifest.permission.ACCESS_NETWORK_STATE,
1418 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420
1421 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001422 mContext.enforceCallingOrSelfPermission(
1423 android.Manifest.permission.CHANGE_NETWORK_STATE,
1424 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 }
1426
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001427 private void enforceTetherAccessPermission() {
1428 mContext.enforceCallingOrSelfPermission(
1429 android.Manifest.permission.ACCESS_NETWORK_STATE,
1430 "ConnectivityService");
1431 }
1432
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001433 private void enforceConnectivityInternalPermission() {
1434 mContext.enforceCallingOrSelfPermission(
1435 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1436 "ConnectivityService");
1437 }
1438
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001439 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001440 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001441 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001442 }
1443
1444 private void sendInetConditionBroadcast(NetworkInfo info) {
1445 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1446 }
1447
Wink Saville628b0852011-08-04 15:01:58 -07001448 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001449 if (mLockdownTracker != null) {
1450 info = mLockdownTracker.augmentNetworkInfo(info);
1451 }
1452
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001453 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001454 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001455 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 if (info.isFailover()) {
1457 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1458 info.setFailover(false);
1459 }
1460 if (info.getReason() != null) {
1461 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1462 }
1463 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001464 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1465 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001467 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001468 return intent;
1469 }
1470
1471 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1472 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1473 }
1474
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001475 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001476 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1477 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1478 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001479 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001480 final long ident = Binder.clearCallingIdentity();
1481 try {
1482 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1483 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1484 } finally {
1485 Binder.restoreCallingIdentity(ident);
1486 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001487 }
1488
Mike Lockwood0f79b542009-08-14 14:18:49 -04001489 private void sendStickyBroadcast(Intent intent) {
1490 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001491 if (!mSystemReady) {
1492 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001493 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001494 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001495 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001496 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001497 }
1498
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001499 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001500 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1501 final IBatteryStats bs = BatteryStatsService.getService();
1502 try {
1503 NetworkInfo ni = intent.getParcelableExtra(
1504 ConnectivityManager.EXTRA_NETWORK_INFO);
1505 bs.noteConnectivityChanged(intent.getIntExtra(
1506 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1507 ni != null ? ni.getState().toString() : "?");
1508 } catch (RemoteException e) {
1509 }
1510 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001511 try {
1512 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1513 } finally {
1514 Binder.restoreCallingIdentity(ident);
1515 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001516 }
1517 }
1518
1519 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001520 loadGlobalProxy();
1521
Mike Lockwood0f79b542009-08-14 14:18:49 -04001522 synchronized(this) {
1523 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001524 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001525 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001526 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001527 }
1528 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001529 // load the global proxy at startup
1530 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001531
1532 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1533 // for user to unlock device.
1534 if (!updateLockdownVpn()) {
1535 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1536 mContext.registerReceiver(mUserPresentReceiver, filter);
1537 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001538
Erik Klineda4bfa82015-04-30 12:58:40 +09001539 // Configure whether mobile data is always on.
1540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1541
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001542 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001543
1544 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001547 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1548 @Override
1549 public void onReceive(Context context, Intent intent) {
1550 // Try creating lockdown tracker, since user present usually means
1551 // unlocked keystore.
1552 if (updateLockdownVpn()) {
1553 mContext.unregisterReceiver(this);
1554 }
1555 }
1556 };
1557
Wink Savilled747cbc2013-08-07 16:22:47 -07001558 /** @hide */
1559 @Override
1560 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1561 enforceConnectivityInternalPermission();
1562 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001563// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001564 }
1565
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001566 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001567 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001568 *
1569 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001570 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001571 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001572 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1573 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001574
1575 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001576 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001577
Robert Greenwalt7b816022014-04-18 15:25:25 -07001578 if (networkAgent.networkCapabilities.hasTransport(
1579 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001580 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1581 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001582 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001583 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001584 } else if (networkAgent.networkCapabilities.hasTransport(
1585 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001586 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1587 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001588 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001589 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001590 } else {
1591 // do not track any other networks
1592 timeout = 0;
1593 }
1594
Robert Greenwalt7b816022014-04-18 15:25:25 -07001595 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001596 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001597 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001598 } catch (Exception e) {
1599 // You shall not crash!
1600 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001601 }
1602 }
1603 }
1604
1605 /**
1606 * Remove data activity tracking when network disconnects.
1607 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001608 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1609 final String iface = networkAgent.linkProperties.getInterfaceName();
1610 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001611
Robert Greenwalt7b816022014-04-18 15:25:25 -07001612 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1613 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001614 try {
1615 // the call fails silently if no idletimer setup for this interface
1616 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001617 } catch (Exception e) {
1618 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001619 }
1620 }
1621 }
1622
1623 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001624 * Reads the network specific MTU size from reources.
1625 * and set it on it's iface.
1626 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001627 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1628 final String iface = newLp.getInterfaceName();
1629 final int mtu = newLp.getMtu();
1630 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1631 if (VDBG) log("identical MTU - not setting");
1632 return;
1633 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001634
Robert Greenwalt43074032014-08-15 17:53:05 -07001635 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001636 loge("Unexpected mtu value: " + mtu + ", " + iface);
1637 return;
1638 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001639
w1997615afd812014-08-05 15:18:11 -07001640 // Cannot set MTU without interface name
1641 if (TextUtils.isEmpty(iface)) {
1642 loge("Setting MTU size with null iface.");
1643 return;
1644 }
1645
Robert Greenwalt7b816022014-04-18 15:25:25 -07001646 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001647 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001648 mNetd.setMtu(iface, mtu);
1649 } catch (Exception e) {
1650 Slog.e(TAG, "exception in setMtu()" + e);
1651 }
1652 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001653
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001654 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001655
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001656 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1657 if (isDefaultNetwork(nai) == false) {
1658 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001659 }
1660
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001661 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1662 String[] values = null;
1663 if (tcpBufferSizes != null) {
1664 values = tcpBufferSizes.split(",");
1665 }
1666
1667 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001668 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001669 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1670 values = tcpBufferSizes.split(",");
1671 }
1672
1673 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1674
1675 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001676 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001677
1678 final String prefix = "/sys/kernel/ipv4/tcp_";
1679 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1680 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1681 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1682 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1683 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1684 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1685 mCurrentTcpBufferSizes = tcpBufferSizes;
1686 } catch (IOException e) {
1687 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001688 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001689
1690 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1691 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1692 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1693 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1694 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1695 if (rwndValue != 0) {
1696 SystemProperties.set(sysctlKey, rwndValue.toString());
1697 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001698 }
1699
Mattias Falk8b47b362011-08-23 14:15:13 +02001700 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001701 /*
1702 * Tell the VMs to toss their DNS caches
1703 */
1704 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1705 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001706 /*
1707 * Connectivity events can happen before boot has completed ...
1708 */
1709 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001710 final long ident = Binder.clearCallingIdentity();
1711 try {
1712 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1713 } finally {
1714 Binder.restoreCallingIdentity(ident);
1715 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001716 }
1717
Robert Greenwalt562cc542014-05-15 18:07:26 -07001718 @Override
1719 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001720 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1721 NETWORK_RESTORE_DELAY_PROP_NAME);
1722 if(restoreDefaultNetworkDelayStr != null &&
1723 restoreDefaultNetworkDelayStr.length() != 0) {
1724 try {
1725 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1726 } catch (NumberFormatException e) {
1727 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001728 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001729 // if the system property isn't set, use the value for the apn type
1730 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1731
1732 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1733 (mNetConfigs[networkType] != null)) {
1734 ret = mNetConfigs[networkType].restoreTime;
1735 }
1736 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001737 }
1738
1739 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001740 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1741 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001742 if (mContext.checkCallingOrSelfPermission(
1743 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001745 pw.println("Permission Denial: can't dump ConnectivityService " +
1746 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1747 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 return;
1749 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001750
Robert Greenwalta67be032014-05-16 15:49:14 -07001751 pw.println("NetworkFactories for:");
1752 pw.increaseIndent();
1753 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1754 pw.println(nfi.name);
1755 }
1756 pw.decreaseIndent();
1757 pw.println();
1758
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001759 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1760 pw.print("Active default network: ");
1761 if (defaultNai == null) {
1762 pw.println("none");
1763 } else {
1764 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001765 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001766 pw.println();
1767
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001768 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001769 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001770 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1771 pw.println(nai.toString());
1772 pw.increaseIndent();
1773 pw.println("Requests:");
1774 pw.increaseIndent();
1775 for (int i = 0; i < nai.networkRequests.size(); i++) {
1776 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001777 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001778 pw.decreaseIndent();
1779 pw.println("Lingered:");
1780 pw.increaseIndent();
1781 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1782 pw.decreaseIndent();
1783 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001784 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001785 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001786 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001787
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001788 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001789 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001790 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1791 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001792 }
1793 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001794 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001795
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001796 pw.println("mLegacyTypeTracker:");
1797 pw.increaseIndent();
1798 mLegacyTypeTracker.dump(pw);
1799 pw.decreaseIndent();
1800 pw.println();
1801
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001802 synchronized (this) {
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001803 pw.println("NetworkTransitionWakeLock is currently " +
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001804 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1805 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1806 }
1807 pw.println();
1808
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001809 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001810
1811 if (mInetLog != null) {
1812 pw.println();
1813 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001814 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001815 for(int i = 0; i < mInetLog.size(); i++) {
1816 pw.println(mInetLog.get(i));
1817 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001818 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001819 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001820 }
1821
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001822 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001823 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001824 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001825 if (officialNai != null && officialNai.equals(nai)) return true;
1826 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001827 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001828 " - " + nai);
1829 }
1830 return false;
1831 }
1832
Paul Jensenc8b9a742014-09-30 15:37:41 -04001833 private boolean isRequest(NetworkRequest request) {
1834 return mNetworkRequests.get(request).isRequest;
1835 }
1836
Robert Greenwalt42acef32009-08-12 16:08:25 -07001837 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001838 private class NetworkStateTrackerHandler extends Handler {
1839 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001840 super(looper);
1841 }
1842
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001843 @Override
1844 public void handleMessage(Message msg) {
1845 NetworkInfo info;
1846 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001847 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001848 handleAsyncChannelHalfConnect(msg);
1849 break;
1850 }
1851 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1852 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1853 if (nai != null) nai.asyncChannel.disconnect();
1854 break;
1855 }
1856 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1857 handleAsyncChannelDisconnected(msg);
1858 break;
1859 }
1860 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1861 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1862 if (nai == null) {
1863 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1864 } else {
1865 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001866 }
1867 break;
1868 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001869 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1870 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1871 if (nai == null) {
1872 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1873 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001874 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001875 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001876 "; created=" + nai.created);
1877 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001878 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001879 synchronized (nai) {
1880 nai.linkProperties = (LinkProperties)msg.obj;
1881 }
Paul Jenseneec75412014-08-04 12:21:19 -04001882 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001883 }
1884 break;
1885 }
1886 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1887 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1888 if (nai == null) {
1889 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1890 break;
1891 }
1892 info = (NetworkInfo) msg.obj;
1893 updateNetworkInfo(nai, info);
1894 break;
1895 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001896 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1897 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1898 if (nai == null) {
1899 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1900 break;
1901 }
1902 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001903 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001904 break;
1905 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001906 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1907 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1908 if (nai == null) {
1909 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1910 break;
1911 }
1912 try {
1913 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001914 } catch (Exception e) {
1915 // Never crash!
1916 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001917 }
1918 break;
1919 }
1920 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1921 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1922 if (nai == null) {
1923 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1924 break;
1925 }
1926 try {
1927 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001928 } catch (Exception e) {
1929 // Never crash!
1930 loge("Exception in removeVpnUidRanges: " + e);
1931 }
1932 break;
1933 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001934 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1935 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1936 if (nai == null) {
1937 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1938 break;
1939 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001940 if (nai.created && !nai.networkMisc.explicitlySelected) {
1941 loge("ERROR: created network explicitly selected.");
1942 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001943 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001944 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001945 break;
1946 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001947 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001948 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001949 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001950 boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001951 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001952 if (valid) {
1953 if (DBG) log("Validated " + nai.name());
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001954 if (!nai.everValidated) {
1955 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001956 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1957 ReapUnvalidatedNetworks.REAP);
1958 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001959 sendUpdatedScoreToFactories(nai);
1960 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001961 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001962 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001963 // Let the NetworkAgent know the state of its network
1964 nai.asyncChannel.sendMessage(
1965 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1966 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1967 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001968
1969 // TODO: trigger a NetworkCapabilities update so that the dialog can know
1970 // that the network is now validated and close itself.
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001971 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001972 break;
1973 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001974 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001975 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001976 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1977 handleLingerComplete(nai);
1978 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001979 break;
1980 }
Paul Jensen869868be2014-05-15 10:33:05 -04001981 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001982 if (msg.arg1 == 0) {
1983 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1984 } else {
Lorenzo Colittid49159f2015-05-14 23:15:10 +09001985 final NetworkAgentInfo nai;
Paul Jensen5df4bec2014-08-25 22:45:39 -04001986 synchronized (mNetworkForNetId) {
1987 nai = mNetworkForNetId.get(msg.arg2);
1988 }
1989 if (nai == null) {
1990 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1991 break;
1992 }
Lorenzo Colittid49159f2015-05-14 23:15:10 +09001993 nai.captivePortalDetected = true;
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001994 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
1995 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04001996 }
Paul Jensen869868be2014-05-15 10:33:05 -04001997 break;
1998 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001999 }
2000 }
2001 }
2002
Paul Jensen0cc17322014-11-25 15:26:53 -05002003 // Cancel any lingering so the linger timeout doesn't teardown a network.
2004 // This should be called when a network begins satisfying a NetworkRequest.
2005 // Note: depending on what state the NetworkMonitor is in (e.g.,
2006 // if it's awaiting captive portal login, or if validation failed), this
2007 // may trigger a re-evaluation of the network.
2008 private void unlinger(NetworkAgentInfo nai) {
2009 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002010 // If network has never been validated, it cannot have been lingered, so don't bother
2011 // needlessly triggering a re-evaluation.
2012 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002013 nai.networkLingered.clear();
2014 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2015 }
2016
Robert Greenwalt7b816022014-04-18 15:25:25 -07002017 private void handleAsyncChannelHalfConnect(Message msg) {
2018 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002019 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002020 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2021 if (VDBG) log("NetworkFactory connected");
2022 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002023 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002024 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002025 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002026 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002027 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002028 }
2029 } else {
2030 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002031 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002032 }
2033 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2034 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2035 if (VDBG) log("NetworkAgent connected");
2036 // A network agent has requested a connection. Establish the connection.
2037 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2038 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2039 } else {
2040 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002041 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002042 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002043 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002044 synchronized (mNetworkForNetId) {
2045 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002046 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002047 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002048 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002049 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002050 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002051 }
2052 }
2053 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002054
Robert Greenwalt7b816022014-04-18 15:25:25 -07002055 private void handleAsyncChannelDisconnected(Message msg) {
2056 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2057 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002058 if (DBG) {
2059 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2060 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002061 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002062 if (nai.created) {
2063 // Tell netd to clean up the configuration for this network
2064 // (routing rules, DNS, etc).
2065 try {
2066 mNetd.removeNetwork(nai.network.netId);
2067 } catch (Exception e) {
2068 loge("Exception removing network: " + e);
2069 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002070 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002071 // TODO - if we move the logic to the network agent (have them disconnect
2072 // because they lost all their requests or because their score isn't good)
2073 // then they would disconnect organically, report their new state and then
2074 // disconnect the channel.
2075 if (nai.networkInfo.isConnected()) {
2076 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2077 null, null);
2078 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002079 final boolean wasDefault = isDefaultNetwork(nai);
2080 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002081 mDefaultInetConditionPublished = 0;
2082 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002083 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002084 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002085 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002086 mNetworkAgentInfos.remove(msg.replyTo);
2087 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002088 synchronized (mNetworkForNetId) {
2089 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002090 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002091 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002092 // Since we've lost the network, go through all the requests that
2093 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002094 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002095 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002096 for (int i = 0; i < nai.networkRequests.size(); i++) {
2097 NetworkRequest request = nai.networkRequests.valueAt(i);
2098 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2099 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002100 if (DBG) {
2101 log("Checking for replacement network to handle request " + request );
2102 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002103 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002104 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002105 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002106 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2107 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002108 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002109 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002110 alternative = existing;
2111 }
2112 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002113 if (alternative != null) {
2114 if (DBG) log(" found replacement in " + alternative.name());
2115 if (!toActivate.contains(alternative)) {
2116 toActivate.add(alternative);
2117 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002118 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002119 }
2120 }
2121 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2122 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002123 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002124 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002125 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002126 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002127 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002128 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002129 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2130 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002131 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302133 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2134 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002135 }
2136
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002137 // If this method proves to be too slow then we can maintain a separate
2138 // pendingIntent => NetworkRequestInfo map.
2139 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2140 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2141 Intent intent = pendingIntent.getIntent();
2142 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2143 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2144 if (existingPendingIntent != null &&
2145 existingPendingIntent.getIntent().filterEquals(intent)) {
2146 return entry.getValue();
2147 }
2148 }
2149 return null;
2150 }
2151
2152 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2153 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2154
2155 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2156 if (existingRequest != null) { // remove the existing request.
2157 if (DBG) log("Replacing " + existingRequest.request + " with "
2158 + nri.request + " because their intents matched.");
2159 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2160 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002161 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002162 }
2163
Erik Klineda4bfa82015-04-30 12:58:40 +09002164 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002165 mNetworkRequests.put(nri.request, nri);
2166
Paul Jensen0cc17322014-11-25 15:26:53 -05002167 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2168
Robert Greenwalt9258c642014-03-26 16:47:06 -07002169 // Check for the best currently alive network that satisfies this request
2170 NetworkAgentInfo bestNetwork = null;
2171 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002172 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002173 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002174 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002175 if (!nri.isRequest) {
2176 // Not setting bestNetwork here as a listening NetworkRequest may be
2177 // satisfied by multiple Networks. Instead the request is added to
2178 // each satisfying Network and notified about each.
2179 network.addRequest(nri.request);
2180 notifyNetworkCallback(network, nri);
2181 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002182 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002183 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002184 }
2185 }
2186 }
2187 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002188 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002189 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002190 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002191 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002192 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002193 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002194 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2195 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002196 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002197
Lorenzo Colittia793a672014-07-31 23:20:17 +09002198 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002199 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002200 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002201 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002202 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002203 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002204 }
2205 }
2206 }
2207
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002208 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2209 int callingUid) {
2210 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2211 if (nri != null) {
2212 handleReleaseNetworkRequest(nri.request, callingUid);
2213 }
2214 }
2215
Paul Jensen99364842014-12-09 11:43:45 -05002216 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2217 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2218 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2219 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2220 private boolean unneeded(NetworkAgentInfo nai) {
2221 if (!nai.created || nai.isVPN()) return false;
2222 boolean unneeded = true;
2223 if (nai.everValidated) {
2224 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2225 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2226 try {
2227 if (isRequest(nr)) unneeded = false;
2228 } catch (Exception e) {
2229 loge("Request " + nr + " not found in mNetworkRequests.");
2230 loge(" it came from request list of " + nai.name());
2231 }
2232 }
2233 } else {
2234 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2235 // If this Network is already the highest scoring Network for a request, or if
2236 // there is hope for it to become one if it validated, then it is needed.
2237 if (nri.isRequest && nai.satisfies(nri.request) &&
2238 (nai.networkRequests.get(nri.request.requestId) != null ||
2239 // Note that this catches two important cases:
2240 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2241 // is currently satisfying the request. This is desirable when
2242 // cellular ends up validating but WiFi does not.
2243 // 2. Unvalidated WiFi will not be reaped when validated cellular
2244 // is currently satsifying the request. This is desirable when
2245 // WiFi ends up validating and out scoring cellular.
2246 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2247 nai.getCurrentScoreAsValidated())) {
2248 unneeded = false;
2249 break;
2250 }
2251 }
2252 }
2253 return unneeded;
2254 }
2255
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002256 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2257 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002258 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002259 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002260 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2261 return;
2262 }
2263 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002264 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002265 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002266 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002267 // Find all networks that are satisfying this request and remove the request
2268 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002269 // TODO - it's my understanding that for a request there is only a single
2270 // network satisfying it, so this loop is wasteful
2271 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002272 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2273 if (nai.networkRequests.get(nri.request.requestId) != null) {
2274 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002275 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002276 log(" Removing from current network " + nai.name() +
2277 ", leaving " + nai.networkRequests.size() +
2278 " requests.");
2279 }
Paul Jensen99364842014-12-09 11:43:45 -05002280 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002281 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002282 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002283 } else {
2284 // suspect there should only be one pass through here
2285 // but if any were kept do the check below
2286 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002287 }
2288 }
2289 }
2290
Robert Greenwalt51481852015-01-08 14:43:31 -08002291 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2292 if (nai != null) {
2293 mNetworkForRequestId.remove(nri.request.requestId);
2294 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002295 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002296 // that a network connected to serve it, even though the network was already
2297 // connected. Now that this request has gone away, we might have to pretend
2298 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002299 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002300 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2301 boolean doRemove = true;
2302 if (wasKept) {
2303 // check if any of the remaining requests for this network are for the
2304 // same legacy type - if so, don't remove the nai
2305 for (int i = 0; i < nai.networkRequests.size(); i++) {
2306 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2307 if (otherRequest.legacyType == nri.request.legacyType &&
2308 isRequest(otherRequest)) {
2309 if (DBG) log(" still have other legacy request - leaving");
2310 doRemove = false;
2311 }
2312 }
2313 }
2314
2315 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002316 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002317 }
2318 }
2319
Robert Greenwalta67be032014-05-16 15:49:14 -07002320 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002321 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2322 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002323 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002324 } else {
2325 // listens don't have a singular affectedNetwork. Check all networks to see
2326 // if this listen request applies and remove it.
2327 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2328 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002329 }
2330 }
2331 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2332 }
2333 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002334
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002335 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2336 enforceConnectivityInternalPermission();
2337 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2338 accept ? 1 : 0, always ? 1: 0, network));
2339 }
2340
2341 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2342 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2343 " accept=" + accept + " always=" + always);
2344
2345 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2346 if (nai == null) {
2347 // Nothing to do.
2348 return;
2349 }
2350
2351 if (nai.everValidated) {
2352 // The network validated while the dialog box was up. Don't make any changes. There's a
2353 // TODO in the dialog code to make it go away if the network validates; once that's
2354 // implemented, taking action here will be confusing.
2355 return;
2356 }
2357
2358 if (!nai.networkMisc.explicitlySelected) {
2359 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2360 }
2361
2362 if (accept != nai.networkMisc.acceptUnvalidated) {
2363 int oldScore = nai.getCurrentScore();
2364 nai.networkMisc.acceptUnvalidated = accept;
2365 rematchAllNetworksAndRequests(nai, oldScore);
2366 sendUpdatedScoreToFactories(nai);
2367 }
2368
2369 if (always) {
2370 nai.asyncChannel.sendMessage(
2371 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2372 }
2373
2374 // TODO: should we also disconnect from the network if accept is false?
2375 }
2376
2377 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2378 mHandler.sendMessageDelayed(
2379 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2380 PROMPT_UNVALIDATED_DELAY_MS);
2381 }
2382
2383 private void handlePromptUnvalidated(Network network) {
2384 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2385
2386 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2387 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002388 // Also don't prompt on captive portals because we're already prompting the user to sign in.
2389 if (nai == null || nai.everValidated || nai.captivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002390 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2391 return;
2392 }
2393
2394 // TODO: What should we do if we've already switched to this network because we had no
2395 // better option? There are two obvious alternatives.
2396 //
2397 // 1. Decide that there's no point prompting because this is our only usable network.
2398 // However, because we didn't prompt, if later on a validated network comes along, we'll
2399 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2400 // unvalidated network - or b) prompt the user at that later time - bad because the user
2401 // might not understand why they are now being prompted.
2402 //
2403 // 2. Always prompt the user, even if we have no other network to use. The user could then
2404 // try to find an alternative network to join (remember, if we got here, then the user
2405 // selected this network manually). This is bad because the prompt isn't really very
2406 // useful.
2407 //
2408 // For now we do #1, but we can revisit that later.
2409 if (isDefaultNetwork(nai)) {
2410 return;
2411 }
2412
2413 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2414 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2415 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2416 intent.setClassName("com.android.settings",
2417 "com.android.settings.wifi.WifiNoInternetDialog");
2418 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2419 }
2420
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002421 private class InternalHandler extends Handler {
2422 public InternalHandler(Looper looper) {
2423 super(looper);
2424 }
2425
2426 @Override
2427 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002428 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002429 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002430 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002431 String causedBy = null;
2432 synchronized (ConnectivityService.this) {
2433 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2434 mNetTransitionWakeLock.isHeld()) {
2435 mNetTransitionWakeLock.release();
2436 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002437 } else {
2438 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002439 }
2440 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002441 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2442 log("Failed to find a new network - expiring NetTransition Wakelock");
2443 } else {
2444 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2445 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002446 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002447 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002448 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002449 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002450 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002451 break;
2452 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002453 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002454 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002455 sendStickyBroadcast(intent);
2456 break;
2457 }
Jason Monkdecd2952013-10-10 14:02:51 -04002458 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002459 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002460 break;
2461 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002462 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002463 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2464 break;
2465 }
2466 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2467 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002468 break;
2469 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002470 case EVENT_REGISTER_NETWORK_AGENT: {
2471 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2472 break;
2473 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002474 case EVENT_REGISTER_NETWORK_REQUEST:
2475 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002476 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002477 break;
2478 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002479 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2480 handleRegisterNetworkRequestWithIntent(msg);
2481 break;
2482 }
2483 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2484 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2485 break;
2486 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002487 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002488 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002489 break;
2490 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002491 case EVENT_SET_ACCEPT_UNVALIDATED: {
2492 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2493 break;
2494 }
2495 case EVENT_PROMPT_UNVALIDATED: {
2496 handlePromptUnvalidated((Network) msg.obj);
2497 break;
2498 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002499 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2500 handleMobileDataAlwaysOn();
2501 break;
2502 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002503 case EVENT_SYSTEM_READY: {
2504 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2505 nai.networkMonitor.systemReady = true;
2506 }
2507 break;
2508 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002509 }
2510 }
2511 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002512
2513 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002514 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002515 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002516 if (isTetheringSupported()) {
2517 return mTethering.tether(iface);
2518 } else {
2519 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2520 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002521 }
2522
2523 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002524 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002525 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002526
2527 if (isTetheringSupported()) {
2528 return mTethering.untether(iface);
2529 } else {
2530 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2531 }
2532 }
2533
2534 // javadoc from interface
2535 public int getLastTetherError(String iface) {
2536 enforceTetherAccessPermission();
2537
2538 if (isTetheringSupported()) {
2539 return mTethering.getLastTetherError(iface);
2540 } else {
2541 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2542 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002543 }
2544
2545 // TODO - proper iface API for selection by property, inspection, etc
2546 public String[] getTetherableUsbRegexs() {
2547 enforceTetherAccessPermission();
2548 if (isTetheringSupported()) {
2549 return mTethering.getTetherableUsbRegexs();
2550 } else {
2551 return new String[0];
2552 }
2553 }
2554
2555 public String[] getTetherableWifiRegexs() {
2556 enforceTetherAccessPermission();
2557 if (isTetheringSupported()) {
2558 return mTethering.getTetherableWifiRegexs();
2559 } else {
2560 return new String[0];
2561 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002562 }
2563
Danica Chang6fdd0c62010-08-11 14:54:43 -07002564 public String[] getTetherableBluetoothRegexs() {
2565 enforceTetherAccessPermission();
2566 if (isTetheringSupported()) {
2567 return mTethering.getTetherableBluetoothRegexs();
2568 } else {
2569 return new String[0];
2570 }
2571 }
2572
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002573 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002574 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002575 if (isTetheringSupported()) {
2576 return mTethering.setUsbTethering(enable);
2577 } else {
2578 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2579 }
2580 }
2581
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002582 // TODO - move iface listing, queries, etc to new module
2583 // javadoc from interface
2584 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002585 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002586 return mTethering.getTetherableIfaces();
2587 }
2588
2589 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002590 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002591 return mTethering.getTetheredIfaces();
2592 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002593
Robert Greenwalt5a735062010-03-02 17:25:02 -08002594 public String[] getTetheringErroredIfaces() {
2595 enforceTetherAccessPermission();
2596 return mTethering.getErroredIfaces();
2597 }
2598
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002599 public String[] getTetheredDhcpRanges() {
2600 enforceConnectivityInternalPermission();
2601 return mTethering.getTetheredDhcpRanges();
2602 }
2603
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002604 // if ro.tether.denied = true we default to no tethering
2605 // gservices could set the secure setting to 1 though to enable it on a build where it
2606 // had previously been turned off.
2607 public boolean isTetheringSupported() {
2608 enforceTetherAccessPermission();
2609 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002610 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002611 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2612 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002613 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2614 mTethering.getTetherableWifiRegexs().length != 0 ||
2615 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2616 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002617 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002618
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002619 // Called when we lose the default network and have no replacement yet.
2620 // This will automatically be cleared after X seconds or a new default network
2621 // becomes CONNECTED, whichever happens first. The timer is started by the
2622 // first caller and not restarted by subsequent callers.
2623 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002624 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002625 synchronized (this) {
2626 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002627 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002628 mNetTransitionWakeLock.acquire();
2629 mNetTransitionWakeLockCausedBy = forWhom;
2630 }
2631 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002632 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002633 mNetTransitionWakeLockTimeout);
2634 return;
2635 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002636
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002637 // 100 percent is full good, 0 is full bad.
2638 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002639 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002640 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002641 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002642 }
2643
Paul Jensenbfd17b72015-04-07 12:43:13 -04002644 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002645 enforceAccessPermission();
2646 enforceInternetPermission();
2647
Paul Jensenbfd17b72015-04-07 12:43:13 -04002648 NetworkAgentInfo nai;
2649 if (network == null) {
2650 nai = getDefaultNetwork();
2651 } else {
2652 nai = getNetworkAgentInfoForNetwork(network);
2653 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002654 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002655 // Revalidate if the app report does not match our current validated state.
2656 if (hasConnectivity == nai.lastValidated) return;
2657 final int uid = Binder.getCallingUid();
2658 if (DBG) {
2659 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2660 ") by " + uid);
2661 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002662 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002663 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2664 // which isn't meant to work on uncreated networks.
2665 if (!nai.created) return;
2666
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002667 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002668
2669 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2670 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002671 }
2672
Paul Jensen25a217c2015-02-27 22:55:47 -05002673 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2674 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2675 enforceConnectivityInternalPermission();
2676 }
2677 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2678 if (nai == null) return;
2679 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2680 actionToken);
2681 }
2682
Paul Jensene0bef712014-12-10 15:12:18 -05002683 public ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002684 // this information is already available as a world read/writable jvm property
2685 // so this API change wouldn't have a benifit. It also breaks the passing
2686 // of proxy info to all the JVMs.
2687 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002688 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002689 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002690 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2691 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002692 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002693 }
2694
Paul Jensene0bef712014-12-10 15:12:18 -05002695 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2696 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2697 // proxy is null then there is no proxy in place).
2698 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2699 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2700 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2701 proxy = null;
2702 }
2703 return proxy;
2704 }
2705
2706 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2707 // better for determining if a new proxy broadcast is necessary:
2708 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2709 // avoid unnecessary broadcasts.
2710 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2711 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2712 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2713 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2714 // all set.
2715 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2716 a = canonicalizeProxyInfo(a);
2717 b = canonicalizeProxyInfo(b);
2718 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2719 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2720 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2721 }
2722
Jason Monk207900c2014-04-25 15:00:09 -04002723 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002724 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002725
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002726 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002727 if (proxyProperties == mGlobalProxy) return;
2728 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2729 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2730
2731 String host = "";
2732 int port = 0;
2733 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002734 String pacFileUrl = "";
2735 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002736 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002737 if (!proxyProperties.isValid()) {
2738 if (DBG)
2739 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2740 return;
2741 }
Jason Monk207900c2014-04-25 15:00:09 -04002742 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002743 host = mGlobalProxy.getHost();
2744 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002745 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002746 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002747 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002748 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002749 } else {
2750 mGlobalProxy = null;
2751 }
2752 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002753 final long token = Binder.clearCallingIdentity();
2754 try {
2755 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2756 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2757 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2758 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002759 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002760 } finally {
2761 Binder.restoreCallingIdentity(token);
2762 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002763
Jason Monkcf0f97a2014-10-02 15:39:38 -04002764 if (mGlobalProxy == null) {
2765 proxyProperties = mDefaultProxy;
2766 }
2767 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002768 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002769 }
2770
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002771 private void loadGlobalProxy() {
2772 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002773 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2774 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2775 String exclList = Settings.Global.getString(res,
2776 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002777 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2778 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002779 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002780 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002781 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002782 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002783 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002784 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002785 if (!proxyProperties.isValid()) {
2786 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2787 return;
2788 }
2789
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002790 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002791 mGlobalProxy = proxyProperties;
2792 }
2793 }
2794 }
2795
Jason Monk207900c2014-04-25 15:00:09 -04002796 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002797 // this information is already available as a world read/writable jvm property
2798 // so this API change wouldn't have a benifit. It also breaks the passing
2799 // of proxy info to all the JVMs.
2800 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002801 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002802 return mGlobalProxy;
2803 }
2804 }
2805
Jason Monk207900c2014-04-25 15:00:09 -04002806 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002807 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002808 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002809 proxy = null;
2810 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002811 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002812 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002813 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002814 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002815 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2816 return;
2817 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002818
2819 // This call could be coming from the PacManager, containing the port of the local
2820 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2821 // global (to get the correct local port), and send a broadcast.
2822 // TODO: Switch PacManager to have its own message to send back rather than
2823 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002824 if ((mGlobalProxy != null) && (proxy != null)
2825 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002826 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2827 mGlobalProxy = proxy;
2828 sendProxyBroadcast(mGlobalProxy);
2829 return;
2830 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002831 mDefaultProxy = proxy;
2832
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002833 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002834 if (!mDefaultProxyDisabled) {
2835 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002836 }
2837 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002838 }
2839
Paul Jensene0bef712014-12-10 15:12:18 -05002840 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2841 // This method gets called when any network changes proxy, but the broadcast only ever contains
2842 // the default proxy (even if it hasn't changed).
2843 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2844 // world where an app might be bound to a non-default network.
2845 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2846 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2847 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2848
2849 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2850 sendProxyBroadcast(getDefaultProxy());
2851 }
2852 }
2853
Robert Greenwalt434203a2010-10-11 16:00:27 -07002854 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002855 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2856 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002857 if (!TextUtils.isEmpty(proxy)) {
2858 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002859 if (data.length == 0) {
2860 return;
2861 }
2862
Robert Greenwalt434203a2010-10-11 16:00:27 -07002863 String proxyHost = data[0];
2864 int proxyPort = 8080;
2865 if (data.length > 1) {
2866 try {
2867 proxyPort = Integer.parseInt(data[1]);
2868 } catch (NumberFormatException e) {
2869 return;
2870 }
2871 }
Jason Monk207900c2014-04-25 15:00:09 -04002872 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002873 setGlobalProxy(p);
2874 }
2875 }
2876
Jason Monk207900c2014-04-25 15:00:09 -04002877 private void sendProxyBroadcast(ProxyInfo proxy) {
2878 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002879 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002880 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002881 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002882 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2883 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002884 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002885 final long ident = Binder.clearCallingIdentity();
2886 try {
2887 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2888 } finally {
2889 Binder.restoreCallingIdentity(ident);
2890 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002891 }
2892
2893 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002894 final private HashMap<Uri, Integer> mUriEventMap;
2895 final private Context mContext;
2896 final private Handler mHandler;
2897
2898 SettingsObserver(Context context, Handler handler) {
2899 super(null);
2900 mUriEventMap = new HashMap<Uri, Integer>();
2901 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002902 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002903 }
2904
Erik Klineda4bfa82015-04-30 12:58:40 +09002905 void observe(Uri uri, int what) {
2906 mUriEventMap.put(uri, what);
2907 final ContentResolver resolver = mContext.getContentResolver();
2908 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002909 }
2910
2911 @Override
2912 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002913 Slog.wtf(TAG, "Should never be reached.");
2914 }
2915
2916 @Override
2917 public void onChange(boolean selfChange, Uri uri) {
2918 final Integer what = mUriEventMap.get(uri);
2919 if (what != null) {
2920 mHandler.obtainMessage(what.intValue()).sendToTarget();
2921 } else {
2922 loge("No matching event to send for URI=" + uri);
2923 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002924 }
2925 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002926
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002927 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002928 Slog.d(TAG, s);
2929 }
2930
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002931 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002932 Slog.e(TAG, s);
2933 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002934
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002935 private static <T> T checkNotNull(T value, String message) {
2936 if (value == null) {
2937 throw new NullPointerException(message);
2938 }
2939 return value;
2940 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002941
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002942 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002943 * Prepare for a VPN application.
Jeff Davidson9a1da682014-11-11 13:52:58 -08002944 * Permissions are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002945 * @hide
2946 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002947 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002948 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002949 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002950 int user = UserHandle.getUserId(Binder.getCallingUid());
2951 synchronized(mVpns) {
2952 return mVpns.get(user).prepare(oldPackage, newPackage);
2953 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002954 }
2955
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002956 /**
Jeff Davidson05542602014-08-11 14:07:27 -07002957 * Set whether the current VPN package has the ability to launch VPNs without
Jeff Davidson9a1da682014-11-11 13:52:58 -08002958 * user intervention. This method is used by system-privileged apps.
2959 * Permissions are checked in Vpn class.
Jeff Davidson05542602014-08-11 14:07:27 -07002960 * @hide
2961 */
2962 @Override
2963 public void setVpnPackageAuthorization(boolean authorized) {
2964 int user = UserHandle.getUserId(Binder.getCallingUid());
2965 synchronized(mVpns) {
2966 mVpns.get(user).setPackageAuthorization(authorized);
2967 }
2968 }
2969
2970 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002971 * Configure a TUN interface and return its file descriptor. Parameters
2972 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002973 * and not available in ConnectivityManager. Permissions are checked in
2974 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002975 * @hide
2976 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002977 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002978 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002979 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002980 int user = UserHandle.getUserId(Binder.getCallingUid());
2981 synchronized(mVpns) {
2982 return mVpns.get(user).establish(config);
2983 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002984 }
2985
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002986 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07002987 * Start legacy VPN, controlling native daemons as needed. Creates a
2988 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002989 */
2990 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07002991 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002992 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07002993 final LinkProperties egress = getActiveLinkProperties();
2994 if (egress == null) {
2995 throw new IllegalStateException("Missing active network connection");
2996 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002997 int user = UserHandle.getUserId(Binder.getCallingUid());
2998 synchronized(mVpns) {
2999 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3000 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003001 }
3002
3003 /**
3004 * Return the information of the ongoing legacy VPN. This method is used
3005 * by VpnSettings and not available in ConnectivityManager. Permissions
3006 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003007 */
3008 @Override
3009 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003010 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003011 int user = UserHandle.getUserId(Binder.getCallingUid());
3012 synchronized(mVpns) {
3013 return mVpns.get(user).getLegacyVpnInfo();
3014 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003015 }
3016
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003017 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003018 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3019 * and not available in ConnectivityManager.
3020 */
3021 @Override
3022 public VpnInfo[] getAllVpnInfo() {
3023 enforceConnectivityInternalPermission();
3024 if (mLockdownEnabled) {
3025 return new VpnInfo[0];
3026 }
3027
3028 synchronized(mVpns) {
3029 List<VpnInfo> infoList = new ArrayList<>();
3030 for (int i = 0; i < mVpns.size(); i++) {
3031 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3032 if (info != null) {
3033 infoList.add(info);
3034 }
3035 }
3036 return infoList.toArray(new VpnInfo[infoList.size()]);
3037 }
3038 }
3039
3040 /**
3041 * @return VPN information for accounting, or null if we can't retrieve all required
3042 * information, e.g primary underlying iface.
3043 */
3044 @Nullable
3045 private VpnInfo createVpnInfo(Vpn vpn) {
3046 VpnInfo info = vpn.getVpnInfo();
3047 if (info == null) {
3048 return null;
3049 }
3050 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3051 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3052 // the underlyingNetworks list.
3053 if (underlyingNetworks == null) {
3054 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3055 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3056 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3057 }
3058 } else if (underlyingNetworks.length > 0) {
3059 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3060 if (linkProperties != null) {
3061 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3062 }
3063 }
3064 return info.primaryUnderlyingIface == null ? null : info;
3065 }
3066
3067 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003068 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3069 * not available in ConnectivityManager.
3070 * Permissions are checked in Vpn class.
3071 * @hide
3072 */
3073 @Override
3074 public VpnConfig getVpnConfig() {
3075 int user = UserHandle.getUserId(Binder.getCallingUid());
3076 synchronized(mVpns) {
3077 return mVpns.get(user).getVpnConfig();
3078 }
3079 }
3080
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003081 @Override
3082 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003083 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3084 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3085 return false;
3086 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003087
3088 // Tear down existing lockdown if profile was removed
3089 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3090 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003091 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003092 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3093 return false;
3094 }
3095
3096 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3097 final VpnProfile profile = VpnProfile.decode(
3098 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003099 int user = UserHandle.getUserId(Binder.getCallingUid());
3100 synchronized(mVpns) {
3101 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3102 profile));
3103 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003104 } else {
3105 setLockdownTracker(null);
3106 }
3107
3108 return true;
3109 }
3110
3111 /**
3112 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3113 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3114 */
3115 private void setLockdownTracker(LockdownVpnTracker tracker) {
3116 // Shutdown any existing tracker
3117 final LockdownVpnTracker existing = mLockdownTracker;
3118 mLockdownTracker = null;
3119 if (existing != null) {
3120 existing.shutdown();
3121 }
3122
3123 try {
3124 if (tracker != null) {
3125 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003126 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003127 mLockdownTracker = tracker;
3128 mLockdownTracker.init();
3129 } else {
3130 mNetd.setFirewallEnabled(false);
3131 }
3132 } catch (RemoteException e) {
3133 // ignored; NMS lives inside system_server
3134 }
3135 }
3136
3137 private void throwIfLockdownEnabled() {
3138 if (mLockdownEnabled) {
3139 throw new IllegalStateException("Unavailable in lockdown mode");
3140 }
3141 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003142
Wink Savilleab9321d2013-06-29 21:10:57 -07003143 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003144 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003145 // TODO: Remove? Any reason to trigger a provisioning check?
3146 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003147 }
3148
3149 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3150 private volatile boolean mIsNotificationVisible = false;
3151
Paul Jensen89e0f092014-09-15 15:59:36 -04003152 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003153 if (DBG) {
3154 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003155 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003156 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003157 Intent intent = new Intent(action);
3158 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003159 // Concatenate the range of types onto the range of NetIDs.
3160 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003161 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003162 }
3163
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003164 /**
3165 * Show or hide network provisioning notificaitons.
3166 *
3167 * @param id an identifier that uniquely identifies this notification. This must match
3168 * between show and hide calls. We use the NetID value but for legacy callers
3169 * we concatenate the range of types with the range of NetIDs.
3170 */
3171 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003172 String extraInfo, PendingIntent intent) {
3173 if (DBG) {
3174 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3175 networkType + " extraInfo=" + extraInfo);
3176 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003177
3178 Resources r = Resources.getSystem();
3179 NotificationManager notificationManager = (NotificationManager) mContext
3180 .getSystemService(Context.NOTIFICATION_SERVICE);
3181
3182 if (visible) {
3183 CharSequence title;
3184 CharSequence details;
3185 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003186 Notification notification = new Notification();
3187 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003188 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003189 title = r.getString(R.string.wifi_available_sign_in, 0);
3190 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003191 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003192 icon = R.drawable.stat_notify_wifi_in_range;
3193 break;
3194 case ConnectivityManager.TYPE_MOBILE:
3195 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003196 title = r.getString(R.string.network_available_sign_in, 0);
3197 // TODO: Change this to pull from NetworkInfo once a printable
3198 // name has been added to it
3199 details = mTelephonyManager.getNetworkOperatorName();
3200 icon = R.drawable.stat_notify_rssi_in_range;
3201 break;
3202 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003203 title = r.getString(R.string.network_available_sign_in, 0);
3204 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003205 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003206 icon = R.drawable.stat_notify_rssi_in_range;
3207 break;
3208 }
3209
Wink Savilleab9321d2013-06-29 21:10:57 -07003210 notification.when = 0;
3211 notification.icon = icon;
3212 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003213 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003214 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003215 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003216 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003217 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003218
Wink Saville948282b2013-08-29 08:55:16 -07003219 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003220 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003221 } catch (NullPointerException npe) {
3222 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3223 npe.printStackTrace();
3224 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003225 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003226 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003227 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003228 } catch (NullPointerException npe) {
3229 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3230 npe.printStackTrace();
3231 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003232 }
Wink Saville948282b2013-08-29 08:55:16 -07003233 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003234 }
3235
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003236 /** Location to an updatable file listing carrier provisioning urls.
3237 * An example:
3238 *
3239 * <?xml version="1.0" encoding="utf-8"?>
3240 * <provisioningUrls>
3241 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3242 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3243 * </provisioningUrls>
3244 */
3245 private static final String PROVISIONING_URL_PATH =
3246 "/data/misc/radio/provisioning_urls.xml";
3247 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003248
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003249 /** XML tag for root element. */
3250 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3251 /** XML tag for individual url */
3252 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3253 /** XML tag for redirected url */
3254 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3255 /** XML attribute for mcc */
3256 private static final String ATTR_MCC = "mcc";
3257 /** XML attribute for mnc */
3258 private static final String ATTR_MNC = "mnc";
3259
3260 private static final int REDIRECTED_PROVISIONING = 1;
3261 private static final int PROVISIONING = 2;
3262
3263 private String getProvisioningUrlBaseFromFile(int type) {
3264 FileReader fileReader = null;
3265 XmlPullParser parser = null;
3266 Configuration config = mContext.getResources().getConfiguration();
3267 String tagType;
3268
3269 switch (type) {
3270 case PROVISIONING:
3271 tagType = TAG_PROVISIONING_URL;
3272 break;
3273 case REDIRECTED_PROVISIONING:
3274 tagType = TAG_REDIRECTED_URL;
3275 break;
3276 default:
3277 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3278 type);
3279 }
3280
3281 try {
3282 fileReader = new FileReader(mProvisioningUrlFile);
3283 parser = Xml.newPullParser();
3284 parser.setInput(fileReader);
3285 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3286
3287 while (true) {
3288 XmlUtils.nextElement(parser);
3289
3290 String element = parser.getName();
3291 if (element == null) break;
3292
3293 if (element.equals(tagType)) {
3294 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3295 try {
3296 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3297 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3298 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3299 parser.next();
3300 if (parser.getEventType() == XmlPullParser.TEXT) {
3301 return parser.getText();
3302 }
3303 }
3304 }
3305 } catch (NumberFormatException e) {
3306 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3307 }
3308 }
3309 }
3310 return null;
3311 } catch (FileNotFoundException e) {
3312 loge("Carrier Provisioning Urls file not found");
3313 } catch (XmlPullParserException e) {
3314 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3315 } catch (IOException e) {
3316 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3317 } finally {
3318 if (fileReader != null) {
3319 try {
3320 fileReader.close();
3321 } catch (IOException e) {}
3322 }
3323 }
3324 return null;
3325 }
3326
Wink Saville42d4f082013-07-20 20:31:59 -07003327 @Override
3328 public String getMobileRedirectedProvisioningUrl() {
3329 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003330 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3331 if (TextUtils.isEmpty(url)) {
3332 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3333 }
3334 return url;
3335 }
3336
Wink Saville42d4f082013-07-20 20:31:59 -07003337 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003338 public String getMobileProvisioningUrl() {
3339 enforceConnectivityInternalPermission();
3340 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3341 if (TextUtils.isEmpty(url)) {
3342 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003343 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003344 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003345 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003346 }
Wink Saville8cf35602013-07-10 23:00:07 -07003347 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003348 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003349 String phoneNumber = mTelephonyManager.getLine1Number();
3350 if (TextUtils.isEmpty(phoneNumber)) {
3351 phoneNumber = "0000000000";
3352 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003353 url = String.format(url,
3354 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3355 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003356 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003357 }
3358
Wink Savilleab9321d2013-06-29 21:10:57 -07003359 return url;
3360 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003361
Wink Saville948282b2013-08-29 08:55:16 -07003362 @Override
3363 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003364 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003365 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003366 final long ident = Binder.clearCallingIdentity();
3367 try {
3368 setProvNotificationVisible(visible, networkType, action);
3369 } finally {
3370 Binder.restoreCallingIdentity(ident);
3371 }
Wink Saville948282b2013-08-29 08:55:16 -07003372 }
Wink Saville7788c612013-08-29 14:57:08 -07003373
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003374 @Override
3375 public void setAirplaneMode(boolean enable) {
3376 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003377 final long ident = Binder.clearCallingIdentity();
3378 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003379 final ContentResolver cr = mContext.getContentResolver();
3380 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3381 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3382 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003383 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003384 } finally {
3385 Binder.restoreCallingIdentity(ident);
3386 }
3387 }
3388
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003389 private void onUserStart(int userId) {
3390 synchronized(mVpns) {
3391 Vpn userVpn = mVpns.get(userId);
3392 if (userVpn != null) {
3393 loge("Starting user already has a VPN");
3394 return;
3395 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003396 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003397 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003398 }
3399 }
3400
3401 private void onUserStop(int userId) {
3402 synchronized(mVpns) {
3403 Vpn userVpn = mVpns.get(userId);
3404 if (userVpn == null) {
3405 loge("Stopping user has no VPN");
3406 return;
3407 }
3408 mVpns.delete(userId);
3409 }
3410 }
3411
3412 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3413 @Override
3414 public void onReceive(Context context, Intent intent) {
3415 final String action = intent.getAction();
3416 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3417 if (userId == UserHandle.USER_NULL) return;
3418
3419 if (Intent.ACTION_USER_STARTING.equals(action)) {
3420 onUserStart(userId);
3421 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3422 onUserStop(userId);
3423 }
3424 }
3425 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003426
Robert Greenwalta67be032014-05-16 15:49:14 -07003427 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3428 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003429 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3430 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003431
Robert Greenwalta67be032014-05-16 15:49:14 -07003432 private static class NetworkFactoryInfo {
3433 public final String name;
3434 public final Messenger messenger;
3435 public final AsyncChannel asyncChannel;
3436
3437 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3438 this.name = name;
3439 this.messenger = messenger;
3440 this.asyncChannel = asyncChannel;
3441 }
3442 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003443
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003444 /**
3445 * Tracks info about the requester.
3446 * Also used to notice when the calling process dies so we can self-expire
3447 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003448 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3449 static final boolean REQUEST = true;
3450 static final boolean LISTEN = false;
3451
3452 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003453 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003454 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003455 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003456 final int mPid;
3457 final int mUid;
3458 final Messenger messenger;
3459 final boolean isRequest;
3460
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003461 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3462 request = r;
3463 mPendingIntent = pi;
3464 messenger = null;
3465 mBinder = null;
3466 mPid = getCallingPid();
3467 mUid = getCallingUid();
3468 this.isRequest = isRequest;
3469 }
3470
Robert Greenwalt9258c642014-03-26 16:47:06 -07003471 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3472 super();
3473 messenger = m;
3474 request = r;
3475 mBinder = binder;
3476 mPid = getCallingPid();
3477 mUid = getCallingUid();
3478 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003479 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003480
3481 try {
3482 mBinder.linkToDeath(this, 0);
3483 } catch (RemoteException e) {
3484 binderDied();
3485 }
3486 }
3487
3488 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003489 if (mBinder != null) {
3490 mBinder.unlinkToDeath(this, 0);
3491 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003492 }
3493
3494 public void binderDied() {
3495 log("ConnectivityService NetworkRequestInfo binderDied(" +
3496 request + ", " + mBinder + ")");
3497 releaseNetworkRequest(request);
3498 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003499
3500 public String toString() {
3501 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003502 mPid + " for " + request +
3503 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003504 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003505 }
3506
3507 @Override
3508 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003509 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003510 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003511 enforceNetworkRequestPermissions(networkCapabilities);
3512 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003513
Robert Greenwalt6078b502014-06-11 16:05:07 -07003514 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003515 throw new IllegalArgumentException("Bad timeout specified");
3516 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003517
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003518 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3519 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003520 if (DBG) log("requestNetwork for " + networkRequest);
3521 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3522 NetworkRequestInfo.REQUEST);
3523
3524 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003525 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003526 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003527 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003528 }
3529 return networkRequest;
3530 }
3531
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003532 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3533 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3534 == false) {
3535 enforceConnectivityInternalPermission();
3536 } else {
3537 enforceChangePermission();
3538 }
3539 }
3540
fenglub15e72b2015-03-20 11:29:56 -07003541 @Override
fengludb571472015-04-21 17:12:05 -07003542 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003543 enforceAccessPermission();
3544 NetworkAgentInfo nai = null;
3545 if (network == null) {
3546 return false;
3547 }
3548 synchronized (mNetworkForNetId) {
3549 nai = mNetworkForNetId.get(network.netId);
3550 }
3551 if (nai != null) {
3552 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3553 return true;
3554 }
3555 return false;
3556 }
3557
3558
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003559 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3560 // if UID is restricted, don't allow them to bring up metered APNs
3561 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
3562 == false) {
3563 final int uidRules;
3564 final int uid = Binder.getCallingUid();
3565 synchronized(mRulesLock) {
3566 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3567 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003568 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003569 // we could silently fail or we can filter the available nets to only give
3570 // them those they have access to. Chose the more useful
3571 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3572 }
3573 }
3574 }
3575
Robert Greenwalt9258c642014-03-26 16:47:06 -07003576 @Override
3577 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3578 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003579 checkNotNull(operation, "PendingIntent cannot be null.");
3580 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3581 enforceNetworkRequestPermissions(networkCapabilities);
3582 enforceMeteredApnPolicy(networkCapabilities);
3583
3584 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3585 nextNetworkRequestId());
3586 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3587 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3588 NetworkRequestInfo.REQUEST);
3589 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3590 nri));
3591 return networkRequest;
3592 }
3593
Jeremy Joslin79294842014-12-03 17:15:28 -08003594 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3595 mHandler.sendMessageDelayed(
3596 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3597 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3598 }
3599
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003600 @Override
3601 public void releasePendingNetworkRequest(PendingIntent operation) {
3602 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3603 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003604 }
3605
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003606 // In order to implement the compatibility measure for pre-M apps that call
3607 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3608 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3609 // This ensures it has permission to do so.
3610 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3611 if (nc == null) {
3612 return false;
3613 }
3614 int[] transportTypes = nc.getTransportTypes();
3615 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3616 return false;
3617 }
3618 try {
3619 mContext.enforceCallingOrSelfPermission(
3620 android.Manifest.permission.ACCESS_WIFI_STATE,
3621 "ConnectivityService");
3622 } catch (SecurityException e) {
3623 return false;
3624 }
3625 return true;
3626 }
3627
Robert Greenwalt9258c642014-03-26 16:47:06 -07003628 @Override
3629 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3630 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003631 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3632 enforceAccessPermission();
3633 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003634
3635 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003636 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003637 if (DBG) log("listenForNetwork for " + networkRequest);
3638 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3639 NetworkRequestInfo.LISTEN);
3640
3641 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3642 return networkRequest;
3643 }
3644
3645 @Override
3646 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3647 PendingIntent operation) {
3648 }
3649
3650 @Override
3651 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003652 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3653 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003654 }
3655
3656 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003657 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003658 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003659 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3660 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003661 }
3662
Robert Greenwalta67be032014-05-16 15:49:14 -07003663 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003664 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003665 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3666 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3667 }
3668
3669 @Override
3670 public void unregisterNetworkFactory(Messenger messenger) {
3671 enforceConnectivityInternalPermission();
3672 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3673 }
3674
3675 private void handleUnregisterNetworkFactory(Messenger messenger) {
3676 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3677 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003678 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003679 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003680 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003681 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003682 }
3683
Robert Greenwalt7b816022014-04-18 15:25:25 -07003684 /**
3685 * NetworkAgentInfo supporting a request by requestId.
3686 * These have already been vetted (their Capabilities satisfy the request)
3687 * and the are the highest scored network available.
3688 * the are keyed off the Requests requestId.
3689 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003690 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003691 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3692 new SparseArray<NetworkAgentInfo>();
3693
Paul Jensen31a94f42015-02-13 14:18:39 -05003694 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3695 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003696 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3697 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003698 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3699 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3700 // there may not be a strict 1:1 correlation between the two.
3701 @GuardedBy("mNetworkForNetId")
3702 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003703
Robert Greenwalt7b816022014-04-18 15:25:25 -07003704 // NetworkAgentInfo keyed off its connecting messenger
3705 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003706 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003707 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3708 new HashMap<Messenger, NetworkAgentInfo>();
3709
Paul Jensen2c311d62014-11-17 12:34:51 -05003710 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003711 private final NetworkRequest mDefaultRequest;
3712
Erik Klineda4bfa82015-04-30 12:58:40 +09003713 // Request used to optionally keep mobile data active even when higher
3714 // priority networks like Wi-Fi are active.
3715 private final NetworkRequest mDefaultMobileDataRequest;
3716
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003717 private NetworkAgentInfo getDefaultNetwork() {
3718 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3719 }
3720
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003721 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003722 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003723 }
3724
Paul Jensen31a94f42015-02-13 14:18:39 -05003725 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003726 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003727 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003728 enforceConnectivityInternalPermission();
3729
Paul Jensen2c311d62014-11-17 12:34:51 -05003730 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3731 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003732 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003733 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3734 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3735 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003736 synchronized (this) {
3737 nai.networkMonitor.systemReady = mSystemReady;
3738 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003739 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003740 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003741 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003742 }
3743
3744 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3745 if (VDBG) log("Got NetworkAgent Messenger");
3746 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003747 synchronized (mNetworkForNetId) {
3748 mNetworkForNetId.put(na.network.netId, na);
3749 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003750 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3751 NetworkInfo networkInfo = na.networkInfo;
3752 na.networkInfo = null;
3753 updateNetworkInfo(na, networkInfo);
3754 }
3755
3756 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3757 LinkProperties newLp = networkAgent.linkProperties;
3758 int netId = networkAgent.network.netId;
3759
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003760 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3761 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003762 if (networkAgent.clatd != null) {
3763 networkAgent.clatd.fixupLinkProperties(oldLp);
3764 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003765
Paul Jensen992f2522014-04-28 10:33:11 -04003766 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003767 updateMtu(newLp, oldLp);
3768 // TODO - figure out what to do for clat
3769// for (LinkProperties lp : newLp.getStackedLinks()) {
3770// updateMtu(lp, null);
3771// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003772 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003773
3774 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3775 // For now, use it only when the network has Internet access. http://b/18327075
3776 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3777 NetworkCapabilities.NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003778 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003779 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3780
Paul Jensen3b759822014-05-13 11:44:01 -04003781 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003782 if (isDefaultNetwork(networkAgent)) {
3783 handleApplyDefaultProxy(newLp.getHttpProxy());
3784 } else {
3785 updateProxy(newLp, oldLp, networkAgent);
3786 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003787 // TODO - move this check to cover the whole function
3788 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003789 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003790 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3791 }
Paul Jensen3b759822014-05-13 11:44:01 -04003792 }
3793
Lorenzo Colitti95439462014-10-09 13:44:48 +09003794 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3795 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3796 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003797
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003798 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003799 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3800 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003801 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003802 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003803 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003804 }
Paul Jensen992f2522014-04-28 10:33:11 -04003805
3806 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3807 CompareResult<String> interfaceDiff = new CompareResult<String>();
3808 if (oldLp != null) {
3809 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3810 } else if (newLp != null) {
3811 interfaceDiff.added = newLp.getAllInterfaceNames();
3812 }
3813 for (String iface : interfaceDiff.added) {
3814 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003815 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003816 mNetd.addInterfaceToNetwork(iface, netId);
3817 } catch (Exception e) {
3818 loge("Exception adding interface: " + e);
3819 }
3820 }
3821 for (String iface : interfaceDiff.removed) {
3822 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003823 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003824 mNetd.removeInterfaceFromNetwork(iface, netId);
3825 } catch (Exception e) {
3826 loge("Exception removing interface: " + e);
3827 }
3828 }
3829 }
3830
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003831 /**
3832 * Have netd update routes from oldLp to newLp.
3833 * @return true if routes changed between oldLp and newLp
3834 */
3835 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003836 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3837 if (oldLp != null) {
3838 routeDiff = oldLp.compareAllRoutes(newLp);
3839 } else if (newLp != null) {
3840 routeDiff.added = newLp.getAllRoutes();
3841 }
3842
3843 // add routes before removing old in case it helps with continuous connectivity
3844
3845 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3846 for (RouteInfo route : routeDiff.added) {
3847 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003848 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003849 try {
3850 mNetd.addRoute(netId, route);
3851 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003852 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3853 loge("Exception in addRoute for non-gateway: " + e);
3854 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003855 }
3856 }
3857 for (RouteInfo route : routeDiff.added) {
3858 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003859 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003860 try {
3861 mNetd.addRoute(netId, route);
3862 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003863 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3864 loge("Exception in addRoute for gateway: " + e);
3865 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003866 }
3867 }
3868
3869 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003870 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003871 try {
3872 mNetd.removeRoute(netId, route);
3873 } catch (Exception e) {
3874 loge("Exception in removeRoute: " + e);
3875 }
3876 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003877 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003878 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003879 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3880 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003881 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003882 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003883 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003884 dnses = new ArrayList();
3885 dnses.add(mDefaultDns);
3886 if (DBG) {
3887 loge("no dns provided for netId " + netId + ", so using defaults");
3888 }
3889 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003890 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003891 try {
3892 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3893 newLp.getDomains());
3894 } catch (Exception e) {
3895 loge("Exception in setDnsServersForNetwork: " + e);
3896 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003897 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3898 if (defaultNai != null && defaultNai.network.netId == netId) {
3899 setDefaultDnsSystemProperties(dnses);
3900 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003901 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003902 } else if (flush) {
3903 try {
3904 mNetd.flushNetworkDnsCache(netId);
3905 } catch (Exception e) {
3906 loge("Exception in flushNetworkDnsCache: " + e);
3907 }
3908 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003909 }
3910 }
3911
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003912 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3913 int last = 0;
3914 for (InetAddress dns : dnses) {
3915 ++last;
3916 String key = "net.dns" + last;
3917 String value = dns.getHostAddress();
3918 SystemProperties.set(key, value);
3919 }
3920 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3921 String key = "net.dns" + i;
3922 SystemProperties.set(key, "");
3923 }
3924 mNumDnsEntries = last;
3925 }
3926
Robert Greenwalt7b816022014-04-18 15:25:25 -07003927 private void updateCapabilities(NetworkAgentInfo networkAgent,
3928 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003929 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3930 synchronized (networkAgent) {
3931 networkAgent.networkCapabilities = networkCapabilities;
3932 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003933 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003934 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003935 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003936 }
3937
Paul Jensenc8b9a742014-09-30 15:37:41 -04003938 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3939 for (int i = 0; i < nai.networkRequests.size(); i++) {
3940 NetworkRequest nr = nai.networkRequests.valueAt(i);
3941 // Don't send listening requests to factories. b/17393458
3942 if (!isRequest(nr)) continue;
3943 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3944 }
3945 }
3946
Robert Greenwalt7b816022014-04-18 15:25:25 -07003947 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3948 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07003949 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07003950 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3951 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003952 }
3953 }
3954
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003955 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
3956 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08003957 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003958 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08003959 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
3960 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08003961 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003962 sendIntent(nri.mPendingIntent, intent);
3963 }
3964 // else not handled
3965 }
3966
3967 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
3968 mPendingIntentWakeLock.acquire();
3969 try {
3970 if (DBG) log("Sending " + pendingIntent);
3971 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
3972 } catch (PendingIntent.CanceledException e) {
3973 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
3974 mPendingIntentWakeLock.release();
3975 releasePendingNetworkRequest(pendingIntent);
3976 }
3977 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
3978 }
3979
3980 @Override
3981 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
3982 String resultData, Bundle resultExtras) {
3983 if (DBG) log("Finished sending " + pendingIntent);
3984 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08003985 // Release with a delay so the receiving client has an opportunity to put in its
3986 // own request.
3987 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003988 }
3989
Robert Greenwalt9258c642014-03-26 16:47:06 -07003990 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003991 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003992 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003993 Bundle bundle = new Bundle();
3994 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
3995 new NetworkRequest(nri.request));
3996 Message msg = Message.obtain();
3997 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
3998 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
3999 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4000 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004001 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004002 case ConnectivityManager.CALLBACK_LOSING: {
4003 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4004 break;
4005 }
4006 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4007 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4008 new NetworkCapabilities(networkAgent.networkCapabilities));
4009 break;
4010 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004011 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004012 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4013 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004014 break;
4015 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004016 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004017 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004018 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004019 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004020 if (VDBG) {
4021 log("sending notification " + notifyTypeToName(notificationType) +
4022 " for " + nri.request);
4023 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004024 nri.messenger.send(msg);
4025 } catch (RemoteException e) {
4026 // may occur naturally in the race of binder death.
4027 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4028 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004029 }
4030
Paul Jensenc8b9a742014-09-30 15:37:41 -04004031 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4032 for (int i = 0; i < nai.networkRequests.size(); i++) {
4033 NetworkRequest nr = nai.networkRequests.valueAt(i);
4034 // Ignore listening requests.
4035 if (!isRequest(nr)) continue;
4036 loge("Dead network still had at least " + nr);
4037 break;
4038 }
4039 nai.asyncChannel.disconnect();
4040 }
4041
Robert Greenwalt7b816022014-04-18 15:25:25 -07004042 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4043 if (oldNetwork == null) {
4044 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4045 return;
4046 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004047 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4048 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004049 }
4050
Paul Jensen27b02b72014-07-14 12:03:33 -04004051 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004052 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004053 setupDataActivityTracking(newNetwork);
4054 try {
4055 mNetd.setDefaultNetId(newNetwork.network.netId);
4056 } catch (Exception e) {
4057 loge("Exception setting default network :" + e);
4058 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004059 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004060 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004061 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004062 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004063 }
4064
Paul Jensen2161a8e2014-09-11 11:00:39 -04004065 // Handles a network appearing or improving its score.
4066 //
4067 // - Evaluates all current NetworkRequests that can be
4068 // satisfied by newNetwork, and reassigns to newNetwork
4069 // any such requests for which newNetwork is the best.
4070 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004071 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004072 // needed. A network is needed if it is the best network for
4073 // one or more NetworkRequests, or if it is a VPN.
4074 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004075 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004076 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4077 //
4078 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4079 // networks that have no chance (i.e. even if validated)
4080 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004081 //
4082 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4083 // it does not remove NetworkRequests that other Networks could better satisfy.
4084 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4085 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4086 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004087 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004088 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004089 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004090 // torn down if unneeded.
4091 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4092 // performed to tear down unvalidated networks that have no chance (i.e. even if
4093 // validated) of becoming the highest scoring network.
4094 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4095 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004096 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004097 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004098 loge("ERROR: nascent network not validated.");
4099 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004100 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004101 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004102 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004103 if (DBG) log("rematching " + newNetwork.name());
4104 // Find and migrate to this Network any NetworkRequests for
4105 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004106 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004107 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004108 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004109 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4110 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004111 if (DBG) {
4112 log("Network " + newNetwork.name() + " was already satisfying" +
4113 " request " + nri.request.requestId + ". No change.");
4114 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004115 keep = true;
4116 continue;
4117 }
4118
4119 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004120 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004121 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004122 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004123 // This is not a request, it's a callback listener.
4124 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004125 newNetwork.addRequest(nri.request);
4126 continue;
4127 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004128
Robert Greenwalt7b816022014-04-18 15:25:25 -07004129 // next check if it's better than any current network we're using for
4130 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004131 if (VDBG) {
4132 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004133 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4134 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004135 }
4136 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004137 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004138 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004139 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004140 currentNetwork.networkRequests.remove(nri.request.requestId);
4141 currentNetwork.networkLingered.add(nri.request);
4142 affectedNetworks.add(currentNetwork);
4143 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004144 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004145 }
Paul Jensen573a0352015-01-08 10:49:34 -05004146 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004147 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004148 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004149 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004150 // Tell NetworkFactories about the new score, so they can stop
4151 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004152 // TODO - this could get expensive if we have alot of requests for this
4153 // network. Think about if there is a way to reduce this. Push
4154 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004155 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004156 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004157 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004158 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004159 }
4160 }
4161 }
4162 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004163 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004164 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004165 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004166 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4167 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4168 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004169 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004170 }
4171 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004172 if (keep) {
4173 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004174 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004175 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004176 synchronized (ConnectivityService.this) {
4177 // have a new default network, release the transition wakelock in
4178 // a second if it's held. The second pause is to allow apps
4179 // to reconnect over the new network
4180 if (mNetTransitionWakeLock.isHeld()) {
4181 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4182 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4183 mNetTransitionWakeLockSerialNumber, 0),
4184 1000);
4185 }
4186 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004187 }
4188
4189 // do this after the default net is switched, but
4190 // before LegacyTypeTracker sends legacy broadcasts
4191 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4192
4193 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004194 // Maintain the illusion: since the legacy API only
4195 // understands one network at a time, we must pretend
4196 // that the current default network disconnected before
4197 // the new one connected.
4198 if (oldDefaultNetwork != null) {
4199 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004200 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004201 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004202 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004203 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4204 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004205 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004206
4207 // Notify battery stats service about this network, both the normal
4208 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004209 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004210 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004211 final IBatteryStats bs = BatteryStatsService.getService();
4212 final int type = newNetwork.networkInfo.getType();
4213
4214 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4215 bs.noteNetworkInterfaceType(baseIface, type);
4216 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4217 final String stackedIface = stacked.getInterfaceName();
4218 bs.noteNetworkInterfaceType(stackedIface, type);
4219 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4220 }
4221 } catch (RemoteException ignored) {
4222 }
4223
Robert Greenwalt152ed372014-12-17 17:19:53 -08004224 // This has to happen after the notifyNetworkCallbacks as that tickles each
4225 // ConnectivityManager instance so that legacy requests correctly bind dns
4226 // requests to this network. The legacy users are listening for this bcast
4227 // and will generally do a dns request so they can ensureRouteToHost and if
4228 // they do that before the callbacks happen they'll use the default network.
4229 //
4230 // TODO: Is there still a race here? We send the broadcast
4231 // after sending the callback, but if the app can receive the
4232 // broadcast before the callback, it might still break.
4233 //
4234 // This *does* introduce a race where if the user uses the new api
4235 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4236 // they may get old info. Reverse this after the old startUsing api is removed.
4237 // This is on top of the multiple intent sequencing referenced in the todo above.
4238 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4239 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4240 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4241 // legacy type tracker filters out repeat adds
4242 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4243 }
4244 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004245
4246 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4247 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4248 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4249 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4250 if (newNetwork.isVPN()) {
4251 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4252 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004253 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004254 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004255 // validated (and get evaluated against peers, one losing here), or get reaped (see
4256 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4257 // network. Networks that have been up for a while and are validated should be torn
4258 // down via the lingering process so communication on that network is given time to
4259 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004260 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004261 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004262 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004263 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4264 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004265 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004266 if (DBG) log("Reaping " + nai.name());
4267 teardownUnneededNetwork(nai);
4268 }
4269 }
4270 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004271 }
4272
Paul Jensen2161a8e2014-09-11 11:00:39 -04004273 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4274 // being disconnected.
4275 // If only one Network's score or capabilities have been modified since the last time
4276 // this function was called, pass this Network in via the "changed" arugment, otherwise
4277 // pass null.
4278 // If only one Network has been changed but its NetworkCapabilities have not changed,
4279 // pass in the Network's score (from getCurrentScore()) prior to the change via
4280 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4281 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4282 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4283 // to avoid the slowness. It is not simply enough to process just "changed", for
4284 // example in the case where "changed"'s score decreases and another network should begin
4285 // satifying a NetworkRequest that "changed" currently satisfies.
4286
4287 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4288 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4289 // rematchNetworkAndRequests() handles.
4290 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004291 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4292 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004293 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004294 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4295 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4296 NascentState.NOT_JUST_VALIDATED,
4297 // Only reap the last time through the loop. Reaping before all rematching
4298 // is complete could incorrectly teardown a network that hasn't yet been
4299 // rematched.
4300 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4301 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004302 }
4303 }
4304 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004305
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004306 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004307 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004308 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004309 // For now only update icons for default connection.
4310 // TODO: Update WiFi and cellular icons separately. b/17237507
4311 if (!isDefaultNetwork(nai)) return;
4312
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004313 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004314 // Don't repeat publish.
4315 if (newInetCondition == mDefaultInetConditionPublished) return;
4316
4317 mDefaultInetConditionPublished = newInetCondition;
4318 sendInetConditionBroadcast(nai.networkInfo);
4319 }
4320
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004321 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4322 if (mLockdownTracker != null) {
4323 if (nai != null && nai.isVPN()) {
4324 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4325 } else {
4326 mLockdownTracker.onNetworkInfoChanged();
4327 }
4328 }
4329 }
4330
Robert Greenwalt7b816022014-04-18 15:25:25 -07004331 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4332 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004333 NetworkInfo oldInfo = null;
4334 synchronized (networkAgent) {
4335 oldInfo = networkAgent.networkInfo;
4336 networkAgent.networkInfo = newInfo;
4337 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004338 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004339
4340 if (oldInfo != null && oldInfo.getState() == state) {
4341 if (VDBG) log("ignoring duplicate network state non-change");
4342 return;
4343 }
4344 if (DBG) {
4345 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4346 (oldInfo == null ? "null" : oldInfo.getState()) +
4347 " to " + state);
4348 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004349
Paul Jenseneec75412014-08-04 12:21:19 -04004350 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004351 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004352 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004353 if (networkAgent.isVPN()) {
4354 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004355 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4356 (networkAgent.networkMisc == null ||
4357 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004358 } else {
4359 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4360 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004361 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004362 loge("Error creating network " + networkAgent.network.netId + ": "
4363 + e.getMessage());
4364 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004365 }
Paul Jenseneec75412014-08-04 12:21:19 -04004366 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004367 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004368 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004369
Paul Jensenca8f16a2014-05-09 12:47:55 -04004370 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004371 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004372
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004373 if (networkAgent.isVPN()) {
4374 // Temporarily disable the default proxy (not global).
4375 synchronized (mProxyLock) {
4376 if (!mDefaultProxyDisabled) {
4377 mDefaultProxyDisabled = true;
4378 if (mGlobalProxy == null && mDefaultProxy != null) {
4379 sendProxyBroadcast(null);
4380 }
4381 }
4382 }
4383 // TODO: support proxy per network.
4384 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004385
Paul Jensen2161a8e2014-09-11 11:00:39 -04004386 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004387 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4388 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004389
4390 // This has to happen after matching the requests, because callbacks are just requests.
4391 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004392 } else if (state == NetworkInfo.State.DISCONNECTED ||
4393 state == NetworkInfo.State.SUSPENDED) {
4394 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004395 if (networkAgent.isVPN()) {
4396 synchronized (mProxyLock) {
4397 if (mDefaultProxyDisabled) {
4398 mDefaultProxyDisabled = false;
4399 if (mGlobalProxy == null && mDefaultProxy != null) {
4400 sendProxyBroadcast(mDefaultProxy);
4401 }
4402 }
4403 }
4404 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004405 }
4406 }
4407
Robert Greenwaltac96c522014-06-03 16:43:57 -07004408 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4409 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004410 if (score < 0) {
4411 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4412 "). Bumping score to min of 0");
4413 score = 0;
4414 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004415
Paul Jensen2161a8e2014-09-11 11:00:39 -04004416 final int oldScore = nai.getCurrentScore();
4417 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004418
Paul Jensen57a767f2014-11-19 13:01:46 -05004419 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004420
Paul Jensenc8b9a742014-09-30 15:37:41 -04004421 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004422 }
4423
Robert Greenwalt9258c642014-03-26 16:47:06 -07004424 // notify only this one new request of the current state
4425 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4426 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4427 // TODO - read state from monitor to decide what to send.
4428// if (nai.networkMonitor.isLingering()) {
4429// notifyType = NetworkCallbacks.LOSING;
4430// } else if (nai.networkMonitor.isEvaluating()) {
4431// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4432// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004433 if (nri.mPendingIntent == null) {
4434 callCallbackForRequest(nri, nai, notifyType);
4435 } else {
4436 sendPendingIntentForRequest(nri, nai, notifyType);
4437 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004438 }
4439
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004440 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004441 // The NetworkInfo we actually send out has no bearing on the real
4442 // state of affairs. For example, if the default connection is mobile,
4443 // and a request for HIPRI has just gone away, we need to pretend that
4444 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4445 // the state to DISCONNECTED, even though the network is of type MOBILE
4446 // and is still connected.
4447 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4448 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004449 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004450 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004451 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004452 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004453 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004454 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4455 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4456 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4457 if (info.isFailover()) {
4458 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4459 nai.networkInfo.setFailover(false);
4460 }
4461 if (info.getReason() != null) {
4462 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4463 }
4464 if (info.getExtraInfo() != null) {
4465 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4466 }
4467 NetworkAgentInfo newDefaultAgent = null;
4468 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4469 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4470 if (newDefaultAgent != null) {
4471 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4472 newDefaultAgent.networkInfo);
4473 } else {
4474 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4475 }
4476 }
4477 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4478 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004479 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004480 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004481 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004482 }
4483 }
4484 }
4485
Robert Greenwalt7b816022014-04-18 15:25:25 -07004486 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004487 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004488 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004489 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4490 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4491 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004492 if (nri.mPendingIntent == null) {
4493 callCallbackForRequest(nri, networkAgent, notifyType);
4494 } else {
4495 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4496 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004497 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004498 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004499
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004500 private String notifyTypeToName(int notifyType) {
4501 switch (notifyType) {
4502 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4503 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4504 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4505 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4506 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4507 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4508 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4509 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4510 }
4511 return "UNKNOWN";
4512 }
4513
Jeff Sharkey69736342014-12-08 14:50:12 -08004514 /**
4515 * Notify other system services that set of active ifaces has changed.
4516 */
4517 private void notifyIfacesChanged() {
4518 try {
4519 mStatsService.forceUpdateIfaces();
4520 } catch (Exception ignored) {
4521 }
4522 }
4523
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004524 @Override
4525 public boolean addVpnAddress(String address, int prefixLength) {
4526 throwIfLockdownEnabled();
4527 int user = UserHandle.getUserId(Binder.getCallingUid());
4528 synchronized (mVpns) {
4529 return mVpns.get(user).addAddress(address, prefixLength);
4530 }
4531 }
4532
4533 @Override
4534 public boolean removeVpnAddress(String address, int prefixLength) {
4535 throwIfLockdownEnabled();
4536 int user = UserHandle.getUserId(Binder.getCallingUid());
4537 synchronized (mVpns) {
4538 return mVpns.get(user).removeAddress(address, prefixLength);
4539 }
4540 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004541
4542 @Override
4543 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4544 throwIfLockdownEnabled();
4545 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004546 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004547 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004548 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004549 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004550 if (success) {
4551 notifyIfacesChanged();
4552 }
4553 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004554 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004555
4556 @Override
4557 public void factoryReset() {
4558 enforceConnectivityInternalPermission();
4559 // Turn airplane mode off
4560 setAirplaneMode(false);
4561
4562 // Untether
4563 for (String tether : getTetheredIfaces()) {
4564 untether(tether);
4565 }
4566
4567 // Turn VPN off
4568 VpnConfig vpnConfig = getVpnConfig();
4569 if (vpnConfig != null) {
4570 if (vpnConfig.legacy) {
4571 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN);
4572 } else {
4573 // Prevent this app from initiating VPN connections in the future without
4574 // user intervention.
4575 setVpnPackageAuthorization(false);
4576
4577 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN);
4578 }
4579 }
4580 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004581}