blob: bba35801d3c6e54ee28de1a04298043ae791742c [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;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070027import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070028
Wenchao Tongf5ea3402015-03-04 13:26:38 -080029import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070030import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070031import android.app.Notification;
32import android.app.NotificationManager;
33import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070034import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080035import android.content.ContentResolver;
36import android.content.Context;
37import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070038import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080039import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070040import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090041import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070042import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080043import android.net.ConnectivityManager;
44import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070045import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070046import android.net.INetworkPolicyListener;
47import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070048import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080049import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070050import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070051import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070052import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070053import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070054import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080055import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070056import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070057import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070058import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070059import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070060import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070061import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070062import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040063import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070064import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040065import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040066import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080067import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070068import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040069import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080070import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070071import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070072import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070073import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080074import android.os.Looper;
75import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070076import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070077import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070078import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070079import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070080import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070081import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080082import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070083import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040084import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080085import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070086import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070087import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070088import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070089import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080090import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070091import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -050092import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070093import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070094import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080095
Wink Savilleab9321d2013-06-29 21:10:57 -070096import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -040097import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070098import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070099import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700100import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700101import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800102import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700103import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700104import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700105import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700106import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700107import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700108import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400109import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900110import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700111import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400112import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400113import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700114import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800115import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700116import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700117import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700118import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700119import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700120import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700121
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700122import org.xmlpull.v1.XmlPullParser;
123import org.xmlpull.v1.XmlPullParserException;
124
125import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800126import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700127import java.io.FileNotFoundException;
128import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700129import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800130import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700131import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700132import java.net.InetAddress;
133import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700134import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700135import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700136import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700137import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700138import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500139import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700140import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700141import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700142import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700143import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800144
145/**
146 * @hide
147 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800148public class ConnectivityService extends IConnectivityManager.Stub
149 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700150 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800151
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700152 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700153 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800154
Jake Hamby786e71a2014-02-06 14:43:50 -0800155 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700156
Jeff Sharkey899223b2012-08-04 15:24:58 -0700157 // TODO: create better separation between radio types and network types
158
Robert Greenwalt42acef32009-08-12 16:08:25 -0700159 // how long to wait before switching back to a radio's default network
160 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
161 // system property that can override the above value
162 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
163 "android.telephony.apn-restore";
164
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900165 // How long to wait before putting up a "This network doesn't have an Internet connection,
166 // connect anyway?" dialog after the user selects a network that doesn't validate.
167 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
168
Jeremy Joslin79294842014-12-03 17:15:28 -0800169 // How long to delay to removal of a pending intent based request.
170 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
171 private final int mReleasePendingIntentDelayMs;
172
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800173 private Tethering mTethering;
174
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700175 private final PermissionMonitor mPermissionMonitor;
176
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700177 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700178
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700179 @GuardedBy("mVpns")
180 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700181
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700182 private boolean mLockdownEnabled;
183 private LockdownVpnTracker mLockdownTracker;
184
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700185 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
186 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700187 /** Currently active network rules by UID. */
188 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700189 /** Set of ifaces that are costly. */
190 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700191
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800192 private Context mContext;
193 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700194 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700195 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700197 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800198 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800199
200 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700201 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800202
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700203 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800204 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700205 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700206
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700207 private String mCurrentTcpBufferSizes;
208
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700209 private static final int ENABLED = 1;
210 private static final int DISABLED = 0;
211
Paul Jensenb10e37f2014-11-25 12:33:08 -0500212 // Arguments to rematchNetworkAndRequests()
213 private enum NascentState {
214 // Indicates a network was just validated for the first time. If the network is found to
215 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
216 JUST_VALIDATED,
217 // Indicates a network was not validated for the first time immediately prior to this call.
218 NOT_JUST_VALIDATED
219 };
220 private enum ReapUnvalidatedNetworks {
221 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
222 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
223 // known that there may be unvalidated networks that could potentially be reaped, and when
224 // all networks have been rematched against all NetworkRequests.
225 REAP,
226 // Don't reap unvalidated networks. This should be passed when it's known that there are
227 // no unvalidated networks that could potentially be reaped, and when some networks have
228 // not yet been rematched against all NetworkRequests.
229 DONT_REAP
230 };
231
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700232 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700233 * used internally to change our mobile data enabled flag
234 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700235 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700236
237 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700238 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700239 * from one net to another. Clear happens when we get a new
240 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
241 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700242 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700243 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700244
Robert Greenwalt434203a2010-10-11 16:00:27 -0700245 /**
246 * used internally to reload global proxy settings
247 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700248 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700249
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700250 /**
Wink Saville628b0852011-08-04 15:01:58 -0700251 * used internally to send a sticky broadcast delayed.
252 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700253 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700254
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700255 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400256 * PAC manager has received new port.
257 */
258 private static final int EVENT_PROXY_HAS_CHANGED = 16;
259
Robert Greenwalte049c232014-04-11 15:53:27 -0700260 /**
261 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700262 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700263 */
264 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
265
Robert Greenwalt7b816022014-04-18 15:25:25 -0700266 /**
267 * used internally when registering NetworkAgents
268 * obj = Messenger
269 */
270 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
271
Robert Greenwalt9258c642014-03-26 16:47:06 -0700272 /**
273 * used to add a network request
274 * includes a NetworkRequestInfo
275 */
276 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
277
278 /**
279 * indicates a timeout period is over - check if we had a network yet or not
280 * and if not, call the timeout calback (but leave the request live until they
281 * cancel it.
282 * includes a NetworkRequestInfo
283 */
284 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
285
286 /**
287 * used to add a network listener - no request
288 * includes a NetworkRequestInfo
289 */
290 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
291
292 /**
293 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400294 * arg1 = UID of caller
295 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700296 */
297 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
298
Robert Greenwalta67be032014-05-16 15:49:14 -0700299 /**
300 * used internally when registering NetworkFactories
301 * obj = Messenger
302 */
303 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
304
Robert Greenwalt27711812014-06-25 16:45:57 -0700305 /**
306 * used internally to expire a wakelock when transitioning
307 * from one net to another. Expire happens when we fail to find
308 * a new network (typically after 1 minute) -
309 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
310 * a replacement network.
311 */
312 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
313
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700314 /**
315 * Used internally to indicate the system is ready.
316 */
317 private static final int EVENT_SYSTEM_READY = 25;
318
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800319 /**
320 * used to add a network request with a pending intent
321 * includes a NetworkRequestInfo
322 */
323 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
324
325 /**
326 * used to remove a pending intent and its associated network request.
327 * arg1 = UID of caller
328 * obj = PendingIntent
329 */
330 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
331
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900332 /**
333 * used to specify whether a network should be used even if unvalidated.
334 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
335 * arg2 = whether to remember this choice in the future (1 or 0)
336 * obj = network
337 */
338 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
339
340 /**
341 * used to ask the user to confirm a connection to an unvalidated network.
342 * obj = network
343 */
344 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700345
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700346 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700347 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700348 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700349 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700350
Mike Lockwood0f79b542009-08-14 14:18:49 -0400351 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800352 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400353
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700354 private PowerManager.WakeLock mNetTransitionWakeLock;
355 private String mNetTransitionWakeLockCausedBy = "";
356 private int mNetTransitionWakeLockSerialNumber;
357 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800358 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700359
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700360 private InetAddress mDefaultDns;
361
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700362 // used in DBG mode to track inet condition reports
363 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
364 private ArrayList mInetLog;
365
Robert Greenwalt434203a2010-10-11 16:00:27 -0700366 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400367 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700368 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700369 private boolean mDefaultProxyDisabled = false;
370
Robert Greenwalt434203a2010-10-11 16:00:27 -0700371 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400372 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700373
Jason Monk602b2322013-07-03 17:04:33 -0400374 private PacManager mPacManager = null;
375
Robert Greenwalt434203a2010-10-11 16:00:27 -0700376 private SettingsObserver mSettingsObserver;
377
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400378 private UserManager mUserManager;
379
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700380 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700381 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700382
Robert Greenwalt50393202011-06-21 17:26:14 -0700383 // the set of network types that can only be enabled by system/sig apps
384 List mProtectedNetworks;
385
John Spurlockbf991a82013-06-24 14:20:23 -0400386 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700387
Wink Savilleab9321d2013-06-29 21:10:57 -0700388 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400389
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700390 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
391 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700392 private final static int MAX_NET_ID = 65535;
393 private int mNextNetId = MIN_NET_ID;
394
Robert Greenwalt34524f02014-05-18 16:22:10 -0700395 // sequence number of NetworkRequests
396 private int mNextNetworkRequestId = 1;
397
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700398 /**
399 * Implements support for the legacy "one network per network type" model.
400 *
401 * We used to have a static array of NetworkStateTrackers, one for each
402 * network type, but that doesn't work any more now that we can have,
403 * for example, more that one wifi network. This class stores all the
404 * NetworkAgentInfo objects that support a given type, but the legacy
405 * API will only see the first one.
406 *
407 * It serves two main purposes:
408 *
409 * 1. Provide information about "the network for a given type" (since this
410 * API only supports one).
411 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
412 * the first network for a given type changes, or if the default network
413 * changes.
414 */
415 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900416
417 private static final boolean DBG = true;
418 private static final boolean VDBG = false;
419 private static final String TAG = "CSLegacyTypeTracker";
420
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700421 /**
422 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
423 * Each list holds references to all NetworkAgentInfos that are used to
424 * satisfy requests for that network type.
425 *
426 * This array is built out at startup such that an unsupported network
427 * doesn't get an ArrayList instance, making this a tristate:
428 * unsupported, supported but not active and active.
429 *
430 * The actual lists are populated when we scan the network types that
431 * are supported on this device.
432 */
433 private ArrayList<NetworkAgentInfo> mTypeLists[];
434
435 public LegacyTypeTracker() {
436 mTypeLists = (ArrayList<NetworkAgentInfo>[])
437 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
438 }
439
440 public void addSupportedType(int type) {
441 if (mTypeLists[type] != null) {
442 throw new IllegalStateException(
443 "legacy list for type " + type + "already initialized");
444 }
445 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
446 }
447
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700448 public boolean isTypeSupported(int type) {
449 return isNetworkTypeValid(type) && mTypeLists[type] != null;
450 }
451
452 public NetworkAgentInfo getNetworkForType(int type) {
453 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
454 return mTypeLists[type].get(0);
455 } else {
456 return null;
457 }
458 }
459
Lorenzo Colittia793a672014-07-31 23:20:17 +0900460 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
461 if (DBG) {
462 log("Sending " + (connected ? "connected" : "disconnected") +
463 " broadcast for type " + type + " " + nai.name() +
464 " isDefaultNetwork=" + isDefaultNetwork(nai));
465 }
466 }
467
468 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700469 public void add(int type, NetworkAgentInfo nai) {
470 if (!isTypeSupported(type)) {
471 return; // Invalid network type.
472 }
473 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
474
475 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
476 if (list.contains(nai)) {
477 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
478 return;
479 }
480
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900481 list.add(nai);
482
483 // Send a broadcast if this is the first network of its type or if it's the default.
484 if (list.size() == 1 || isDefaultNetwork(nai)) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900485 maybeLogBroadcast(nai, true, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700486 sendLegacyNetworkBroadcast(nai, true, type);
487 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700488 }
489
Lorenzo Colittia793a672014-07-31 23:20:17 +0900490 /** Removes the given network from the specified legacy type list. */
491 public void remove(int type, NetworkAgentInfo nai) {
492 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
493 if (list == null || list.isEmpty()) {
494 return;
495 }
496
497 boolean wasFirstNetwork = list.get(0).equals(nai);
498
499 if (!list.remove(nai)) {
500 return;
501 }
502
503 if (wasFirstNetwork || isDefaultNetwork(nai)) {
504 maybeLogBroadcast(nai, false, type);
505 sendLegacyNetworkBroadcast(nai, false, type);
506 }
507
508 if (!list.isEmpty() && wasFirstNetwork) {
509 if (DBG) log("Other network available for type " + type +
510 ", sending connected broadcast");
511 maybeLogBroadcast(list.get(0), false, type);
512 sendLegacyNetworkBroadcast(list.get(0), false, type);
513 }
514 }
515
516 /** Removes the given network from all legacy type lists. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700517 public void remove(NetworkAgentInfo nai) {
518 if (VDBG) log("Removing agent " + nai);
519 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900520 remove(type, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700521 }
522 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700523
Lorenzo Colittia793a672014-07-31 23:20:17 +0900524 private String naiToString(NetworkAgentInfo nai) {
525 String name = (nai != null) ? nai.name() : "null";
526 String state = (nai.networkInfo != null) ?
527 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
528 "???/???";
529 return name + " " + state;
530 }
531
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700532 public void dump(IndentingPrintWriter pw) {
533 for (int type = 0; type < mTypeLists.length; type++) {
534 if (mTypeLists[type] == null) continue;
535 pw.print(type + " ");
536 pw.increaseIndent();
537 if (mTypeLists[type].size() == 0) pw.println("none");
538 for (NetworkAgentInfo nai : mTypeLists[type]) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900539 pw.println(naiToString(nai));
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700540 }
541 pw.decreaseIndent();
542 }
543 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900544
545 // This class needs its own log method because it has a different TAG.
546 private void log(String s) {
547 Slog.d(TAG, s);
548 }
549
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700550 }
551 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
552
Jeff Sharkey899223b2012-08-04 15:24:58 -0700553 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700554 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800555 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800556
Robert Greenwalte049c232014-04-11 15:53:27 -0700557 NetworkCapabilities netCap = new NetworkCapabilities();
Robert Greenwalt7569f182014-06-08 16:42:59 -0700558 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
559 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700560 mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -0700561 NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
562 NetworkRequestInfo.REQUEST);
563 mNetworkRequests.put(mDefaultRequest, nri);
Robert Greenwalte049c232014-04-11 15:53:27 -0700564
Wink Savillebb08caf2010-09-02 19:23:52 -0700565 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
566 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700567 mHandler = new InternalHandler(handlerThread.getLooper());
568 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700569
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800570 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800571 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
572 String id = Settings.Secure.getString(context.getContentResolver(),
573 Settings.Secure.ANDROID_ID);
574 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700575 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800576 SystemProperties.set("net.hostname", name);
577 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800578 }
579
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700580 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700581 String dns = Settings.Global.getString(context.getContentResolver(),
582 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700583 if (dns == null || dns.length() == 0) {
584 dns = context.getResources().getString(
585 com.android.internal.R.string.config_default_dns_server);
586 }
587 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800588 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
589 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800590 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700591 }
592
Jeremy Joslin79294842014-12-03 17:15:28 -0800593 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
594 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
595
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700596 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700597 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800598 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700599 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700600 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700601 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700602
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700603 try {
604 mPolicyManager.registerListener(mPolicyListener);
605 } catch (RemoteException e) {
606 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700607 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700608 }
609
610 final PowerManager powerManager = (PowerManager) context.getSystemService(
611 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700612 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
613 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
614 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800615 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700616
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700617 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700618
Wink Saville51f456f2013-04-23 14:26:51 -0700619 // TODO: What is the "correct" way to do determine if this is a wifi only device?
620 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
621 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700622 String[] naStrings = context.getResources().getStringArray(
623 com.android.internal.R.array.networkAttributes);
624 for (String naString : naStrings) {
625 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700626 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700627 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700628 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800629 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700630 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700631 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700632 }
Wink Saville51f456f2013-04-23 14:26:51 -0700633 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
634 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
635 n.type);
636 continue;
637 }
Wink Saville975c8482011-04-07 14:23:45 -0700638 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800639 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700640 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700641 continue;
642 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700643 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700644
Wink Saville975c8482011-04-07 14:23:45 -0700645 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700646 mNetworksDefined++;
647 } catch(Exception e) {
648 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700649 }
650 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700651
652 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
653 if (mNetConfigs[TYPE_VPN] == null) {
654 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
655 // don't need to add TYPE_VPN to mNetConfigs.
656 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
657 mNetworksDefined++; // used only in the log() statement below.
658 }
659
Wink Saville5e56bc52013-07-29 15:00:57 -0700660 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700661
Robert Greenwalt50393202011-06-21 17:26:14 -0700662 mProtectedNetworks = new ArrayList<Integer>();
663 int[] protectedNetworks = context.getResources().getIntArray(
664 com.android.internal.R.array.config_protectedNetworks);
665 for (int p : protectedNetworks) {
666 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
667 mProtectedNetworks.add(p);
668 } else {
669 if (DBG) loge("Ignoring protectedNetwork " + p);
670 }
671 }
672
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700673 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
674 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700675
Robert Greenwaltfab501672014-07-23 11:44:01 -0700676 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800677
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700678 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
679
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700680 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700681 IntentFilter intentFilter = new IntentFilter();
682 intentFilter.addAction(Intent.ACTION_USER_STARTING);
683 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
684 mContext.registerReceiverAsUser(
685 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900686
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700687 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700688 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700689 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700690 } catch (RemoteException e) {
691 loge("Error registering observer :" + e);
692 }
693
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700694 if (DBG) {
695 mInetLog = new ArrayList();
696 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700697
698 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
699 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800700
John Spurlockbf991a82013-06-24 14:20:23 -0400701 mDataConnectionStats = new DataConnectionStats(mContext);
702 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400703
Jason Monkdecd2952013-10-10 14:02:51 -0400704 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700705
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400706 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800707 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700708
Robert Greenwalt34524f02014-05-18 16:22:10 -0700709 private synchronized int nextNetworkRequestId() {
710 return mNextNetworkRequestId++;
711 }
712
Paul Jensen31a94f42015-02-13 14:18:39 -0500713 private int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400714 synchronized (mNetworkForNetId) {
715 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
716 int netId = mNextNetId;
717 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
718 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500719 if (!mNetIdInUse.get(netId)) {
720 mNetIdInUse.put(netId, true);
721 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400722 }
723 }
724 }
725 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700726 }
727
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800728 private NetworkState getFilteredNetworkState(int networkType, int uid) {
729 NetworkInfo info = null;
730 LinkProperties lp = null;
731 NetworkCapabilities nc = null;
732 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800733 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800734
735 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
736 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
737 if (nai != null) {
738 synchronized (nai) {
739 info = new NetworkInfo(nai.networkInfo);
740 lp = new LinkProperties(nai.linkProperties);
741 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400742 // Network objects are outwardly immutable so there is no point to duplicating.
743 // Duplicating also precludes sharing socket factories and connection pools.
744 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800745 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800746 }
747 info.setType(networkType);
748 } else {
749 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
750 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
751 info.setIsAvailable(true);
752 lp = new LinkProperties();
753 nc = new NetworkCapabilities();
754 network = null;
755 }
756 info = getFilteredNetworkInfo(info, lp, uid);
757 }
758
Jeff Sharkey32566012014-12-02 18:30:14 -0800759 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400760 }
761
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800762 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
763 if (network == null) {
764 return null;
765 }
766 synchronized (mNetworkForNetId) {
767 return mNetworkForNetId.get(network.netId);
768 }
769 };
770
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900771 private Network[] getVpnUnderlyingNetworks(int uid) {
772 if (!mLockdownEnabled) {
773 int user = UserHandle.getUserId(uid);
774 synchronized (mVpns) {
775 Vpn vpn = mVpns.get(user);
776 if (vpn != null && vpn.appliesToUid(uid)) {
777 return vpn.getUnderlyingNetworks();
778 }
779 }
780 }
781 return null;
782 }
783
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800784 private NetworkState getUnfilteredActiveNetworkState(int uid) {
785 NetworkInfo info = null;
786 LinkProperties lp = null;
787 NetworkCapabilities nc = null;
788 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800789 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800790
791 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800792
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900793 final Network[] networks = getVpnUnderlyingNetworks(uid);
794 if (networks != null) {
795 // getUnderlyingNetworks() returns:
796 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
797 // empty array => the VPN explicitly said "no default network".
798 // non-empty array => the VPN specified one or more default networks; we use the
799 // first one.
800 if (networks.length > 0) {
801 nai = getNetworkAgentInfoForNetwork(networks[0]);
802 } else {
803 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800804 }
805 }
806
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800807 if (nai != null) {
808 synchronized (nai) {
809 info = new NetworkInfo(nai.networkInfo);
810 lp = new LinkProperties(nai.linkProperties);
811 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400812 // Network objects are outwardly immutable so there is no point to duplicating.
813 // Duplicating also precludes sharing socket factories and connection pools.
814 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800815 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800816 }
817 }
818
Jeff Sharkey32566012014-12-02 18:30:14 -0800819 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400820 }
821
822 /**
823 * Check if UID should be blocked from using the network with the given LinkProperties.
824 */
825 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700826 final boolean networkCostly;
827 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700828
Robert Greenwalt12e67352014-05-13 21:41:06 -0700829 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700830 synchronized (mRulesLock) {
831 networkCostly = mMeteredIfaces.contains(iface);
832 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700833 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700834
835 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
836 return true;
837 }
838
839 // no restrictive rules; network is visible
840 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700841 }
842
843 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700844 * Return a filtered {@link NetworkInfo}, potentially marked
845 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800846 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700847 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800848 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
849 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400850 // network is blocked; clone and override state
851 info = new NetworkInfo(info);
852 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900853 if (DBG) {
854 log("returning Blocked NetworkInfo for ifname=" +
855 lp.getInterfaceName() + ", uid=" + uid);
856 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700857 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800858 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700859 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700860 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700861 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700862 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700863 }
864
865 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800866 * Return NetworkInfo for the active (i.e., connected) network interface.
867 * It is assumed that at most one network is active at a time. If more
868 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700869 * @return the info for the active network, or {@code null} if none is
870 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800871 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700872 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700874 enforceAccessPermission();
875 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800876 NetworkState state = getUnfilteredActiveNetworkState(uid);
877 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800878 }
879
Paul Jensen31a94f42015-02-13 14:18:39 -0500880 @Override
881 public Network getActiveNetwork() {
882 enforceAccessPermission();
883 final int uid = Binder.getCallingUid();
884 final int user = UserHandle.getUserId(uid);
885 int vpnNetId = NETID_UNSET;
886 synchronized (mVpns) {
887 final Vpn vpn = mVpns.get(user);
888 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
889 }
890 NetworkAgentInfo nai;
891 if (vpnNetId != NETID_UNSET) {
892 synchronized (mNetworkForNetId) {
893 nai = mNetworkForNetId.get(vpnNetId);
894 }
895 if (nai != null) return nai.network;
896 }
897 nai = getDefaultNetwork();
898 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
899 return nai != null ? nai.network : null;
900 }
901
Wink Saville948282b2013-08-29 08:55:16 -0700902 /**
903 * Find the first Provisioning network.
904 *
905 * @return NetworkInfo or null if none.
906 */
907 private NetworkInfo getProvisioningNetworkInfo() {
908 enforceAccessPermission();
909
910 // Find the first Provisioning Network
911 NetworkInfo provNi = null;
912 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700913 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700914 provNi = ni;
915 break;
916 }
917 }
918 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
919 return provNi;
920 }
921
922 /**
923 * Find the first Provisioning network or the ActiveDefaultNetwork
924 * if there is no Provisioning network
925 *
926 * @return NetworkInfo or null if none.
927 */
928 @Override
929 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
930 enforceAccessPermission();
931
932 NetworkInfo provNi = getProvisioningNetworkInfo();
933 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800934 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700935 }
936 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
937 return provNi;
938 }
939
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700940 public NetworkInfo getActiveNetworkInfoUnfiltered() {
941 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800942 final int uid = Binder.getCallingUid();
943 NetworkState state = getUnfilteredActiveNetworkState(uid);
944 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700945 }
946
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700947 @Override
948 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
949 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800950 NetworkState state = getUnfilteredActiveNetworkState(uid);
951 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700952 }
953
954 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800955 public NetworkInfo getNetworkInfo(int networkType) {
956 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700957 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900958 if (getVpnUnderlyingNetworks(uid) != null) {
959 // A VPN is active, so we may need to return one of its underlying networks. This
960 // information is not available in LegacyTypeTracker, so we have to get it from
961 // getUnfilteredActiveNetworkState.
962 NetworkState state = getUnfilteredActiveNetworkState(uid);
963 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
964 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
965 }
966 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800967 NetworkState state = getFilteredNetworkState(networkType, uid);
968 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800969 }
970
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800971 @Override
972 public NetworkInfo getNetworkInfoForNetwork(Network network) {
973 enforceAccessPermission();
974 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700975 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800976 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
977 if (nai != null) {
978 synchronized (nai) {
979 info = new NetworkInfo(nai.networkInfo);
980 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700981 }
982 }
983 return info;
984 }
985
986 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800987 public NetworkInfo[] getAllNetworkInfo() {
988 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700989 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -0400990 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
991 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800992 NetworkInfo info = getNetworkInfo(networkType);
993 if (info != null) {
994 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700995 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800996 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700997 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 }
999
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001000 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001001 public Network getNetworkForType(int networkType) {
1002 enforceAccessPermission();
1003 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001004 NetworkState state = getFilteredNetworkState(networkType, uid);
1005 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1006 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001007 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001008 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001009 }
1010
1011 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001012 public Network[] getAllNetworks() {
1013 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001014 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001015 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001016 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001017 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001018 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001019 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001020 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001021 }
1022
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001023 private NetworkCapabilities getNetworkCapabilitiesAndValidation(NetworkAgentInfo nai) {
1024 if (nai != null) {
1025 synchronized (nai) {
1026 if (nai.created) {
1027 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001028 if (nai.lastValidated) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001029 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1030 } else {
1031 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1032 }
1033 return nc;
1034 }
1035 }
1036 }
1037 return null;
1038 }
1039
1040 @Override
1041 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1042 // The basic principle is: if an app's traffic could possibly go over a
1043 // network, without the app doing anything multinetwork-specific,
1044 // (hence, by "default"), then include that network's capabilities in
1045 // the array.
1046 //
1047 // In the normal case, app traffic only goes over the system's default
1048 // network connection, so that's the only network returned.
1049 //
1050 // With a VPN in force, some app traffic may go into the VPN, and thus
1051 // over whatever underlying networks the VPN specifies, while other app
1052 // traffic may go over the system default network (e.g.: a split-tunnel
1053 // VPN, or an app disallowed by the VPN), so the set of networks
1054 // returned includes the VPN's underlying networks and the system
1055 // default.
1056 enforceAccessPermission();
1057
1058 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1059
1060 NetworkAgentInfo nai = getDefaultNetwork();
1061 NetworkCapabilities nc = getNetworkCapabilitiesAndValidation(getDefaultNetwork());
1062 if (nc != null) {
1063 result.put(nai.network, nc);
1064 }
1065
1066 if (!mLockdownEnabled) {
1067 synchronized (mVpns) {
1068 Vpn vpn = mVpns.get(userId);
1069 if (vpn != null) {
1070 Network[] networks = vpn.getUnderlyingNetworks();
1071 if (networks != null) {
1072 for (Network network : networks) {
1073 nai = getNetworkAgentInfoForNetwork(network);
1074 nc = getNetworkCapabilitiesAndValidation(nai);
1075 if (nc != null) {
1076 result.put(nai.network, nc);
1077 }
1078 }
1079 }
1080 }
1081 }
1082 }
1083
1084 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1085 out = result.values().toArray(out);
1086 return out;
1087 }
1088
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001089 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001090 public boolean isNetworkSupported(int networkType) {
1091 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001092 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001093 }
1094
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001095 /**
1096 * Return LinkProperties for the active (i.e., connected) default
1097 * network interface. It is assumed that at most one default network
1098 * is active at a time. If more than one is active, it is indeterminate
1099 * which will be returned.
1100 * @return the ip properties for the active network, or {@code null} if
1101 * none is active
1102 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001103 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001104 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001105 enforceAccessPermission();
1106 final int uid = Binder.getCallingUid();
1107 NetworkState state = getUnfilteredActiveNetworkState(uid);
1108 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001109 }
1110
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001111 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001112 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001113 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001114 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1115 if (nai != null) {
1116 synchronized (nai) {
1117 return new LinkProperties(nai.linkProperties);
1118 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001119 }
1120 return null;
1121 }
1122
Robert Greenwalt12e67352014-05-13 21:41:06 -07001123 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001124 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001125 public LinkProperties getLinkProperties(Network network) {
1126 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001127 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001128 if (nai != null) {
1129 synchronized (nai) {
1130 return new LinkProperties(nai.linkProperties);
1131 }
1132 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001133 return null;
1134 }
1135
1136 @Override
1137 public NetworkCapabilities getNetworkCapabilities(Network network) {
1138 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001139 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001140 if (nai != null) {
1141 synchronized (nai) {
1142 return new NetworkCapabilities(nai.networkCapabilities);
1143 }
1144 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001145 return null;
1146 }
1147
1148 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001149 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001150 // Require internal since we're handing out IMSI details
1151 enforceConnectivityInternalPermission();
1152
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001153 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001154 for (Network network : getAllNetworks()) {
1155 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1156 if (nai != null) {
1157 synchronized (nai) {
1158 final String subscriberId = (nai.networkMisc != null)
1159 ? nai.networkMisc.subscriberId : null;
1160 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1161 nai.networkCapabilities, network, subscriberId, null));
1162 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001163 }
1164 }
1165 return result.toArray(new NetworkState[result.size()]);
1166 }
1167
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001168 @Override
1169 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1170 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001171 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001172 final long token = Binder.clearCallingIdentity();
1173 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001174 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1175 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001176 try {
1177 return mPolicyManager.getNetworkQuotaInfo(state);
1178 } catch (RemoteException e) {
1179 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001180 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001181 return null;
1182 } finally {
1183 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001184 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001185 }
1186
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001187 @Override
1188 public boolean isActiveNetworkMetered() {
1189 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001190 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001191 final long token = Binder.clearCallingIdentity();
1192 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001193 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001194 } finally {
1195 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001196 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001197 }
1198
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001199 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1200 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1201 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001202 try {
1203 return mPolicyManager.isNetworkMetered(state);
1204 } catch (RemoteException e) {
1205 }
1206 }
1207 return false;
1208 }
1209
Jeff Sharkey216c1812012-08-05 14:29:23 -07001210 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1211 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001212 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001213 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001214 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001215 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001216 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001217
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001218 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001219 * Ensure that a network route exists to deliver traffic to the specified
1220 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001221 * @param networkType the type of the network over which traffic to the
1222 * specified host is to be routed
1223 * @param hostAddress the IP address of the host to which the route is
1224 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001225 * @return {@code true} on success, {@code false} on failure
1226 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001227 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001228 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001229 if (mProtectedNetworks.contains(networkType)) {
1230 enforceConnectivityInternalPermission();
1231 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001232
Chad Brubakerc0234532014-02-14 13:24:29 -08001233 InetAddress addr;
1234 try {
1235 addr = InetAddress.getByAddress(hostAddress);
1236 } catch (UnknownHostException e) {
1237 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1238 return false;
1239 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001240
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001241 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001242 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001243 return false;
1244 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001245
1246 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1247 if (nai == null) {
1248 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1249 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1250 } else {
1251 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1252 }
1253 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001254 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001255
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001256 DetailedState netState;
1257 synchronized (nai) {
1258 netState = nai.networkInfo.getDetailedState();
1259 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001260
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001261 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001262 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001263 log("requestRouteToHostAddress on down network "
1264 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001265 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001266 }
1267 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001268 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001269
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001270 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001271 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001272 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001273 LinkProperties lp;
1274 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001275 synchronized (nai) {
1276 lp = nai.linkProperties;
1277 netId = nai.network.netId;
1278 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001279 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001280 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1281 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001282 } finally {
1283 Binder.restoreCallingIdentity(token);
1284 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001285 }
1286
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001287 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001288 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001289 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001290 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001291 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001292 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001293 if (bestRoute.getGateway().equals(addr)) {
1294 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001295 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001296 } else {
1297 // if we will connect to this through another route, add a direct route
1298 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001299 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001300 }
1301 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001302 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001303 try {
1304 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1305 } catch (Exception e) {
1306 // never crash - catch them all
1307 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001308 return false;
1309 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001310 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001311 }
1312
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001313 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1314 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001315 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001316 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001317 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001318 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001319 }
1320
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001321 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001322 // skip update when we've already applied rules
1323 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1324 if (oldRules == uidRules) return;
1325
1326 mUidRules.put(uid, uidRules);
1327 }
1328
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001329 // TODO: notify UID when it has requested targeted updates
1330 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001331
1332 @Override
1333 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001334 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001335 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001336 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001337 }
1338
1339 synchronized (mRulesLock) {
1340 mMeteredIfaces.clear();
1341 for (String iface : meteredIfaces) {
1342 mMeteredIfaces.add(iface);
1343 }
1344 }
1345 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001346
1347 @Override
1348 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1349 // caller is NPMS, since we only register with them
1350 if (LOGD_RULES) {
1351 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1352 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001353 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001354 };
1355
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001356 private void enforceInternetPermission() {
1357 mContext.enforceCallingOrSelfPermission(
1358 android.Manifest.permission.INTERNET,
1359 "ConnectivityService");
1360 }
1361
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001362 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001363 mContext.enforceCallingOrSelfPermission(
1364 android.Manifest.permission.ACCESS_NETWORK_STATE,
1365 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001366 }
1367
1368 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001369 mContext.enforceCallingOrSelfPermission(
1370 android.Manifest.permission.CHANGE_NETWORK_STATE,
1371 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001372 }
1373
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001374 private void enforceTetherAccessPermission() {
1375 mContext.enforceCallingOrSelfPermission(
1376 android.Manifest.permission.ACCESS_NETWORK_STATE,
1377 "ConnectivityService");
1378 }
1379
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001380 private void enforceConnectivityInternalPermission() {
1381 mContext.enforceCallingOrSelfPermission(
1382 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1383 "ConnectivityService");
1384 }
1385
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001386 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001387 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001388 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001389 }
1390
1391 private void sendInetConditionBroadcast(NetworkInfo info) {
1392 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1393 }
1394
Wink Saville628b0852011-08-04 15:01:58 -07001395 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001396 if (mLockdownTracker != null) {
1397 info = mLockdownTracker.augmentNetworkInfo(info);
1398 }
1399
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001400 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001401 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001402 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001403 if (info.isFailover()) {
1404 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1405 info.setFailover(false);
1406 }
1407 if (info.getReason() != null) {
1408 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1409 }
1410 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001411 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1412 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001413 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001414 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001415 return intent;
1416 }
1417
1418 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1419 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1420 }
1421
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001422 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001423 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1424 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1425 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001426 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001427 final long ident = Binder.clearCallingIdentity();
1428 try {
1429 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1430 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1431 } finally {
1432 Binder.restoreCallingIdentity(ident);
1433 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001434 }
1435
Mike Lockwood0f79b542009-08-14 14:18:49 -04001436 private void sendStickyBroadcast(Intent intent) {
1437 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001438 if (!mSystemReady) {
1439 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001440 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001441 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001442 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001443 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001444 }
1445
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001446 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001447 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1448 final IBatteryStats bs = BatteryStatsService.getService();
1449 try {
1450 NetworkInfo ni = intent.getParcelableExtra(
1451 ConnectivityManager.EXTRA_NETWORK_INFO);
1452 bs.noteConnectivityChanged(intent.getIntExtra(
1453 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1454 ni != null ? ni.getState().toString() : "?");
1455 } catch (RemoteException e) {
1456 }
1457 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001458 try {
1459 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1460 } finally {
1461 Binder.restoreCallingIdentity(ident);
1462 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001463 }
1464 }
1465
1466 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001467 loadGlobalProxy();
1468
Mike Lockwood0f79b542009-08-14 14:18:49 -04001469 synchronized(this) {
1470 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001471 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001472 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001473 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001474 }
1475 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001476 // load the global proxy at startup
1477 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001478
1479 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1480 // for user to unlock device.
1481 if (!updateLockdownVpn()) {
1482 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1483 mContext.registerReceiver(mUserPresentReceiver, filter);
1484 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001485
1486 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001487
1488 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001489 }
1490
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001491 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1492 @Override
1493 public void onReceive(Context context, Intent intent) {
1494 // Try creating lockdown tracker, since user present usually means
1495 // unlocked keystore.
1496 if (updateLockdownVpn()) {
1497 mContext.unregisterReceiver(this);
1498 }
1499 }
1500 };
1501
Wink Savilled747cbc2013-08-07 16:22:47 -07001502 /** @hide */
1503 @Override
1504 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1505 enforceConnectivityInternalPermission();
1506 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001507// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001508 }
1509
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001510 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001511 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001512 *
1513 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001514 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001515 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001516 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1517 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001518
1519 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001520 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001521
Robert Greenwalt7b816022014-04-18 15:25:25 -07001522 if (networkAgent.networkCapabilities.hasTransport(
1523 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001524 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1525 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001526 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001527 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001528 } else if (networkAgent.networkCapabilities.hasTransport(
1529 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001530 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1531 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001532 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001533 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001534 } else {
1535 // do not track any other networks
1536 timeout = 0;
1537 }
1538
Robert Greenwalt7b816022014-04-18 15:25:25 -07001539 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001540 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001541 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001542 } catch (Exception e) {
1543 // You shall not crash!
1544 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001545 }
1546 }
1547 }
1548
1549 /**
1550 * Remove data activity tracking when network disconnects.
1551 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001552 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1553 final String iface = networkAgent.linkProperties.getInterfaceName();
1554 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001555
Robert Greenwalt7b816022014-04-18 15:25:25 -07001556 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1557 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001558 try {
1559 // the call fails silently if no idletimer setup for this interface
1560 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001561 } catch (Exception e) {
1562 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001563 }
1564 }
1565 }
1566
1567 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001568 * Reads the network specific MTU size from reources.
1569 * and set it on it's iface.
1570 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001571 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1572 final String iface = newLp.getInterfaceName();
1573 final int mtu = newLp.getMtu();
1574 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1575 if (VDBG) log("identical MTU - not setting");
1576 return;
1577 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001578
Robert Greenwalt43074032014-08-15 17:53:05 -07001579 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001580 loge("Unexpected mtu value: " + mtu + ", " + iface);
1581 return;
1582 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001583
w1997615afd812014-08-05 15:18:11 -07001584 // Cannot set MTU without interface name
1585 if (TextUtils.isEmpty(iface)) {
1586 loge("Setting MTU size with null iface.");
1587 return;
1588 }
1589
Robert Greenwalt7b816022014-04-18 15:25:25 -07001590 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001591 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001592 mNetd.setMtu(iface, mtu);
1593 } catch (Exception e) {
1594 Slog.e(TAG, "exception in setMtu()" + e);
1595 }
1596 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001597
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001598 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001599
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001600 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1601 if (isDefaultNetwork(nai) == false) {
1602 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001603 }
1604
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001605 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1606 String[] values = null;
1607 if (tcpBufferSizes != null) {
1608 values = tcpBufferSizes.split(",");
1609 }
1610
1611 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001612 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001613 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1614 values = tcpBufferSizes.split(",");
1615 }
1616
1617 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1618
1619 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001620 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001621
1622 final String prefix = "/sys/kernel/ipv4/tcp_";
1623 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1624 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1625 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1626 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1627 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1628 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1629 mCurrentTcpBufferSizes = tcpBufferSizes;
1630 } catch (IOException e) {
1631 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001632 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001633
1634 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1635 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1636 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1637 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1638 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1639 if (rwndValue != 0) {
1640 SystemProperties.set(sysctlKey, rwndValue.toString());
1641 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001642 }
1643
Mattias Falk8b47b362011-08-23 14:15:13 +02001644 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001645 /*
1646 * Tell the VMs to toss their DNS caches
1647 */
1648 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1649 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001650 /*
1651 * Connectivity events can happen before boot has completed ...
1652 */
1653 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001654 final long ident = Binder.clearCallingIdentity();
1655 try {
1656 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1657 } finally {
1658 Binder.restoreCallingIdentity(ident);
1659 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001660 }
1661
Robert Greenwalt562cc542014-05-15 18:07:26 -07001662 @Override
1663 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001664 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1665 NETWORK_RESTORE_DELAY_PROP_NAME);
1666 if(restoreDefaultNetworkDelayStr != null &&
1667 restoreDefaultNetworkDelayStr.length() != 0) {
1668 try {
1669 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1670 } catch (NumberFormatException e) {
1671 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001672 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001673 // if the system property isn't set, use the value for the apn type
1674 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1675
1676 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1677 (mNetConfigs[networkType] != null)) {
1678 ret = mNetConfigs[networkType].restoreTime;
1679 }
1680 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001681 }
1682
1683 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001684 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1685 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001686 if (mContext.checkCallingOrSelfPermission(
1687 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001688 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001689 pw.println("Permission Denial: can't dump ConnectivityService " +
1690 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1691 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001692 return;
1693 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001694
Robert Greenwalta67be032014-05-16 15:49:14 -07001695 pw.println("NetworkFactories for:");
1696 pw.increaseIndent();
1697 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1698 pw.println(nfi.name);
1699 }
1700 pw.decreaseIndent();
1701 pw.println();
1702
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001703 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1704 pw.print("Active default network: ");
1705 if (defaultNai == null) {
1706 pw.println("none");
1707 } else {
1708 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001709 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001710 pw.println();
1711
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001712 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001713 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001714 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1715 pw.println(nai.toString());
1716 pw.increaseIndent();
1717 pw.println("Requests:");
1718 pw.increaseIndent();
1719 for (int i = 0; i < nai.networkRequests.size(); i++) {
1720 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001721 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001722 pw.decreaseIndent();
1723 pw.println("Lingered:");
1724 pw.increaseIndent();
1725 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1726 pw.decreaseIndent();
1727 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001728 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001729 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001730 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001731
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001732 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001733 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001734 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1735 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001736 }
1737 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001738 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001739
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001740 pw.println("mLegacyTypeTracker:");
1741 pw.increaseIndent();
1742 mLegacyTypeTracker.dump(pw);
1743 pw.decreaseIndent();
1744 pw.println();
1745
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001746 synchronized (this) {
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001747 pw.println("NetworkTransitionWakeLock is currently " +
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001748 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1749 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1750 }
1751 pw.println();
1752
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001753 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001754
1755 if (mInetLog != null) {
1756 pw.println();
1757 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001758 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001759 for(int i = 0; i < mInetLog.size(); i++) {
1760 pw.println(mInetLog.get(i));
1761 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001762 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001763 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001764 }
1765
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001766 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001767 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001768 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001769 if (officialNai != null && officialNai.equals(nai)) return true;
1770 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001771 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001772 " - " + nai);
1773 }
1774 return false;
1775 }
1776
Paul Jensenc8b9a742014-09-30 15:37:41 -04001777 private boolean isRequest(NetworkRequest request) {
1778 return mNetworkRequests.get(request).isRequest;
1779 }
1780
Robert Greenwalt42acef32009-08-12 16:08:25 -07001781 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001782 private class NetworkStateTrackerHandler extends Handler {
1783 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001784 super(looper);
1785 }
1786
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001787 @Override
1788 public void handleMessage(Message msg) {
1789 NetworkInfo info;
1790 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001791 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001792 handleAsyncChannelHalfConnect(msg);
1793 break;
1794 }
1795 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1796 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1797 if (nai != null) nai.asyncChannel.disconnect();
1798 break;
1799 }
1800 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1801 handleAsyncChannelDisconnected(msg);
1802 break;
1803 }
1804 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1805 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1806 if (nai == null) {
1807 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1808 } else {
1809 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001810 }
1811 break;
1812 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001813 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1814 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1815 if (nai == null) {
1816 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1817 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001818 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001819 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001820 "; created=" + nai.created);
1821 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001822 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001823 synchronized (nai) {
1824 nai.linkProperties = (LinkProperties)msg.obj;
1825 }
Paul Jenseneec75412014-08-04 12:21:19 -04001826 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001827 }
1828 break;
1829 }
1830 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1831 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1832 if (nai == null) {
1833 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1834 break;
1835 }
1836 info = (NetworkInfo) msg.obj;
1837 updateNetworkInfo(nai, info);
1838 break;
1839 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001840 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1841 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1842 if (nai == null) {
1843 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1844 break;
1845 }
1846 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001847 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001848 break;
1849 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001850 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1851 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1852 if (nai == null) {
1853 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1854 break;
1855 }
1856 try {
1857 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001858 } catch (Exception e) {
1859 // Never crash!
1860 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001861 }
1862 break;
1863 }
1864 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1865 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1866 if (nai == null) {
1867 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1868 break;
1869 }
1870 try {
1871 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001872 } catch (Exception e) {
1873 // Never crash!
1874 loge("Exception in removeVpnUidRanges: " + e);
1875 }
1876 break;
1877 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001878 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1879 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1880 if (nai == null) {
1881 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1882 break;
1883 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001884 if (nai.created && !nai.networkMisc.explicitlySelected) {
1885 loge("ERROR: created network explicitly selected.");
1886 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001887 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001888 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001889 break;
1890 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001891 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001892 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001893 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001894 boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001895 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001896 if (valid) {
1897 if (DBG) log("Validated " + nai.name());
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001898 if (!nai.everValidated) {
1899 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001900 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1901 ReapUnvalidatedNetworks.REAP);
1902 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001903 sendUpdatedScoreToFactories(nai);
1904 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001905 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001906 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001907 // Let the NetworkAgent know the state of its network
1908 nai.asyncChannel.sendMessage(
1909 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1910 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1911 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001912
1913 // TODO: trigger a NetworkCapabilities update so that the dialog can know
1914 // that the network is now validated and close itself.
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001915 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001916 break;
1917 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001918 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001919 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001920 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1921 handleLingerComplete(nai);
1922 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001923 break;
1924 }
Paul Jensen869868be2014-05-15 10:33:05 -04001925 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001926 if (msg.arg1 == 0) {
1927 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1928 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04001929 NetworkAgentInfo nai = null;
1930 synchronized (mNetworkForNetId) {
1931 nai = mNetworkForNetId.get(msg.arg2);
1932 }
1933 if (nai == null) {
1934 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1935 break;
1936 }
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001937 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
1938 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04001939 }
Paul Jensen869868be2014-05-15 10:33:05 -04001940 break;
1941 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001942 }
1943 }
1944 }
1945
Paul Jensen0cc17322014-11-25 15:26:53 -05001946 // Cancel any lingering so the linger timeout doesn't teardown a network.
1947 // This should be called when a network begins satisfying a NetworkRequest.
1948 // Note: depending on what state the NetworkMonitor is in (e.g.,
1949 // if it's awaiting captive portal login, or if validation failed), this
1950 // may trigger a re-evaluation of the network.
1951 private void unlinger(NetworkAgentInfo nai) {
1952 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05001953 // If network has never been validated, it cannot have been lingered, so don't bother
1954 // needlessly triggering a re-evaluation.
1955 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05001956 nai.networkLingered.clear();
1957 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
1958 }
1959
Robert Greenwalt7b816022014-04-18 15:25:25 -07001960 private void handleAsyncChannelHalfConnect(Message msg) {
1961 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07001962 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001963 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1964 if (VDBG) log("NetworkFactory connected");
1965 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07001966 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07001967 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07001968 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07001969 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04001970 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001971 }
1972 } else {
1973 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07001974 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001975 }
1976 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
1977 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1978 if (VDBG) log("NetworkAgent connected");
1979 // A network agent has requested a connection. Establish the connection.
1980 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
1981 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
1982 } else {
1983 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07001984 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07001985 if (nai != null) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001986 synchronized (mNetworkForNetId) {
1987 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05001988 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001989 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09001990 // Just in case.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001991 mLegacyTypeTracker.remove(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07001992 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001993 }
1994 }
1995 }
Paul Jensen0cc17322014-11-25 15:26:53 -05001996
Robert Greenwalt7b816022014-04-18 15:25:25 -07001997 private void handleAsyncChannelDisconnected(Message msg) {
1998 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1999 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002000 if (DBG) {
2001 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2002 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002003 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002004 if (nai.created) {
2005 // Tell netd to clean up the configuration for this network
2006 // (routing rules, DNS, etc).
2007 try {
2008 mNetd.removeNetwork(nai.network.netId);
2009 } catch (Exception e) {
2010 loge("Exception removing network: " + e);
2011 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002012 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002013 // TODO - if we move the logic to the network agent (have them disconnect
2014 // because they lost all their requests or because their score isn't good)
2015 // then they would disconnect organically, report their new state and then
2016 // disconnect the channel.
2017 if (nai.networkInfo.isConnected()) {
2018 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2019 null, null);
2020 }
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002021 if (isDefaultNetwork(nai)) {
2022 mDefaultInetConditionPublished = 0;
2023 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002024 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002025 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002026 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002027 mNetworkAgentInfos.remove(msg.replyTo);
2028 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002029 mLegacyTypeTracker.remove(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002030 synchronized (mNetworkForNetId) {
2031 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002032 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002033 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002034 // Since we've lost the network, go through all the requests that
2035 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002036 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002037 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002038 for (int i = 0; i < nai.networkRequests.size(); i++) {
2039 NetworkRequest request = nai.networkRequests.valueAt(i);
2040 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2041 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002042 if (DBG) {
2043 log("Checking for replacement network to handle request " + request );
2044 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002045 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002047 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002048 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2049 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002050 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002051 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002052 alternative = existing;
2053 }
2054 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002055 if (alternative != null) {
2056 if (DBG) log(" found replacement in " + alternative.name());
2057 if (!toActivate.contains(alternative)) {
2058 toActivate.add(alternative);
2059 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002060 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002061 }
2062 }
2063 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2064 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002065 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002066 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002067 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002068 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002069 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002070 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2071 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002072 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002073 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302074 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2075 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002076 }
2077
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002078 // If this method proves to be too slow then we can maintain a separate
2079 // pendingIntent => NetworkRequestInfo map.
2080 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2081 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2082 Intent intent = pendingIntent.getIntent();
2083 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2084 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2085 if (existingPendingIntent != null &&
2086 existingPendingIntent.getIntent().filterEquals(intent)) {
2087 return entry.getValue();
2088 }
2089 }
2090 return null;
2091 }
2092
2093 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2094 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2095
2096 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2097 if (existingRequest != null) { // remove the existing request.
2098 if (DBG) log("Replacing " + existingRequest.request + " with "
2099 + nri.request + " because their intents matched.");
2100 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2101 }
2102 handleRegisterNetworkRequest(msg);
2103 }
2104
Robert Greenwalt9258c642014-03-26 16:47:06 -07002105 private void handleRegisterNetworkRequest(Message msg) {
2106 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002107
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002108 mNetworkRequests.put(nri.request, nri);
2109
Paul Jensen0cc17322014-11-25 15:26:53 -05002110 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2111
Robert Greenwalt9258c642014-03-26 16:47:06 -07002112 // Check for the best currently alive network that satisfies this request
2113 NetworkAgentInfo bestNetwork = null;
2114 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002115 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002116 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002117 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002118 if (!nri.isRequest) {
2119 // Not setting bestNetwork here as a listening NetworkRequest may be
2120 // satisfied by multiple Networks. Instead the request is added to
2121 // each satisfying Network and notified about each.
2122 network.addRequest(nri.request);
2123 notifyNetworkCallback(network, nri);
2124 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002125 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002126 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002127 }
2128 }
2129 }
2130 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002131 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002132 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002133 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002134 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002135 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002136 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002137 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2138 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002139 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002140
Lorenzo Colittia793a672014-07-31 23:20:17 +09002141 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002142 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002143 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002144 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002145 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002146 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002147 }
2148 }
2149 }
2150
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002151 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2152 int callingUid) {
2153 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2154 if (nri != null) {
2155 handleReleaseNetworkRequest(nri.request, callingUid);
2156 }
2157 }
2158
Paul Jensen99364842014-12-09 11:43:45 -05002159 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2160 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2161 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2162 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2163 private boolean unneeded(NetworkAgentInfo nai) {
2164 if (!nai.created || nai.isVPN()) return false;
2165 boolean unneeded = true;
2166 if (nai.everValidated) {
2167 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2168 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2169 try {
2170 if (isRequest(nr)) unneeded = false;
2171 } catch (Exception e) {
2172 loge("Request " + nr + " not found in mNetworkRequests.");
2173 loge(" it came from request list of " + nai.name());
2174 }
2175 }
2176 } else {
2177 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2178 // If this Network is already the highest scoring Network for a request, or if
2179 // there is hope for it to become one if it validated, then it is needed.
2180 if (nri.isRequest && nai.satisfies(nri.request) &&
2181 (nai.networkRequests.get(nri.request.requestId) != null ||
2182 // Note that this catches two important cases:
2183 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2184 // is currently satisfying the request. This is desirable when
2185 // cellular ends up validating but WiFi does not.
2186 // 2. Unvalidated WiFi will not be reaped when validated cellular
2187 // is currently satsifying the request. This is desirable when
2188 // WiFi ends up validating and out scoring cellular.
2189 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2190 nai.getCurrentScoreAsValidated())) {
2191 unneeded = false;
2192 break;
2193 }
2194 }
2195 }
2196 return unneeded;
2197 }
2198
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002199 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2200 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002201 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002202 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002203 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2204 return;
2205 }
2206 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002207 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002208 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002209 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002210 // Find all networks that are satisfying this request and remove the request
2211 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002212 // TODO - it's my understanding that for a request there is only a single
2213 // network satisfying it, so this loop is wasteful
2214 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002215 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2216 if (nai.networkRequests.get(nri.request.requestId) != null) {
2217 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002218 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002219 log(" Removing from current network " + nai.name() +
2220 ", leaving " + nai.networkRequests.size() +
2221 " requests.");
2222 }
Paul Jensen99364842014-12-09 11:43:45 -05002223 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002224 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002225 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002226 } else {
2227 // suspect there should only be one pass through here
2228 // but if any were kept do the check below
2229 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002230 }
2231 }
2232 }
2233
Robert Greenwalt51481852015-01-08 14:43:31 -08002234 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2235 if (nai != null) {
2236 mNetworkForRequestId.remove(nri.request.requestId);
2237 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002238 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002239 // that a network connected to serve it, even though the network was already
2240 // connected. Now that this request has gone away, we might have to pretend
2241 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002242 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002243 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2244 boolean doRemove = true;
2245 if (wasKept) {
2246 // check if any of the remaining requests for this network are for the
2247 // same legacy type - if so, don't remove the nai
2248 for (int i = 0; i < nai.networkRequests.size(); i++) {
2249 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2250 if (otherRequest.legacyType == nri.request.legacyType &&
2251 isRequest(otherRequest)) {
2252 if (DBG) log(" still have other legacy request - leaving");
2253 doRemove = false;
2254 }
2255 }
2256 }
2257
2258 if (doRemove) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002259 mLegacyTypeTracker.remove(nri.request.legacyType, nai);
2260 }
2261 }
2262
Robert Greenwalta67be032014-05-16 15:49:14 -07002263 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002264 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2265 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002266 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002267 } else {
2268 // listens don't have a singular affectedNetwork. Check all networks to see
2269 // if this listen request applies and remove it.
2270 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2271 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002272 }
2273 }
2274 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2275 }
2276 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002277
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002278 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2279 enforceConnectivityInternalPermission();
2280 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2281 accept ? 1 : 0, always ? 1: 0, network));
2282 }
2283
2284 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2285 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2286 " accept=" + accept + " always=" + always);
2287
2288 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2289 if (nai == null) {
2290 // Nothing to do.
2291 return;
2292 }
2293
2294 if (nai.everValidated) {
2295 // The network validated while the dialog box was up. Don't make any changes. There's a
2296 // TODO in the dialog code to make it go away if the network validates; once that's
2297 // implemented, taking action here will be confusing.
2298 return;
2299 }
2300
2301 if (!nai.networkMisc.explicitlySelected) {
2302 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2303 }
2304
2305 if (accept != nai.networkMisc.acceptUnvalidated) {
2306 int oldScore = nai.getCurrentScore();
2307 nai.networkMisc.acceptUnvalidated = accept;
2308 rematchAllNetworksAndRequests(nai, oldScore);
2309 sendUpdatedScoreToFactories(nai);
2310 }
2311
2312 if (always) {
2313 nai.asyncChannel.sendMessage(
2314 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2315 }
2316
2317 // TODO: should we also disconnect from the network if accept is false?
2318 }
2319
2320 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2321 mHandler.sendMessageDelayed(
2322 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2323 PROMPT_UNVALIDATED_DELAY_MS);
2324 }
2325
2326 private void handlePromptUnvalidated(Network network) {
2327 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2328
2329 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2330 // we haven't already been told to switch to it regardless of whether it validated or not.
2331 if (nai == null || nai.everValidated ||
2332 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2333 return;
2334 }
2335
2336 // TODO: What should we do if we've already switched to this network because we had no
2337 // better option? There are two obvious alternatives.
2338 //
2339 // 1. Decide that there's no point prompting because this is our only usable network.
2340 // However, because we didn't prompt, if later on a validated network comes along, we'll
2341 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2342 // unvalidated network - or b) prompt the user at that later time - bad because the user
2343 // might not understand why they are now being prompted.
2344 //
2345 // 2. Always prompt the user, even if we have no other network to use. The user could then
2346 // try to find an alternative network to join (remember, if we got here, then the user
2347 // selected this network manually). This is bad because the prompt isn't really very
2348 // useful.
2349 //
2350 // For now we do #1, but we can revisit that later.
2351 if (isDefaultNetwork(nai)) {
2352 return;
2353 }
2354
2355 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2356 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2357 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2358 intent.setClassName("com.android.settings",
2359 "com.android.settings.wifi.WifiNoInternetDialog");
2360 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2361 }
2362
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002363 private class InternalHandler extends Handler {
2364 public InternalHandler(Looper looper) {
2365 super(looper);
2366 }
2367
2368 @Override
2369 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002370 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002371 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002372 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002373 String causedBy = null;
2374 synchronized (ConnectivityService.this) {
2375 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2376 mNetTransitionWakeLock.isHeld()) {
2377 mNetTransitionWakeLock.release();
2378 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002379 } else {
2380 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002381 }
2382 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002383 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2384 log("Failed to find a new network - expiring NetTransition Wakelock");
2385 } else {
2386 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2387 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002388 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002389 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002390 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002391 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002392 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002393 break;
2394 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002395 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002396 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002397 sendStickyBroadcast(intent);
2398 break;
2399 }
Jason Monkdecd2952013-10-10 14:02:51 -04002400 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002401 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002402 break;
2403 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002404 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002405 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2406 break;
2407 }
2408 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2409 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002410 break;
2411 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002412 case EVENT_REGISTER_NETWORK_AGENT: {
2413 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2414 break;
2415 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002416 case EVENT_REGISTER_NETWORK_REQUEST:
2417 case EVENT_REGISTER_NETWORK_LISTENER: {
2418 handleRegisterNetworkRequest(msg);
2419 break;
2420 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002421 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2422 handleRegisterNetworkRequestWithIntent(msg);
2423 break;
2424 }
2425 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2426 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2427 break;
2428 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002429 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002430 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002431 break;
2432 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002433 case EVENT_SET_ACCEPT_UNVALIDATED: {
2434 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2435 break;
2436 }
2437 case EVENT_PROMPT_UNVALIDATED: {
2438 handlePromptUnvalidated((Network) msg.obj);
2439 break;
2440 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002441 case EVENT_SYSTEM_READY: {
2442 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2443 nai.networkMonitor.systemReady = true;
2444 }
2445 break;
2446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002447 }
2448 }
2449 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002450
2451 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002452 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002453 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002454 if (isTetheringSupported()) {
2455 return mTethering.tether(iface);
2456 } else {
2457 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2458 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002459 }
2460
2461 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002462 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002463 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002464
2465 if (isTetheringSupported()) {
2466 return mTethering.untether(iface);
2467 } else {
2468 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2469 }
2470 }
2471
2472 // javadoc from interface
2473 public int getLastTetherError(String iface) {
2474 enforceTetherAccessPermission();
2475
2476 if (isTetheringSupported()) {
2477 return mTethering.getLastTetherError(iface);
2478 } else {
2479 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2480 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002481 }
2482
2483 // TODO - proper iface API for selection by property, inspection, etc
2484 public String[] getTetherableUsbRegexs() {
2485 enforceTetherAccessPermission();
2486 if (isTetheringSupported()) {
2487 return mTethering.getTetherableUsbRegexs();
2488 } else {
2489 return new String[0];
2490 }
2491 }
2492
2493 public String[] getTetherableWifiRegexs() {
2494 enforceTetherAccessPermission();
2495 if (isTetheringSupported()) {
2496 return mTethering.getTetherableWifiRegexs();
2497 } else {
2498 return new String[0];
2499 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002500 }
2501
Danica Chang6fdd0c62010-08-11 14:54:43 -07002502 public String[] getTetherableBluetoothRegexs() {
2503 enforceTetherAccessPermission();
2504 if (isTetheringSupported()) {
2505 return mTethering.getTetherableBluetoothRegexs();
2506 } else {
2507 return new String[0];
2508 }
2509 }
2510
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002511 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002512 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002513 if (isTetheringSupported()) {
2514 return mTethering.setUsbTethering(enable);
2515 } else {
2516 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2517 }
2518 }
2519
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002520 // TODO - move iface listing, queries, etc to new module
2521 // javadoc from interface
2522 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002523 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002524 return mTethering.getTetherableIfaces();
2525 }
2526
2527 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002528 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002529 return mTethering.getTetheredIfaces();
2530 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002531
Robert Greenwalt5a735062010-03-02 17:25:02 -08002532 public String[] getTetheringErroredIfaces() {
2533 enforceTetherAccessPermission();
2534 return mTethering.getErroredIfaces();
2535 }
2536
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002537 public String[] getTetheredDhcpRanges() {
2538 enforceConnectivityInternalPermission();
2539 return mTethering.getTetheredDhcpRanges();
2540 }
2541
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002542 // if ro.tether.denied = true we default to no tethering
2543 // gservices could set the secure setting to 1 though to enable it on a build where it
2544 // had previously been turned off.
2545 public boolean isTetheringSupported() {
2546 enforceTetherAccessPermission();
2547 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002548 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002549 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2550 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002551 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2552 mTethering.getTetherableWifiRegexs().length != 0 ||
2553 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2554 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002555 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002556
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002557 // Called when we lose the default network and have no replacement yet.
2558 // This will automatically be cleared after X seconds or a new default network
2559 // becomes CONNECTED, whichever happens first. The timer is started by the
2560 // first caller and not restarted by subsequent callers.
2561 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002562 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002563 synchronized (this) {
2564 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002565 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002566 mNetTransitionWakeLock.acquire();
2567 mNetTransitionWakeLockCausedBy = forWhom;
2568 }
2569 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002570 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002571 mNetTransitionWakeLockTimeout);
2572 return;
2573 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002574
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002575 // 100 percent is full good, 0 is full bad.
2576 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002577 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002578 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002579 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002580 }
2581
Paul Jensenbfd17b72015-04-07 12:43:13 -04002582 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002583 enforceAccessPermission();
2584 enforceInternetPermission();
2585
Paul Jensenbfd17b72015-04-07 12:43:13 -04002586 NetworkAgentInfo nai;
2587 if (network == null) {
2588 nai = getDefaultNetwork();
2589 } else {
2590 nai = getNetworkAgentInfoForNetwork(network);
2591 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002592 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002593 // Revalidate if the app report does not match our current validated state.
2594 if (hasConnectivity == nai.lastValidated) return;
2595 final int uid = Binder.getCallingUid();
2596 if (DBG) {
2597 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2598 ") by " + uid);
2599 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002600 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002601 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2602 // which isn't meant to work on uncreated networks.
2603 if (!nai.created) return;
2604
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002605 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002606
2607 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2608 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002609 }
2610
Paul Jensene0bef712014-12-10 15:12:18 -05002611 public ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002612 // this information is already available as a world read/writable jvm property
2613 // so this API change wouldn't have a benifit. It also breaks the passing
2614 // of proxy info to all the JVMs.
2615 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002616 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002617 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002618 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2619 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002620 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002621 }
2622
Paul Jensene0bef712014-12-10 15:12:18 -05002623 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2624 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2625 // proxy is null then there is no proxy in place).
2626 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2627 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2628 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2629 proxy = null;
2630 }
2631 return proxy;
2632 }
2633
2634 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2635 // better for determining if a new proxy broadcast is necessary:
2636 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2637 // avoid unnecessary broadcasts.
2638 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2639 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2640 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2641 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2642 // all set.
2643 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2644 a = canonicalizeProxyInfo(a);
2645 b = canonicalizeProxyInfo(b);
2646 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2647 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2648 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2649 }
2650
Jason Monk207900c2014-04-25 15:00:09 -04002651 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002652 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002653
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002654 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002655 if (proxyProperties == mGlobalProxy) return;
2656 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2657 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2658
2659 String host = "";
2660 int port = 0;
2661 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002662 String pacFileUrl = "";
2663 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002664 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002665 if (!proxyProperties.isValid()) {
2666 if (DBG)
2667 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2668 return;
2669 }
Jason Monk207900c2014-04-25 15:00:09 -04002670 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002671 host = mGlobalProxy.getHost();
2672 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002673 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002674 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002675 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002676 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002677 } else {
2678 mGlobalProxy = null;
2679 }
2680 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002681 final long token = Binder.clearCallingIdentity();
2682 try {
2683 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2684 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2685 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2686 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002687 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002688 } finally {
2689 Binder.restoreCallingIdentity(token);
2690 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002691
Jason Monkcf0f97a2014-10-02 15:39:38 -04002692 if (mGlobalProxy == null) {
2693 proxyProperties = mDefaultProxy;
2694 }
2695 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002696 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002697 }
2698
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002699 private void loadGlobalProxy() {
2700 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002701 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2702 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2703 String exclList = Settings.Global.getString(res,
2704 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002705 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2706 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002707 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002708 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002709 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002710 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002711 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002712 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002713 if (!proxyProperties.isValid()) {
2714 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2715 return;
2716 }
2717
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002718 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002719 mGlobalProxy = proxyProperties;
2720 }
2721 }
2722 }
2723
Jason Monk207900c2014-04-25 15:00:09 -04002724 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002725 // this information is already available as a world read/writable jvm property
2726 // so this API change wouldn't have a benifit. It also breaks the passing
2727 // of proxy info to all the JVMs.
2728 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002729 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002730 return mGlobalProxy;
2731 }
2732 }
2733
Jason Monk207900c2014-04-25 15:00:09 -04002734 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002735 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002736 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002737 proxy = null;
2738 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002739 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002740 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002741 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002742 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002743 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2744 return;
2745 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002746
2747 // This call could be coming from the PacManager, containing the port of the local
2748 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2749 // global (to get the correct local port), and send a broadcast.
2750 // TODO: Switch PacManager to have its own message to send back rather than
2751 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002752 if ((mGlobalProxy != null) && (proxy != null)
2753 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002754 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2755 mGlobalProxy = proxy;
2756 sendProxyBroadcast(mGlobalProxy);
2757 return;
2758 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002759 mDefaultProxy = proxy;
2760
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002761 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002762 if (!mDefaultProxyDisabled) {
2763 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002764 }
2765 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002766 }
2767
Paul Jensene0bef712014-12-10 15:12:18 -05002768 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2769 // This method gets called when any network changes proxy, but the broadcast only ever contains
2770 // the default proxy (even if it hasn't changed).
2771 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2772 // world where an app might be bound to a non-default network.
2773 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2774 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2775 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2776
2777 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2778 sendProxyBroadcast(getDefaultProxy());
2779 }
2780 }
2781
Robert Greenwalt434203a2010-10-11 16:00:27 -07002782 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002783 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2784 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002785 if (!TextUtils.isEmpty(proxy)) {
2786 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002787 if (data.length == 0) {
2788 return;
2789 }
2790
Robert Greenwalt434203a2010-10-11 16:00:27 -07002791 String proxyHost = data[0];
2792 int proxyPort = 8080;
2793 if (data.length > 1) {
2794 try {
2795 proxyPort = Integer.parseInt(data[1]);
2796 } catch (NumberFormatException e) {
2797 return;
2798 }
2799 }
Jason Monk207900c2014-04-25 15:00:09 -04002800 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002801 setGlobalProxy(p);
2802 }
2803 }
2804
Jason Monk207900c2014-04-25 15:00:09 -04002805 private void sendProxyBroadcast(ProxyInfo proxy) {
2806 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002807 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002808 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002809 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002810 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2811 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002812 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002813 final long ident = Binder.clearCallingIdentity();
2814 try {
2815 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2816 } finally {
2817 Binder.restoreCallingIdentity(ident);
2818 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002819 }
2820
2821 private static class SettingsObserver extends ContentObserver {
2822 private int mWhat;
2823 private Handler mHandler;
2824 SettingsObserver(Handler handler, int what) {
2825 super(handler);
2826 mHandler = handler;
2827 mWhat = what;
2828 }
2829
2830 void observe(Context context) {
2831 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002832 resolver.registerContentObserver(Settings.Global.getUriFor(
2833 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002834 }
2835
2836 @Override
2837 public void onChange(boolean selfChange) {
2838 mHandler.obtainMessage(mWhat).sendToTarget();
2839 }
2840 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002841
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002842 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002843 Slog.d(TAG, s);
2844 }
2845
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002846 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002847 Slog.e(TAG, s);
2848 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002849
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002850 private static <T> T checkNotNull(T value, String message) {
2851 if (value == null) {
2852 throw new NullPointerException(message);
2853 }
2854 return value;
2855 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002856
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002857 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002858 * Prepare for a VPN application.
Jeff Davidson9a1da682014-11-11 13:52:58 -08002859 * Permissions are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002860 * @hide
2861 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002862 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002863 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002864 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002865 int user = UserHandle.getUserId(Binder.getCallingUid());
2866 synchronized(mVpns) {
2867 return mVpns.get(user).prepare(oldPackage, newPackage);
2868 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002869 }
2870
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002871 /**
Jeff Davidson05542602014-08-11 14:07:27 -07002872 * Set whether the current VPN package has the ability to launch VPNs without
Jeff Davidson9a1da682014-11-11 13:52:58 -08002873 * user intervention. This method is used by system-privileged apps.
2874 * Permissions are checked in Vpn class.
Jeff Davidson05542602014-08-11 14:07:27 -07002875 * @hide
2876 */
2877 @Override
2878 public void setVpnPackageAuthorization(boolean authorized) {
2879 int user = UserHandle.getUserId(Binder.getCallingUid());
2880 synchronized(mVpns) {
2881 mVpns.get(user).setPackageAuthorization(authorized);
2882 }
2883 }
2884
2885 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002886 * Configure a TUN interface and return its file descriptor. Parameters
2887 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002888 * and not available in ConnectivityManager. Permissions are checked in
2889 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002890 * @hide
2891 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002892 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002893 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002894 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002895 int user = UserHandle.getUserId(Binder.getCallingUid());
2896 synchronized(mVpns) {
2897 return mVpns.get(user).establish(config);
2898 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002899 }
2900
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002901 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07002902 * Start legacy VPN, controlling native daemons as needed. Creates a
2903 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002904 */
2905 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07002906 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002907 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07002908 final LinkProperties egress = getActiveLinkProperties();
2909 if (egress == null) {
2910 throw new IllegalStateException("Missing active network connection");
2911 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002912 int user = UserHandle.getUserId(Binder.getCallingUid());
2913 synchronized(mVpns) {
2914 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2915 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002916 }
2917
2918 /**
2919 * Return the information of the ongoing legacy VPN. This method is used
2920 * by VpnSettings and not available in ConnectivityManager. Permissions
2921 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002922 */
2923 @Override
2924 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002925 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002926 int user = UserHandle.getUserId(Binder.getCallingUid());
2927 synchronized(mVpns) {
2928 return mVpns.get(user).getLegacyVpnInfo();
2929 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002930 }
2931
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002932 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08002933 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
2934 * and not available in ConnectivityManager.
2935 */
2936 @Override
2937 public VpnInfo[] getAllVpnInfo() {
2938 enforceConnectivityInternalPermission();
2939 if (mLockdownEnabled) {
2940 return new VpnInfo[0];
2941 }
2942
2943 synchronized(mVpns) {
2944 List<VpnInfo> infoList = new ArrayList<>();
2945 for (int i = 0; i < mVpns.size(); i++) {
2946 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
2947 if (info != null) {
2948 infoList.add(info);
2949 }
2950 }
2951 return infoList.toArray(new VpnInfo[infoList.size()]);
2952 }
2953 }
2954
2955 /**
2956 * @return VPN information for accounting, or null if we can't retrieve all required
2957 * information, e.g primary underlying iface.
2958 */
2959 @Nullable
2960 private VpnInfo createVpnInfo(Vpn vpn) {
2961 VpnInfo info = vpn.getVpnInfo();
2962 if (info == null) {
2963 return null;
2964 }
2965 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
2966 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
2967 // the underlyingNetworks list.
2968 if (underlyingNetworks == null) {
2969 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
2970 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
2971 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
2972 }
2973 } else if (underlyingNetworks.length > 0) {
2974 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
2975 if (linkProperties != null) {
2976 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
2977 }
2978 }
2979 return info.primaryUnderlyingIface == null ? null : info;
2980 }
2981
2982 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07002983 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
2984 * not available in ConnectivityManager.
2985 * Permissions are checked in Vpn class.
2986 * @hide
2987 */
2988 @Override
2989 public VpnConfig getVpnConfig() {
2990 int user = UserHandle.getUserId(Binder.getCallingUid());
2991 synchronized(mVpns) {
2992 return mVpns.get(user).getVpnConfig();
2993 }
2994 }
2995
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002996 @Override
2997 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08002998 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2999 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3000 return false;
3001 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003002
3003 // Tear down existing lockdown if profile was removed
3004 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3005 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003006 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003007 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3008 return false;
3009 }
3010
3011 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3012 final VpnProfile profile = VpnProfile.decode(
3013 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003014 int user = UserHandle.getUserId(Binder.getCallingUid());
3015 synchronized(mVpns) {
3016 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3017 profile));
3018 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003019 } else {
3020 setLockdownTracker(null);
3021 }
3022
3023 return true;
3024 }
3025
3026 /**
3027 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3028 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3029 */
3030 private void setLockdownTracker(LockdownVpnTracker tracker) {
3031 // Shutdown any existing tracker
3032 final LockdownVpnTracker existing = mLockdownTracker;
3033 mLockdownTracker = null;
3034 if (existing != null) {
3035 existing.shutdown();
3036 }
3037
3038 try {
3039 if (tracker != null) {
3040 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003041 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003042 mLockdownTracker = tracker;
3043 mLockdownTracker.init();
3044 } else {
3045 mNetd.setFirewallEnabled(false);
3046 }
3047 } catch (RemoteException e) {
3048 // ignored; NMS lives inside system_server
3049 }
3050 }
3051
3052 private void throwIfLockdownEnabled() {
3053 if (mLockdownEnabled) {
3054 throw new IllegalStateException("Unavailable in lockdown mode");
3055 }
3056 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003057
Wink Savilleab9321d2013-06-29 21:10:57 -07003058 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003059 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003060 // TODO: Remove? Any reason to trigger a provisioning check?
3061 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003062 }
3063
3064 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3065 private volatile boolean mIsNotificationVisible = false;
3066
Paul Jensen89e0f092014-09-15 15:59:36 -04003067 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003068 if (DBG) {
3069 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003070 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003071 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003072 Intent intent = new Intent(action);
3073 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003074 // Concatenate the range of types onto the range of NetIDs.
3075 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003076 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003077 }
3078
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003079 /**
3080 * Show or hide network provisioning notificaitons.
3081 *
3082 * @param id an identifier that uniquely identifies this notification. This must match
3083 * between show and hide calls. We use the NetID value but for legacy callers
3084 * we concatenate the range of types with the range of NetIDs.
3085 */
3086 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003087 String extraInfo, PendingIntent intent) {
3088 if (DBG) {
3089 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3090 networkType + " extraInfo=" + extraInfo);
3091 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003092
3093 Resources r = Resources.getSystem();
3094 NotificationManager notificationManager = (NotificationManager) mContext
3095 .getSystemService(Context.NOTIFICATION_SERVICE);
3096
3097 if (visible) {
3098 CharSequence title;
3099 CharSequence details;
3100 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003101 Notification notification = new Notification();
3102 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003103 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003104 title = r.getString(R.string.wifi_available_sign_in, 0);
3105 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003106 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003107 icon = R.drawable.stat_notify_wifi_in_range;
3108 break;
3109 case ConnectivityManager.TYPE_MOBILE:
3110 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003111 title = r.getString(R.string.network_available_sign_in, 0);
3112 // TODO: Change this to pull from NetworkInfo once a printable
3113 // name has been added to it
3114 details = mTelephonyManager.getNetworkOperatorName();
3115 icon = R.drawable.stat_notify_rssi_in_range;
3116 break;
3117 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003118 title = r.getString(R.string.network_available_sign_in, 0);
3119 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003120 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003121 icon = R.drawable.stat_notify_rssi_in_range;
3122 break;
3123 }
3124
Wink Savilleab9321d2013-06-29 21:10:57 -07003125 notification.when = 0;
3126 notification.icon = icon;
3127 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003128 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003129 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003130 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003131 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003132 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003133
Wink Saville948282b2013-08-29 08:55:16 -07003134 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003135 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003136 } catch (NullPointerException npe) {
3137 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3138 npe.printStackTrace();
3139 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003140 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003141 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003142 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003143 } catch (NullPointerException npe) {
3144 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3145 npe.printStackTrace();
3146 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003147 }
Wink Saville948282b2013-08-29 08:55:16 -07003148 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003149 }
3150
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003151 /** Location to an updatable file listing carrier provisioning urls.
3152 * An example:
3153 *
3154 * <?xml version="1.0" encoding="utf-8"?>
3155 * <provisioningUrls>
3156 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3157 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3158 * </provisioningUrls>
3159 */
3160 private static final String PROVISIONING_URL_PATH =
3161 "/data/misc/radio/provisioning_urls.xml";
3162 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003163
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003164 /** XML tag for root element. */
3165 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3166 /** XML tag for individual url */
3167 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3168 /** XML tag for redirected url */
3169 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3170 /** XML attribute for mcc */
3171 private static final String ATTR_MCC = "mcc";
3172 /** XML attribute for mnc */
3173 private static final String ATTR_MNC = "mnc";
3174
3175 private static final int REDIRECTED_PROVISIONING = 1;
3176 private static final int PROVISIONING = 2;
3177
3178 private String getProvisioningUrlBaseFromFile(int type) {
3179 FileReader fileReader = null;
3180 XmlPullParser parser = null;
3181 Configuration config = mContext.getResources().getConfiguration();
3182 String tagType;
3183
3184 switch (type) {
3185 case PROVISIONING:
3186 tagType = TAG_PROVISIONING_URL;
3187 break;
3188 case REDIRECTED_PROVISIONING:
3189 tagType = TAG_REDIRECTED_URL;
3190 break;
3191 default:
3192 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3193 type);
3194 }
3195
3196 try {
3197 fileReader = new FileReader(mProvisioningUrlFile);
3198 parser = Xml.newPullParser();
3199 parser.setInput(fileReader);
3200 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3201
3202 while (true) {
3203 XmlUtils.nextElement(parser);
3204
3205 String element = parser.getName();
3206 if (element == null) break;
3207
3208 if (element.equals(tagType)) {
3209 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3210 try {
3211 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3212 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3213 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3214 parser.next();
3215 if (parser.getEventType() == XmlPullParser.TEXT) {
3216 return parser.getText();
3217 }
3218 }
3219 }
3220 } catch (NumberFormatException e) {
3221 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3222 }
3223 }
3224 }
3225 return null;
3226 } catch (FileNotFoundException e) {
3227 loge("Carrier Provisioning Urls file not found");
3228 } catch (XmlPullParserException e) {
3229 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3230 } catch (IOException e) {
3231 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3232 } finally {
3233 if (fileReader != null) {
3234 try {
3235 fileReader.close();
3236 } catch (IOException e) {}
3237 }
3238 }
3239 return null;
3240 }
3241
Wink Saville42d4f082013-07-20 20:31:59 -07003242 @Override
3243 public String getMobileRedirectedProvisioningUrl() {
3244 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003245 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3246 if (TextUtils.isEmpty(url)) {
3247 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3248 }
3249 return url;
3250 }
3251
Wink Saville42d4f082013-07-20 20:31:59 -07003252 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003253 public String getMobileProvisioningUrl() {
3254 enforceConnectivityInternalPermission();
3255 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3256 if (TextUtils.isEmpty(url)) {
3257 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003258 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003259 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003260 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003261 }
Wink Saville8cf35602013-07-10 23:00:07 -07003262 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003263 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003264 String phoneNumber = mTelephonyManager.getLine1Number();
3265 if (TextUtils.isEmpty(phoneNumber)) {
3266 phoneNumber = "0000000000";
3267 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003268 url = String.format(url,
3269 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3270 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003271 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003272 }
3273
Wink Savilleab9321d2013-06-29 21:10:57 -07003274 return url;
3275 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003276
Wink Saville948282b2013-08-29 08:55:16 -07003277 @Override
3278 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003279 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003280 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003281 final long ident = Binder.clearCallingIdentity();
3282 try {
3283 setProvNotificationVisible(visible, networkType, action);
3284 } finally {
3285 Binder.restoreCallingIdentity(ident);
3286 }
Wink Saville948282b2013-08-29 08:55:16 -07003287 }
Wink Saville7788c612013-08-29 14:57:08 -07003288
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003289 @Override
3290 public void setAirplaneMode(boolean enable) {
3291 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003292 final long ident = Binder.clearCallingIdentity();
3293 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003294 final ContentResolver cr = mContext.getContentResolver();
3295 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3296 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3297 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003298 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003299 } finally {
3300 Binder.restoreCallingIdentity(ident);
3301 }
3302 }
3303
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003304 private void onUserStart(int userId) {
3305 synchronized(mVpns) {
3306 Vpn userVpn = mVpns.get(userId);
3307 if (userVpn != null) {
3308 loge("Starting user already has a VPN");
3309 return;
3310 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003311 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003312 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003313 }
3314 }
3315
3316 private void onUserStop(int userId) {
3317 synchronized(mVpns) {
3318 Vpn userVpn = mVpns.get(userId);
3319 if (userVpn == null) {
3320 loge("Stopping user has no VPN");
3321 return;
3322 }
3323 mVpns.delete(userId);
3324 }
3325 }
3326
3327 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3328 @Override
3329 public void onReceive(Context context, Intent intent) {
3330 final String action = intent.getAction();
3331 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3332 if (userId == UserHandle.USER_NULL) return;
3333
3334 if (Intent.ACTION_USER_STARTING.equals(action)) {
3335 onUserStart(userId);
3336 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3337 onUserStop(userId);
3338 }
3339 }
3340 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003341
Robert Greenwalta67be032014-05-16 15:49:14 -07003342 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3343 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003344 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3345 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003346
Robert Greenwalta67be032014-05-16 15:49:14 -07003347 private static class NetworkFactoryInfo {
3348 public final String name;
3349 public final Messenger messenger;
3350 public final AsyncChannel asyncChannel;
3351
3352 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3353 this.name = name;
3354 this.messenger = messenger;
3355 this.asyncChannel = asyncChannel;
3356 }
3357 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003358
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003359 /**
3360 * Tracks info about the requester.
3361 * Also used to notice when the calling process dies so we can self-expire
3362 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003363 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3364 static final boolean REQUEST = true;
3365 static final boolean LISTEN = false;
3366
3367 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003368 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003369 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003370 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003371 final int mPid;
3372 final int mUid;
3373 final Messenger messenger;
3374 final boolean isRequest;
3375
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003376 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3377 request = r;
3378 mPendingIntent = pi;
3379 messenger = null;
3380 mBinder = null;
3381 mPid = getCallingPid();
3382 mUid = getCallingUid();
3383 this.isRequest = isRequest;
3384 }
3385
Robert Greenwalt9258c642014-03-26 16:47:06 -07003386 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3387 super();
3388 messenger = m;
3389 request = r;
3390 mBinder = binder;
3391 mPid = getCallingPid();
3392 mUid = getCallingUid();
3393 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003394 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003395
3396 try {
3397 mBinder.linkToDeath(this, 0);
3398 } catch (RemoteException e) {
3399 binderDied();
3400 }
3401 }
3402
3403 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003404 if (mBinder != null) {
3405 mBinder.unlinkToDeath(this, 0);
3406 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003407 }
3408
3409 public void binderDied() {
3410 log("ConnectivityService NetworkRequestInfo binderDied(" +
3411 request + ", " + mBinder + ")");
3412 releaseNetworkRequest(request);
3413 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003414
3415 public String toString() {
3416 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003417 mPid + " for " + request +
3418 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003419 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003420 }
3421
3422 @Override
3423 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003424 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003425 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003426 enforceNetworkRequestPermissions(networkCapabilities);
3427 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003428
Robert Greenwalt6078b502014-06-11 16:05:07 -07003429 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003430 throw new IllegalArgumentException("Bad timeout specified");
3431 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003432
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003433 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3434 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003435 if (DBG) log("requestNetwork for " + networkRequest);
3436 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3437 NetworkRequestInfo.REQUEST);
3438
3439 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003440 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003441 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003442 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003443 }
3444 return networkRequest;
3445 }
3446
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003447 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3448 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3449 == false) {
3450 enforceConnectivityInternalPermission();
3451 } else {
3452 enforceChangePermission();
3453 }
3454 }
3455
fenglub15e72b2015-03-20 11:29:56 -07003456 @Override
Robert Greenwalt2c22a912015-04-21 23:59:14 +00003457 public boolean requestBwUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003458 enforceAccessPermission();
3459 NetworkAgentInfo nai = null;
3460 if (network == null) {
3461 return false;
3462 }
3463 synchronized (mNetworkForNetId) {
3464 nai = mNetworkForNetId.get(network.netId);
3465 }
3466 if (nai != null) {
3467 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3468 return true;
3469 }
3470 return false;
3471 }
3472
3473
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003474 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3475 // if UID is restricted, don't allow them to bring up metered APNs
3476 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
3477 == false) {
3478 final int uidRules;
3479 final int uid = Binder.getCallingUid();
3480 synchronized(mRulesLock) {
3481 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3482 }
3483 if ((uidRules & RULE_REJECT_METERED) != 0) {
3484 // we could silently fail or we can filter the available nets to only give
3485 // them those they have access to. Chose the more useful
3486 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3487 }
3488 }
3489 }
3490
Robert Greenwalt9258c642014-03-26 16:47:06 -07003491 @Override
3492 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3493 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003494 checkNotNull(operation, "PendingIntent cannot be null.");
3495 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3496 enforceNetworkRequestPermissions(networkCapabilities);
3497 enforceMeteredApnPolicy(networkCapabilities);
3498
3499 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3500 nextNetworkRequestId());
3501 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3502 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3503 NetworkRequestInfo.REQUEST);
3504 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3505 nri));
3506 return networkRequest;
3507 }
3508
Jeremy Joslin79294842014-12-03 17:15:28 -08003509 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3510 mHandler.sendMessageDelayed(
3511 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3512 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3513 }
3514
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003515 @Override
3516 public void releasePendingNetworkRequest(PendingIntent operation) {
3517 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3518 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003519 }
3520
3521 @Override
3522 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3523 Messenger messenger, IBinder binder) {
3524 enforceAccessPermission();
3525
3526 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003527 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003528 if (DBG) log("listenForNetwork for " + networkRequest);
3529 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3530 NetworkRequestInfo.LISTEN);
3531
3532 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3533 return networkRequest;
3534 }
3535
3536 @Override
3537 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3538 PendingIntent operation) {
3539 }
3540
3541 @Override
3542 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003543 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3544 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003545 }
3546
3547 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003548 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003549 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003550 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3551 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003552 }
3553
Robert Greenwalta67be032014-05-16 15:49:14 -07003554 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003555 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003556 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3557 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3558 }
3559
3560 @Override
3561 public void unregisterNetworkFactory(Messenger messenger) {
3562 enforceConnectivityInternalPermission();
3563 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3564 }
3565
3566 private void handleUnregisterNetworkFactory(Messenger messenger) {
3567 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3568 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003569 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003570 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003571 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003572 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003573 }
3574
Robert Greenwalt7b816022014-04-18 15:25:25 -07003575 /**
3576 * NetworkAgentInfo supporting a request by requestId.
3577 * These have already been vetted (their Capabilities satisfy the request)
3578 * and the are the highest scored network available.
3579 * the are keyed off the Requests requestId.
3580 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003581 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003582 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3583 new SparseArray<NetworkAgentInfo>();
3584
Paul Jensen31a94f42015-02-13 14:18:39 -05003585 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3586 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003587 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3588 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003589 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3590 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3591 // there may not be a strict 1:1 correlation between the two.
3592 @GuardedBy("mNetworkForNetId")
3593 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003594
Robert Greenwalt7b816022014-04-18 15:25:25 -07003595 // NetworkAgentInfo keyed off its connecting messenger
3596 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003597 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003598 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3599 new HashMap<Messenger, NetworkAgentInfo>();
3600
Paul Jensen2c311d62014-11-17 12:34:51 -05003601 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003602 private final NetworkRequest mDefaultRequest;
3603
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003604 private NetworkAgentInfo getDefaultNetwork() {
3605 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3606 }
3607
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003608 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003609 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003610 }
3611
Paul Jensen31a94f42015-02-13 14:18:39 -05003612 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003613 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003614 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003615 enforceConnectivityInternalPermission();
3616
Paul Jensen2c311d62014-11-17 12:34:51 -05003617 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3618 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003619 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003620 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3621 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3622 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003623 synchronized (this) {
3624 nai.networkMonitor.systemReady = mSystemReady;
3625 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003626 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003627 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003628 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003629 }
3630
3631 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3632 if (VDBG) log("Got NetworkAgent Messenger");
3633 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003634 synchronized (mNetworkForNetId) {
3635 mNetworkForNetId.put(na.network.netId, na);
3636 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003637 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3638 NetworkInfo networkInfo = na.networkInfo;
3639 na.networkInfo = null;
3640 updateNetworkInfo(na, networkInfo);
3641 }
3642
3643 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3644 LinkProperties newLp = networkAgent.linkProperties;
3645 int netId = networkAgent.network.netId;
3646
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003647 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3648 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003649 if (networkAgent.clatd != null) {
3650 networkAgent.clatd.fixupLinkProperties(oldLp);
3651 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003652
Paul Jensen992f2522014-04-28 10:33:11 -04003653 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003654 updateMtu(newLp, oldLp);
3655 // TODO - figure out what to do for clat
3656// for (LinkProperties lp : newLp.getStackedLinks()) {
3657// updateMtu(lp, null);
3658// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003659 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003660
3661 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3662 // For now, use it only when the network has Internet access. http://b/18327075
3663 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3664 NetworkCapabilities.NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003665 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003666 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3667
Paul Jensen3b759822014-05-13 11:44:01 -04003668 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003669 if (isDefaultNetwork(networkAgent)) {
3670 handleApplyDefaultProxy(newLp.getHttpProxy());
3671 } else {
3672 updateProxy(newLp, oldLp, networkAgent);
3673 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003674 // TODO - move this check to cover the whole function
3675 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003676 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003677 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3678 }
Paul Jensen3b759822014-05-13 11:44:01 -04003679 }
3680
Lorenzo Colitti95439462014-10-09 13:44:48 +09003681 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3682 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3683 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003684
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003685 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003686 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3687 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003688 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003689 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003690 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003691 }
Paul Jensen992f2522014-04-28 10:33:11 -04003692
3693 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3694 CompareResult<String> interfaceDiff = new CompareResult<String>();
3695 if (oldLp != null) {
3696 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3697 } else if (newLp != null) {
3698 interfaceDiff.added = newLp.getAllInterfaceNames();
3699 }
3700 for (String iface : interfaceDiff.added) {
3701 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003702 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003703 mNetd.addInterfaceToNetwork(iface, netId);
3704 } catch (Exception e) {
3705 loge("Exception adding interface: " + e);
3706 }
3707 }
3708 for (String iface : interfaceDiff.removed) {
3709 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003710 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003711 mNetd.removeInterfaceFromNetwork(iface, netId);
3712 } catch (Exception e) {
3713 loge("Exception removing interface: " + e);
3714 }
3715 }
3716 }
3717
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003718 /**
3719 * Have netd update routes from oldLp to newLp.
3720 * @return true if routes changed between oldLp and newLp
3721 */
3722 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003723 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3724 if (oldLp != null) {
3725 routeDiff = oldLp.compareAllRoutes(newLp);
3726 } else if (newLp != null) {
3727 routeDiff.added = newLp.getAllRoutes();
3728 }
3729
3730 // add routes before removing old in case it helps with continuous connectivity
3731
3732 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3733 for (RouteInfo route : routeDiff.added) {
3734 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003735 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003736 try {
3737 mNetd.addRoute(netId, route);
3738 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003739 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3740 loge("Exception in addRoute for non-gateway: " + e);
3741 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003742 }
3743 }
3744 for (RouteInfo route : routeDiff.added) {
3745 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003746 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003747 try {
3748 mNetd.addRoute(netId, route);
3749 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003750 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3751 loge("Exception in addRoute for gateway: " + e);
3752 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003753 }
3754 }
3755
3756 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003757 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003758 try {
3759 mNetd.removeRoute(netId, route);
3760 } catch (Exception e) {
3761 loge("Exception in removeRoute: " + e);
3762 }
3763 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003764 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003765 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003766 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3767 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003768 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003769 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003770 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003771 dnses = new ArrayList();
3772 dnses.add(mDefaultDns);
3773 if (DBG) {
3774 loge("no dns provided for netId " + netId + ", so using defaults");
3775 }
3776 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003777 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003778 try {
3779 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3780 newLp.getDomains());
3781 } catch (Exception e) {
3782 loge("Exception in setDnsServersForNetwork: " + e);
3783 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003784 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3785 if (defaultNai != null && defaultNai.network.netId == netId) {
3786 setDefaultDnsSystemProperties(dnses);
3787 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003788 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003789 } else if (flush) {
3790 try {
3791 mNetd.flushNetworkDnsCache(netId);
3792 } catch (Exception e) {
3793 loge("Exception in flushNetworkDnsCache: " + e);
3794 }
3795 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003796 }
3797 }
3798
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003799 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3800 int last = 0;
3801 for (InetAddress dns : dnses) {
3802 ++last;
3803 String key = "net.dns" + last;
3804 String value = dns.getHostAddress();
3805 SystemProperties.set(key, value);
3806 }
3807 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3808 String key = "net.dns" + i;
3809 SystemProperties.set(key, "");
3810 }
3811 mNumDnsEntries = last;
3812 }
3813
Robert Greenwalt7b816022014-04-18 15:25:25 -07003814 private void updateCapabilities(NetworkAgentInfo networkAgent,
3815 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003816 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3817 synchronized (networkAgent) {
3818 networkAgent.networkCapabilities = networkCapabilities;
3819 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003820 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003821 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003822 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003823 }
3824
Paul Jensenc8b9a742014-09-30 15:37:41 -04003825 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3826 for (int i = 0; i < nai.networkRequests.size(); i++) {
3827 NetworkRequest nr = nai.networkRequests.valueAt(i);
3828 // Don't send listening requests to factories. b/17393458
3829 if (!isRequest(nr)) continue;
3830 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3831 }
3832 }
3833
Robert Greenwalt7b816022014-04-18 15:25:25 -07003834 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3835 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07003836 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07003837 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3838 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003839 }
3840 }
3841
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003842 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
3843 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08003844 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003845 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08003846 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
3847 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08003848 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003849 sendIntent(nri.mPendingIntent, intent);
3850 }
3851 // else not handled
3852 }
3853
3854 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
3855 mPendingIntentWakeLock.acquire();
3856 try {
3857 if (DBG) log("Sending " + pendingIntent);
3858 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
3859 } catch (PendingIntent.CanceledException e) {
3860 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
3861 mPendingIntentWakeLock.release();
3862 releasePendingNetworkRequest(pendingIntent);
3863 }
3864 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
3865 }
3866
3867 @Override
3868 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
3869 String resultData, Bundle resultExtras) {
3870 if (DBG) log("Finished sending " + pendingIntent);
3871 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08003872 // Release with a delay so the receiving client has an opportunity to put in its
3873 // own request.
3874 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003875 }
3876
Robert Greenwalt9258c642014-03-26 16:47:06 -07003877 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003878 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003879 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003880 Bundle bundle = new Bundle();
3881 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
3882 new NetworkRequest(nri.request));
3883 Message msg = Message.obtain();
3884 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
3885 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
3886 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
3887 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003888 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003889 case ConnectivityManager.CALLBACK_LOSING: {
3890 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
3891 break;
3892 }
3893 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
3894 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
3895 new NetworkCapabilities(networkAgent.networkCapabilities));
3896 break;
3897 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003898 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003899 bundle.putParcelable(LinkProperties.class.getSimpleName(),
3900 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003901 break;
3902 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003903 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003904 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003905 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003906 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003907 if (VDBG) {
3908 log("sending notification " + notifyTypeToName(notificationType) +
3909 " for " + nri.request);
3910 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003911 nri.messenger.send(msg);
3912 } catch (RemoteException e) {
3913 // may occur naturally in the race of binder death.
3914 loge("RemoteException caught trying to send a callback msg for " + nri.request);
3915 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003916 }
3917
Paul Jensenc8b9a742014-09-30 15:37:41 -04003918 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
3919 for (int i = 0; i < nai.networkRequests.size(); i++) {
3920 NetworkRequest nr = nai.networkRequests.valueAt(i);
3921 // Ignore listening requests.
3922 if (!isRequest(nr)) continue;
3923 loge("Dead network still had at least " + nr);
3924 break;
3925 }
3926 nai.asyncChannel.disconnect();
3927 }
3928
Robert Greenwalt7b816022014-04-18 15:25:25 -07003929 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
3930 if (oldNetwork == null) {
3931 loge("Unknown NetworkAgentInfo in handleLingerComplete");
3932 return;
3933 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04003934 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
3935 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003936 }
3937
Paul Jensen27b02b72014-07-14 12:03:33 -04003938 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003939 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04003940 setupDataActivityTracking(newNetwork);
3941 try {
3942 mNetd.setDefaultNetId(newNetwork.network.netId);
3943 } catch (Exception e) {
3944 loge("Exception setting default network :" + e);
3945 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09003946 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04003947 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07003948 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05003949 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04003950 }
3951
Paul Jensen2161a8e2014-09-11 11:00:39 -04003952 // Handles a network appearing or improving its score.
3953 //
3954 // - Evaluates all current NetworkRequests that can be
3955 // satisfied by newNetwork, and reassigns to newNetwork
3956 // any such requests for which newNetwork is the best.
3957 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05003958 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04003959 // needed. A network is needed if it is the best network for
3960 // one or more NetworkRequests, or if it is a VPN.
3961 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003962 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05003963 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
3964 //
3965 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
3966 // networks that have no chance (i.e. even if validated)
3967 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04003968 //
3969 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
3970 // it does not remove NetworkRequests that other Networks could better satisfy.
3971 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
3972 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
3973 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003974 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05003975 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003976 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05003977 // torn down if unneeded.
3978 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
3979 // performed to tear down unvalidated networks that have no chance (i.e. even if
3980 // validated) of becoming the highest scoring network.
3981 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
3982 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05003983 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09003984 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05003985 loge("ERROR: nascent network not validated.");
3986 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04003987 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003988 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05003989 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04003990 if (DBG) log("rematching " + newNetwork.name());
3991 // Find and migrate to this Network any NetworkRequests for
3992 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003993 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04003994 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003995 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09003996 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
3997 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07003998 if (DBG) {
3999 log("Network " + newNetwork.name() + " was already satisfying" +
4000 " request " + nri.request.requestId + ". No change.");
4001 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004002 keep = true;
4003 continue;
4004 }
4005
4006 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004007 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004008 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004009 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004010 // This is not a request, it's a callback listener.
4011 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004012 newNetwork.addRequest(nri.request);
4013 continue;
4014 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004015
Robert Greenwalt7b816022014-04-18 15:25:25 -07004016 // next check if it's better than any current network we're using for
4017 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004018 if (VDBG) {
4019 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004020 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4021 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004022 }
4023 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004024 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004025 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004026 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004027 currentNetwork.networkRequests.remove(nri.request.requestId);
4028 currentNetwork.networkLingered.add(nri.request);
4029 affectedNetworks.add(currentNetwork);
4030 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004031 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004032 }
Paul Jensen573a0352015-01-08 10:49:34 -05004033 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004034 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004035 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004036 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004037 // Tell NetworkFactories about the new score, so they can stop
4038 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004039 // TODO - this could get expensive if we have alot of requests for this
4040 // network. Think about if there is a way to reduce this. Push
4041 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004042 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004043 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004044 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004045 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004046 }
4047 }
4048 }
4049 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004050 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004051 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004052 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004053 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4054 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4055 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004056 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004057 }
4058 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004059 if (keep) {
4060 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004061 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004062 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004063 synchronized (ConnectivityService.this) {
4064 // have a new default network, release the transition wakelock in
4065 // a second if it's held. The second pause is to allow apps
4066 // to reconnect over the new network
4067 if (mNetTransitionWakeLock.isHeld()) {
4068 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4069 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4070 mNetTransitionWakeLockSerialNumber, 0),
4071 1000);
4072 }
4073 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004074 }
4075
4076 // do this after the default net is switched, but
4077 // before LegacyTypeTracker sends legacy broadcasts
4078 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4079
4080 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004081 // Maintain the illusion: since the legacy API only
4082 // understands one network at a time, we must pretend
4083 // that the current default network disconnected before
4084 // the new one connected.
4085 if (oldDefaultNetwork != null) {
4086 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4087 oldDefaultNetwork);
4088 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004089 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004090 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4091 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004092 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004093
4094 // Notify battery stats service about this network, both the normal
4095 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004096 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004097 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004098 final IBatteryStats bs = BatteryStatsService.getService();
4099 final int type = newNetwork.networkInfo.getType();
4100
4101 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4102 bs.noteNetworkInterfaceType(baseIface, type);
4103 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4104 final String stackedIface = stacked.getInterfaceName();
4105 bs.noteNetworkInterfaceType(stackedIface, type);
4106 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4107 }
4108 } catch (RemoteException ignored) {
4109 }
4110
Robert Greenwalt152ed372014-12-17 17:19:53 -08004111 // This has to happen after the notifyNetworkCallbacks as that tickles each
4112 // ConnectivityManager instance so that legacy requests correctly bind dns
4113 // requests to this network. The legacy users are listening for this bcast
4114 // and will generally do a dns request so they can ensureRouteToHost and if
4115 // they do that before the callbacks happen they'll use the default network.
4116 //
4117 // TODO: Is there still a race here? We send the broadcast
4118 // after sending the callback, but if the app can receive the
4119 // broadcast before the callback, it might still break.
4120 //
4121 // This *does* introduce a race where if the user uses the new api
4122 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4123 // they may get old info. Reverse this after the old startUsing api is removed.
4124 // This is on top of the multiple intent sequencing referenced in the todo above.
4125 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4126 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4127 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4128 // legacy type tracker filters out repeat adds
4129 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4130 }
4131 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004132
4133 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4134 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4135 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4136 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4137 if (newNetwork.isVPN()) {
4138 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4139 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004140 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004141 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004142 // validated (and get evaluated against peers, one losing here), or get reaped (see
4143 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4144 // network. Networks that have been up for a while and are validated should be torn
4145 // down via the lingering process so communication on that network is given time to
4146 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004147 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004148 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004149 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004150 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4151 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004152 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004153 if (DBG) log("Reaping " + nai.name());
4154 teardownUnneededNetwork(nai);
4155 }
4156 }
4157 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004158 }
4159
Paul Jensen2161a8e2014-09-11 11:00:39 -04004160 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4161 // being disconnected.
4162 // If only one Network's score or capabilities have been modified since the last time
4163 // this function was called, pass this Network in via the "changed" arugment, otherwise
4164 // pass null.
4165 // If only one Network has been changed but its NetworkCapabilities have not changed,
4166 // pass in the Network's score (from getCurrentScore()) prior to the change via
4167 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4168 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4169 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4170 // to avoid the slowness. It is not simply enough to process just "changed", for
4171 // example in the case where "changed"'s score decreases and another network should begin
4172 // satifying a NetworkRequest that "changed" currently satisfies.
4173
4174 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4175 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4176 // rematchNetworkAndRequests() handles.
4177 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004178 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4179 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004180 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004181 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4182 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4183 NascentState.NOT_JUST_VALIDATED,
4184 // Only reap the last time through the loop. Reaping before all rematching
4185 // is complete could incorrectly teardown a network that hasn't yet been
4186 // rematched.
4187 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4188 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004189 }
4190 }
4191 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004192
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004193 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004194 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004195 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004196 // For now only update icons for default connection.
4197 // TODO: Update WiFi and cellular icons separately. b/17237507
4198 if (!isDefaultNetwork(nai)) return;
4199
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004200 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004201 // Don't repeat publish.
4202 if (newInetCondition == mDefaultInetConditionPublished) return;
4203
4204 mDefaultInetConditionPublished = newInetCondition;
4205 sendInetConditionBroadcast(nai.networkInfo);
4206 }
4207
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004208 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4209 if (mLockdownTracker != null) {
4210 if (nai != null && nai.isVPN()) {
4211 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4212 } else {
4213 mLockdownTracker.onNetworkInfoChanged();
4214 }
4215 }
4216 }
4217
Robert Greenwalt7b816022014-04-18 15:25:25 -07004218 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4219 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004220 NetworkInfo oldInfo = null;
4221 synchronized (networkAgent) {
4222 oldInfo = networkAgent.networkInfo;
4223 networkAgent.networkInfo = newInfo;
4224 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004225 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004226
4227 if (oldInfo != null && oldInfo.getState() == state) {
4228 if (VDBG) log("ignoring duplicate network state non-change");
4229 return;
4230 }
4231 if (DBG) {
4232 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4233 (oldInfo == null ? "null" : oldInfo.getState()) +
4234 " to " + state);
4235 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004236
Paul Jenseneec75412014-08-04 12:21:19 -04004237 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004238 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004239 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004240 if (networkAgent.isVPN()) {
4241 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004242 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4243 (networkAgent.networkMisc == null ||
4244 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004245 } else {
4246 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4247 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004248 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004249 loge("Error creating network " + networkAgent.network.netId + ": "
4250 + e.getMessage());
4251 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004252 }
Paul Jenseneec75412014-08-04 12:21:19 -04004253 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004254 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004255 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004256
Paul Jensenca8f16a2014-05-09 12:47:55 -04004257 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004258 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004259
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004260 if (networkAgent.isVPN()) {
4261 // Temporarily disable the default proxy (not global).
4262 synchronized (mProxyLock) {
4263 if (!mDefaultProxyDisabled) {
4264 mDefaultProxyDisabled = true;
4265 if (mGlobalProxy == null && mDefaultProxy != null) {
4266 sendProxyBroadcast(null);
4267 }
4268 }
4269 }
4270 // TODO: support proxy per network.
4271 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004272
Paul Jensen2161a8e2014-09-11 11:00:39 -04004273 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004274 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4275 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004276
4277 // This has to happen after matching the requests, because callbacks are just requests.
4278 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004279 } else if (state == NetworkInfo.State.DISCONNECTED ||
4280 state == NetworkInfo.State.SUSPENDED) {
4281 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004282 if (networkAgent.isVPN()) {
4283 synchronized (mProxyLock) {
4284 if (mDefaultProxyDisabled) {
4285 mDefaultProxyDisabled = false;
4286 if (mGlobalProxy == null && mDefaultProxy != null) {
4287 sendProxyBroadcast(mDefaultProxy);
4288 }
4289 }
4290 }
4291 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004292 }
4293 }
4294
Robert Greenwaltac96c522014-06-03 16:43:57 -07004295 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4296 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004297 if (score < 0) {
4298 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4299 "). Bumping score to min of 0");
4300 score = 0;
4301 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004302
Paul Jensen2161a8e2014-09-11 11:00:39 -04004303 final int oldScore = nai.getCurrentScore();
4304 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004305
Paul Jensen57a767f2014-11-19 13:01:46 -05004306 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004307
Paul Jensenc8b9a742014-09-30 15:37:41 -04004308 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004309 }
4310
Robert Greenwalt9258c642014-03-26 16:47:06 -07004311 // notify only this one new request of the current state
4312 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4313 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4314 // TODO - read state from monitor to decide what to send.
4315// if (nai.networkMonitor.isLingering()) {
4316// notifyType = NetworkCallbacks.LOSING;
4317// } else if (nai.networkMonitor.isEvaluating()) {
4318// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4319// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004320 if (nri.mPendingIntent == null) {
4321 callCallbackForRequest(nri, nai, notifyType);
4322 } else {
4323 sendPendingIntentForRequest(nri, nai, notifyType);
4324 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004325 }
4326
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004327 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004328 // The NetworkInfo we actually send out has no bearing on the real
4329 // state of affairs. For example, if the default connection is mobile,
4330 // and a request for HIPRI has just gone away, we need to pretend that
4331 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4332 // the state to DISCONNECTED, even though the network is of type MOBILE
4333 // and is still connected.
4334 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4335 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004336 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004337 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004338 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004339 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004340 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004341 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4342 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4343 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4344 if (info.isFailover()) {
4345 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4346 nai.networkInfo.setFailover(false);
4347 }
4348 if (info.getReason() != null) {
4349 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4350 }
4351 if (info.getExtraInfo() != null) {
4352 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4353 }
4354 NetworkAgentInfo newDefaultAgent = null;
4355 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4356 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4357 if (newDefaultAgent != null) {
4358 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4359 newDefaultAgent.networkInfo);
4360 } else {
4361 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4362 }
4363 }
4364 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4365 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004366 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004367 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004368 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004369 }
4370 }
4371 }
4372
Robert Greenwalt7b816022014-04-18 15:25:25 -07004373 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004374 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004375 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004376 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4377 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4378 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004379 if (nri.mPendingIntent == null) {
4380 callCallbackForRequest(nri, networkAgent, notifyType);
4381 } else {
4382 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4383 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004384 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004385 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004386
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004387 private String notifyTypeToName(int notifyType) {
4388 switch (notifyType) {
4389 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4390 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4391 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4392 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4393 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4394 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4395 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4396 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4397 }
4398 return "UNKNOWN";
4399 }
4400
Jeff Sharkey69736342014-12-08 14:50:12 -08004401 /**
4402 * Notify other system services that set of active ifaces has changed.
4403 */
4404 private void notifyIfacesChanged() {
4405 try {
4406 mStatsService.forceUpdateIfaces();
4407 } catch (Exception ignored) {
4408 }
4409 }
4410
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004411 @Override
4412 public boolean addVpnAddress(String address, int prefixLength) {
4413 throwIfLockdownEnabled();
4414 int user = UserHandle.getUserId(Binder.getCallingUid());
4415 synchronized (mVpns) {
4416 return mVpns.get(user).addAddress(address, prefixLength);
4417 }
4418 }
4419
4420 @Override
4421 public boolean removeVpnAddress(String address, int prefixLength) {
4422 throwIfLockdownEnabled();
4423 int user = UserHandle.getUserId(Binder.getCallingUid());
4424 synchronized (mVpns) {
4425 return mVpns.get(user).removeAddress(address, prefixLength);
4426 }
4427 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004428
4429 @Override
4430 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4431 throwIfLockdownEnabled();
4432 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004433 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004434 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004435 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004436 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004437 if (success) {
4438 notifyIfacesChanged();
4439 }
4440 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004441 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004442
4443 @Override
4444 public void factoryReset() {
4445 enforceConnectivityInternalPermission();
4446 // Turn airplane mode off
4447 setAirplaneMode(false);
4448
4449 // Untether
4450 for (String tether : getTetheredIfaces()) {
4451 untether(tether);
4452 }
4453
4454 // Turn VPN off
4455 VpnConfig vpnConfig = getVpnConfig();
4456 if (vpnConfig != null) {
4457 if (vpnConfig.legacy) {
4458 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN);
4459 } else {
4460 // Prevent this app from initiating VPN connections in the future without
4461 // user intervention.
4462 setVpnPackageAuthorization(false);
4463
4464 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN);
4465 }
4466 }
4467 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004468}