blob: 758b0fc4bbc96209959b3a573d994e02e3c58ebd [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
Jeff Sharkey1a303952011-06-16 13:04:20 -070019import static android.Manifest.permission.MANAGE_NETWORK_POLICY;
Haoyu Baidb3c8672012-06-20 14:29:57 -070020import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070021import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
22import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Robert Greenwalt12e67352014-05-13 21:41:06 -070023import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070024import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070025import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070026import static android.net.ConnectivityManager.isNetworkTypeValid;
27import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070028import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070029
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;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070092import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070093import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080094
Wink Savilleab9321d2013-06-29 21:10:57 -070095import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -040096import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070097import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -070098import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070099import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700100import com.android.internal.net.VpnConfig;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700101import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700102import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700103import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700104import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700105import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700106import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400107import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900108import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700109import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400110import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400111import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700112import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800113import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700114import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700115import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700116import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700117import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700118import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700119
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700120import org.xmlpull.v1.XmlPullParser;
121import org.xmlpull.v1.XmlPullParserException;
122
123import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800124import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700125import java.io.FileNotFoundException;
126import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700127import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800128import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700129import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700130import java.net.InetAddress;
131import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700132import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700133import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700134import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700135import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700136import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500137import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700138import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700139import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700140import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700141import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800142
143/**
144 * @hide
145 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800146public class ConnectivityService extends IConnectivityManager.Stub
147 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700148 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700150 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700151 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
Jake Hamby786e71a2014-02-06 14:43:50 -0800153 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700154
Jeff Sharkey899223b2012-08-04 15:24:58 -0700155 // TODO: create better separation between radio types and network types
156
Robert Greenwalt42acef32009-08-12 16:08:25 -0700157 // how long to wait before switching back to a radio's default network
158 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
159 // system property that can override the above value
160 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
161 "android.telephony.apn-restore";
162
Jeremy Joslin79294842014-12-03 17:15:28 -0800163 // How long to delay to removal of a pending intent based request.
164 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
165 private final int mReleasePendingIntentDelayMs;
166
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800167 private Tethering mTethering;
168
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700169 private final PermissionMonitor mPermissionMonitor;
170
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700171 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700172
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700173 @GuardedBy("mVpns")
174 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700175
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700176 private boolean mLockdownEnabled;
177 private LockdownVpnTracker mLockdownTracker;
178
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700179 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
180 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700181 /** Currently active network rules by UID. */
182 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700183 /** Set of ifaces that are costly. */
184 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700185
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800186 private Context mContext;
187 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700188 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700189 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800190
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700191 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800192 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193
194 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700195 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800196
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700197 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800198 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700199 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700200
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700201 private String mCurrentTcpBufferSizes;
202
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700203 private static final int ENABLED = 1;
204 private static final int DISABLED = 0;
205
Paul Jensenb10e37f2014-11-25 12:33:08 -0500206 // Arguments to rematchNetworkAndRequests()
207 private enum NascentState {
208 // Indicates a network was just validated for the first time. If the network is found to
209 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
210 JUST_VALIDATED,
211 // Indicates a network was not validated for the first time immediately prior to this call.
212 NOT_JUST_VALIDATED
213 };
214 private enum ReapUnvalidatedNetworks {
215 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
216 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
217 // known that there may be unvalidated networks that could potentially be reaped, and when
218 // all networks have been rematched against all NetworkRequests.
219 REAP,
220 // Don't reap unvalidated networks. This should be passed when it's known that there are
221 // no unvalidated networks that could potentially be reaped, and when some networks have
222 // not yet been rematched against all NetworkRequests.
223 DONT_REAP
224 };
225
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700226 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700227 * used internally to change our mobile data enabled flag
228 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700229 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700230
231 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700232 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700233 * from one net to another. Clear happens when we get a new
234 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
235 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700236 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700237 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700238
Robert Greenwalt434203a2010-10-11 16:00:27 -0700239 /**
240 * used internally to reload global proxy settings
241 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700242 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700243
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700244 /**
Wink Saville628b0852011-08-04 15:01:58 -0700245 * used internally to send a sticky broadcast delayed.
246 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700247 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700248
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700249 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400250 * PAC manager has received new port.
251 */
252 private static final int EVENT_PROXY_HAS_CHANGED = 16;
253
Robert Greenwalte049c232014-04-11 15:53:27 -0700254 /**
255 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700256 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700257 */
258 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
259
Robert Greenwalt7b816022014-04-18 15:25:25 -0700260 /**
261 * used internally when registering NetworkAgents
262 * obj = Messenger
263 */
264 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
265
Robert Greenwalt9258c642014-03-26 16:47:06 -0700266 /**
267 * used to add a network request
268 * includes a NetworkRequestInfo
269 */
270 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
271
272 /**
273 * indicates a timeout period is over - check if we had a network yet or not
274 * and if not, call the timeout calback (but leave the request live until they
275 * cancel it.
276 * includes a NetworkRequestInfo
277 */
278 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
279
280 /**
281 * used to add a network listener - no request
282 * includes a NetworkRequestInfo
283 */
284 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
285
286 /**
287 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400288 * arg1 = UID of caller
289 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700290 */
291 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
292
Robert Greenwalta67be032014-05-16 15:49:14 -0700293 /**
294 * used internally when registering NetworkFactories
295 * obj = Messenger
296 */
297 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
298
Robert Greenwalt27711812014-06-25 16:45:57 -0700299 /**
300 * used internally to expire a wakelock when transitioning
301 * from one net to another. Expire happens when we fail to find
302 * a new network (typically after 1 minute) -
303 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
304 * a replacement network.
305 */
306 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
307
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700308 /**
309 * Used internally to indicate the system is ready.
310 */
311 private static final int EVENT_SYSTEM_READY = 25;
312
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800313 /**
314 * used to add a network request with a pending intent
315 * includes a NetworkRequestInfo
316 */
317 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
318
319 /**
320 * used to remove a pending intent and its associated network request.
321 * arg1 = UID of caller
322 * obj = PendingIntent
323 */
324 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
325
Robert Greenwalta67be032014-05-16 15:49:14 -0700326
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700327 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700328 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700329 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700330 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700331
Mike Lockwood0f79b542009-08-14 14:18:49 -0400332 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800333 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400334
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700335 private PowerManager.WakeLock mNetTransitionWakeLock;
336 private String mNetTransitionWakeLockCausedBy = "";
337 private int mNetTransitionWakeLockSerialNumber;
338 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800339 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700340
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700341 private InetAddress mDefaultDns;
342
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700343 // used in DBG mode to track inet condition reports
344 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
345 private ArrayList mInetLog;
346
Robert Greenwalt434203a2010-10-11 16:00:27 -0700347 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400348 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700349 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700350 private boolean mDefaultProxyDisabled = false;
351
Robert Greenwalt434203a2010-10-11 16:00:27 -0700352 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400353 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700354
Jason Monk602b2322013-07-03 17:04:33 -0400355 private PacManager mPacManager = null;
356
Robert Greenwalt434203a2010-10-11 16:00:27 -0700357 private SettingsObserver mSettingsObserver;
358
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400359 private UserManager mUserManager;
360
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700361 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700362 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700363
Robert Greenwalt50393202011-06-21 17:26:14 -0700364 // the set of network types that can only be enabled by system/sig apps
365 List mProtectedNetworks;
366
John Spurlockbf991a82013-06-24 14:20:23 -0400367 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700368
Wink Savilleab9321d2013-06-29 21:10:57 -0700369 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400370
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700371 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
372 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700373 private final static int MAX_NET_ID = 65535;
374 private int mNextNetId = MIN_NET_ID;
375
Robert Greenwalt34524f02014-05-18 16:22:10 -0700376 // sequence number of NetworkRequests
377 private int mNextNetworkRequestId = 1;
378
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700379 /**
380 * Implements support for the legacy "one network per network type" model.
381 *
382 * We used to have a static array of NetworkStateTrackers, one for each
383 * network type, but that doesn't work any more now that we can have,
384 * for example, more that one wifi network. This class stores all the
385 * NetworkAgentInfo objects that support a given type, but the legacy
386 * API will only see the first one.
387 *
388 * It serves two main purposes:
389 *
390 * 1. Provide information about "the network for a given type" (since this
391 * API only supports one).
392 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
393 * the first network for a given type changes, or if the default network
394 * changes.
395 */
396 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900397
398 private static final boolean DBG = true;
399 private static final boolean VDBG = false;
400 private static final String TAG = "CSLegacyTypeTracker";
401
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700402 /**
403 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
404 * Each list holds references to all NetworkAgentInfos that are used to
405 * satisfy requests for that network type.
406 *
407 * This array is built out at startup such that an unsupported network
408 * doesn't get an ArrayList instance, making this a tristate:
409 * unsupported, supported but not active and active.
410 *
411 * The actual lists are populated when we scan the network types that
412 * are supported on this device.
413 */
414 private ArrayList<NetworkAgentInfo> mTypeLists[];
415
416 public LegacyTypeTracker() {
417 mTypeLists = (ArrayList<NetworkAgentInfo>[])
418 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
419 }
420
421 public void addSupportedType(int type) {
422 if (mTypeLists[type] != null) {
423 throw new IllegalStateException(
424 "legacy list for type " + type + "already initialized");
425 }
426 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
427 }
428
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700429 public boolean isTypeSupported(int type) {
430 return isNetworkTypeValid(type) && mTypeLists[type] != null;
431 }
432
433 public NetworkAgentInfo getNetworkForType(int type) {
434 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
435 return mTypeLists[type].get(0);
436 } else {
437 return null;
438 }
439 }
440
Lorenzo Colittia793a672014-07-31 23:20:17 +0900441 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
442 if (DBG) {
443 log("Sending " + (connected ? "connected" : "disconnected") +
444 " broadcast for type " + type + " " + nai.name() +
445 " isDefaultNetwork=" + isDefaultNetwork(nai));
446 }
447 }
448
449 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700450 public void add(int type, NetworkAgentInfo nai) {
451 if (!isTypeSupported(type)) {
452 return; // Invalid network type.
453 }
454 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
455
456 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
457 if (list.contains(nai)) {
458 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
459 return;
460 }
461
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900462 list.add(nai);
463
464 // Send a broadcast if this is the first network of its type or if it's the default.
465 if (list.size() == 1 || isDefaultNetwork(nai)) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900466 maybeLogBroadcast(nai, true, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700467 sendLegacyNetworkBroadcast(nai, true, type);
468 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700469 }
470
Lorenzo Colittia793a672014-07-31 23:20:17 +0900471 /** Removes the given network from the specified legacy type list. */
472 public void remove(int type, NetworkAgentInfo nai) {
473 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
474 if (list == null || list.isEmpty()) {
475 return;
476 }
477
478 boolean wasFirstNetwork = list.get(0).equals(nai);
479
480 if (!list.remove(nai)) {
481 return;
482 }
483
484 if (wasFirstNetwork || isDefaultNetwork(nai)) {
485 maybeLogBroadcast(nai, false, type);
486 sendLegacyNetworkBroadcast(nai, false, type);
487 }
488
489 if (!list.isEmpty() && wasFirstNetwork) {
490 if (DBG) log("Other network available for type " + type +
491 ", sending connected broadcast");
492 maybeLogBroadcast(list.get(0), false, type);
493 sendLegacyNetworkBroadcast(list.get(0), false, type);
494 }
495 }
496
497 /** Removes the given network from all legacy type lists. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700498 public void remove(NetworkAgentInfo nai) {
499 if (VDBG) log("Removing agent " + nai);
500 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900501 remove(type, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700502 }
503 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700504
Lorenzo Colittia793a672014-07-31 23:20:17 +0900505 private String naiToString(NetworkAgentInfo nai) {
506 String name = (nai != null) ? nai.name() : "null";
507 String state = (nai.networkInfo != null) ?
508 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
509 "???/???";
510 return name + " " + state;
511 }
512
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700513 public void dump(IndentingPrintWriter pw) {
514 for (int type = 0; type < mTypeLists.length; type++) {
515 if (mTypeLists[type] == null) continue;
516 pw.print(type + " ");
517 pw.increaseIndent();
518 if (mTypeLists[type].size() == 0) pw.println("none");
519 for (NetworkAgentInfo nai : mTypeLists[type]) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900520 pw.println(naiToString(nai));
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700521 }
522 pw.decreaseIndent();
523 }
524 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525
526 // This class needs its own log method because it has a different TAG.
527 private void log(String s) {
528 Slog.d(TAG, s);
529 }
530
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700531 }
532 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
533
Jeff Sharkey899223b2012-08-04 15:24:58 -0700534 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700535 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800536 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800537
Robert Greenwalte049c232014-04-11 15:53:27 -0700538 NetworkCapabilities netCap = new NetworkCapabilities();
Robert Greenwalt7569f182014-06-08 16:42:59 -0700539 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
540 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700541 mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -0700542 NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
543 NetworkRequestInfo.REQUEST);
544 mNetworkRequests.put(mDefaultRequest, nri);
Robert Greenwalte049c232014-04-11 15:53:27 -0700545
Wink Savillebb08caf2010-09-02 19:23:52 -0700546 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
547 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700548 mHandler = new InternalHandler(handlerThread.getLooper());
549 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700550
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800551 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800552 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
553 String id = Settings.Secure.getString(context.getContentResolver(),
554 Settings.Secure.ANDROID_ID);
555 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700556 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800557 SystemProperties.set("net.hostname", name);
558 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800559 }
560
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700561 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700562 String dns = Settings.Global.getString(context.getContentResolver(),
563 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700564 if (dns == null || dns.length() == 0) {
565 dns = context.getResources().getString(
566 com.android.internal.R.string.config_default_dns_server);
567 }
568 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800569 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
570 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800571 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700572 }
573
Jeremy Joslin79294842014-12-03 17:15:28 -0800574 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
575 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
576
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700577 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700578 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800579 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700580 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700581 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700582 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700583
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700584 try {
585 mPolicyManager.registerListener(mPolicyListener);
586 } catch (RemoteException e) {
587 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700588 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700589 }
590
591 final PowerManager powerManager = (PowerManager) context.getSystemService(
592 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700593 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
594 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
595 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800596 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700597
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700598 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700599
Wink Saville51f456f2013-04-23 14:26:51 -0700600 // TODO: What is the "correct" way to do determine if this is a wifi only device?
601 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
602 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700603 String[] naStrings = context.getResources().getStringArray(
604 com.android.internal.R.array.networkAttributes);
605 for (String naString : naStrings) {
606 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700607 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700608 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700609 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800610 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700611 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700612 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700613 }
Wink Saville51f456f2013-04-23 14:26:51 -0700614 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
615 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
616 n.type);
617 continue;
618 }
Wink Saville975c8482011-04-07 14:23:45 -0700619 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800620 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700621 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700622 continue;
623 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700624 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700625
Wink Saville975c8482011-04-07 14:23:45 -0700626 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700627 mNetworksDefined++;
628 } catch(Exception e) {
629 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700630 }
631 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700632
633 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
634 if (mNetConfigs[TYPE_VPN] == null) {
635 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
636 // don't need to add TYPE_VPN to mNetConfigs.
637 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
638 mNetworksDefined++; // used only in the log() statement below.
639 }
640
Wink Saville5e56bc52013-07-29 15:00:57 -0700641 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700642
Robert Greenwalt50393202011-06-21 17:26:14 -0700643 mProtectedNetworks = new ArrayList<Integer>();
644 int[] protectedNetworks = context.getResources().getIntArray(
645 com.android.internal.R.array.config_protectedNetworks);
646 for (int p : protectedNetworks) {
647 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
648 mProtectedNetworks.add(p);
649 } else {
650 if (DBG) loge("Ignoring protectedNetwork " + p);
651 }
652 }
653
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700654 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
655 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700656
Robert Greenwaltfab501672014-07-23 11:44:01 -0700657 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800658
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700659 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
660
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700661 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700662 IntentFilter intentFilter = new IntentFilter();
663 intentFilter.addAction(Intent.ACTION_USER_STARTING);
664 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
665 mContext.registerReceiverAsUser(
666 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900667
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700668 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700669 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700670 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700671 } catch (RemoteException e) {
672 loge("Error registering observer :" + e);
673 }
674
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700675 if (DBG) {
676 mInetLog = new ArrayList();
677 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700678
679 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
680 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800681
John Spurlockbf991a82013-06-24 14:20:23 -0400682 mDataConnectionStats = new DataConnectionStats(mContext);
683 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400684
Jason Monkdecd2952013-10-10 14:02:51 -0400685 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700686
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400687 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800688 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700689
Robert Greenwalt34524f02014-05-18 16:22:10 -0700690 private synchronized int nextNetworkRequestId() {
691 return mNextNetworkRequestId++;
692 }
693
Paul Jensen60061a62014-08-05 14:13:48 -0400694 private void assignNextNetId(NetworkAgentInfo nai) {
695 synchronized (mNetworkForNetId) {
696 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
697 int netId = mNextNetId;
698 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
699 // Make sure NetID unused. http://b/16815182
700 if (mNetworkForNetId.get(netId) == null) {
701 nai.network = new Network(netId);
702 mNetworkForNetId.put(netId, nai);
703 return;
704 }
705 }
706 }
707 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700708 }
709
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800710 private NetworkState getFilteredNetworkState(int networkType, int uid) {
711 NetworkInfo info = null;
712 LinkProperties lp = null;
713 NetworkCapabilities nc = null;
714 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800715 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800716
717 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
718 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
719 if (nai != null) {
720 synchronized (nai) {
721 info = new NetworkInfo(nai.networkInfo);
722 lp = new LinkProperties(nai.linkProperties);
723 nc = new NetworkCapabilities(nai.networkCapabilities);
724 network = new Network(nai.network);
Jeff Sharkey32566012014-12-02 18:30:14 -0800725 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800726 }
727 info.setType(networkType);
728 } else {
729 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
730 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
731 info.setIsAvailable(true);
732 lp = new LinkProperties();
733 nc = new NetworkCapabilities();
734 network = null;
735 }
736 info = getFilteredNetworkInfo(info, lp, uid);
737 }
738
Jeff Sharkey32566012014-12-02 18:30:14 -0800739 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400740 }
741
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800742 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
743 if (network == null) {
744 return null;
745 }
746 synchronized (mNetworkForNetId) {
747 return mNetworkForNetId.get(network.netId);
748 }
749 };
750
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900751 private Network[] getVpnUnderlyingNetworks(int uid) {
752 if (!mLockdownEnabled) {
753 int user = UserHandle.getUserId(uid);
754 synchronized (mVpns) {
755 Vpn vpn = mVpns.get(user);
756 if (vpn != null && vpn.appliesToUid(uid)) {
757 return vpn.getUnderlyingNetworks();
758 }
759 }
760 }
761 return null;
762 }
763
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800764 private NetworkState getUnfilteredActiveNetworkState(int uid) {
765 NetworkInfo info = null;
766 LinkProperties lp = null;
767 NetworkCapabilities nc = null;
768 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800769 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800770
771 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800772
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900773 final Network[] networks = getVpnUnderlyingNetworks(uid);
774 if (networks != null) {
775 // getUnderlyingNetworks() returns:
776 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
777 // empty array => the VPN explicitly said "no default network".
778 // non-empty array => the VPN specified one or more default networks; we use the
779 // first one.
780 if (networks.length > 0) {
781 nai = getNetworkAgentInfoForNetwork(networks[0]);
782 } else {
783 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800784 }
785 }
786
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800787 if (nai != null) {
788 synchronized (nai) {
789 info = new NetworkInfo(nai.networkInfo);
790 lp = new LinkProperties(nai.linkProperties);
791 nc = new NetworkCapabilities(nai.networkCapabilities);
792 network = new Network(nai.network);
Jeff Sharkey32566012014-12-02 18:30:14 -0800793 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800794 }
795 }
796
Jeff Sharkey32566012014-12-02 18:30:14 -0800797 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400798 }
799
800 /**
801 * Check if UID should be blocked from using the network with the given LinkProperties.
802 */
803 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700804 final boolean networkCostly;
805 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700806
Robert Greenwalt12e67352014-05-13 21:41:06 -0700807 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700808 synchronized (mRulesLock) {
809 networkCostly = mMeteredIfaces.contains(iface);
810 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700811 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700812
813 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
814 return true;
815 }
816
817 // no restrictive rules; network is visible
818 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700819 }
820
821 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700822 * Return a filtered {@link NetworkInfo}, potentially marked
823 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800824 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700825 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800826 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
827 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400828 // network is blocked; clone and override state
829 info = new NetworkInfo(info);
830 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900831 if (DBG) {
832 log("returning Blocked NetworkInfo for ifname=" +
833 lp.getInterfaceName() + ", uid=" + uid);
834 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700835 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800836 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700837 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700838 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700839 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700840 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700841 }
842
843 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800844 * Return NetworkInfo for the active (i.e., connected) network interface.
845 * It is assumed that at most one network is active at a time. If more
846 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700847 * @return the info for the active network, or {@code null} if none is
848 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800849 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700850 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800851 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700852 enforceAccessPermission();
853 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800854 NetworkState state = getUnfilteredActiveNetworkState(uid);
855 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800856 }
857
Wink Saville948282b2013-08-29 08:55:16 -0700858 /**
859 * Find the first Provisioning network.
860 *
861 * @return NetworkInfo or null if none.
862 */
863 private NetworkInfo getProvisioningNetworkInfo() {
864 enforceAccessPermission();
865
866 // Find the first Provisioning Network
867 NetworkInfo provNi = null;
868 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700869 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700870 provNi = ni;
871 break;
872 }
873 }
874 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
875 return provNi;
876 }
877
878 /**
879 * Find the first Provisioning network or the ActiveDefaultNetwork
880 * if there is no Provisioning network
881 *
882 * @return NetworkInfo or null if none.
883 */
884 @Override
885 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
886 enforceAccessPermission();
887
888 NetworkInfo provNi = getProvisioningNetworkInfo();
889 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800890 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700891 }
892 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
893 return provNi;
894 }
895
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700896 public NetworkInfo getActiveNetworkInfoUnfiltered() {
897 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800898 final int uid = Binder.getCallingUid();
899 NetworkState state = getUnfilteredActiveNetworkState(uid);
900 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700901 }
902
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700903 @Override
904 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
905 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800906 NetworkState state = getUnfilteredActiveNetworkState(uid);
907 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700908 }
909
910 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800911 public NetworkInfo getNetworkInfo(int networkType) {
912 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700913 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900914 if (getVpnUnderlyingNetworks(uid) != null) {
915 // A VPN is active, so we may need to return one of its underlying networks. This
916 // information is not available in LegacyTypeTracker, so we have to get it from
917 // getUnfilteredActiveNetworkState.
918 NetworkState state = getUnfilteredActiveNetworkState(uid);
919 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
920 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
921 }
922 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800923 NetworkState state = getFilteredNetworkState(networkType, uid);
924 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 }
926
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800927 @Override
928 public NetworkInfo getNetworkInfoForNetwork(Network network) {
929 enforceAccessPermission();
930 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700931 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800932 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
933 if (nai != null) {
934 synchronized (nai) {
935 info = new NetworkInfo(nai.networkInfo);
936 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700937 }
938 }
939 return info;
940 }
941
942 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800943 public NetworkInfo[] getAllNetworkInfo() {
944 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700945 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -0400946 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
947 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800948 NetworkInfo info = getNetworkInfo(networkType);
949 if (info != null) {
950 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700951 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800952 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700953 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800954 }
955
Robert Greenwalt9b2886e2011-08-31 11:46:42 -0700956 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700957 public Network getNetworkForType(int networkType) {
958 enforceAccessPermission();
959 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800960 NetworkState state = getFilteredNetworkState(networkType, uid);
961 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
962 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700963 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800964 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -0700965 }
966
967 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -0700968 public Network[] getAllNetworks() {
969 enforceAccessPermission();
970 final ArrayList<Network> result = new ArrayList();
971 synchronized (mNetworkForNetId) {
972 for (int i = 0; i < mNetworkForNetId.size(); i++) {
973 result.add(new Network(mNetworkForNetId.valueAt(i).network));
974 }
975 }
976 return result.toArray(new Network[result.size()]);
977 }
978
Lorenzo Colitti403aa262014-11-28 11:21:30 +0900979 private NetworkCapabilities getNetworkCapabilitiesAndValidation(NetworkAgentInfo nai) {
980 if (nai != null) {
981 synchronized (nai) {
982 if (nai.created) {
983 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +0900984 if (nai.lastValidated) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +0900985 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
986 } else {
987 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
988 }
989 return nc;
990 }
991 }
992 }
993 return null;
994 }
995
996 @Override
997 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
998 // The basic principle is: if an app's traffic could possibly go over a
999 // network, without the app doing anything multinetwork-specific,
1000 // (hence, by "default"), then include that network's capabilities in
1001 // the array.
1002 //
1003 // In the normal case, app traffic only goes over the system's default
1004 // network connection, so that's the only network returned.
1005 //
1006 // With a VPN in force, some app traffic may go into the VPN, and thus
1007 // over whatever underlying networks the VPN specifies, while other app
1008 // traffic may go over the system default network (e.g.: a split-tunnel
1009 // VPN, or an app disallowed by the VPN), so the set of networks
1010 // returned includes the VPN's underlying networks and the system
1011 // default.
1012 enforceAccessPermission();
1013
1014 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1015
1016 NetworkAgentInfo nai = getDefaultNetwork();
1017 NetworkCapabilities nc = getNetworkCapabilitiesAndValidation(getDefaultNetwork());
1018 if (nc != null) {
1019 result.put(nai.network, nc);
1020 }
1021
1022 if (!mLockdownEnabled) {
1023 synchronized (mVpns) {
1024 Vpn vpn = mVpns.get(userId);
1025 if (vpn != null) {
1026 Network[] networks = vpn.getUnderlyingNetworks();
1027 if (networks != null) {
1028 for (Network network : networks) {
1029 nai = getNetworkAgentInfoForNetwork(network);
1030 nc = getNetworkCapabilitiesAndValidation(nai);
1031 if (nc != null) {
1032 result.put(nai.network, nc);
1033 }
1034 }
1035 }
1036 }
1037 }
1038 }
1039
1040 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1041 out = result.values().toArray(out);
1042 return out;
1043 }
1044
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001045 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001046 public boolean isNetworkSupported(int networkType) {
1047 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001048 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001049 }
1050
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001051 /**
1052 * Return LinkProperties for the active (i.e., connected) default
1053 * network interface. It is assumed that at most one default network
1054 * is active at a time. If more than one is active, it is indeterminate
1055 * which will be returned.
1056 * @return the ip properties for the active network, or {@code null} if
1057 * none is active
1058 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001059 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001060 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001061 enforceAccessPermission();
1062 final int uid = Binder.getCallingUid();
1063 NetworkState state = getUnfilteredActiveNetworkState(uid);
1064 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001065 }
1066
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001067 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001068 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001069 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001070 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1071 if (nai != null) {
1072 synchronized (nai) {
1073 return new LinkProperties(nai.linkProperties);
1074 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001075 }
1076 return null;
1077 }
1078
Robert Greenwalt12e67352014-05-13 21:41:06 -07001079 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001080 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001081 public LinkProperties getLinkProperties(Network network) {
1082 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001083 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001084 if (nai != null) {
1085 synchronized (nai) {
1086 return new LinkProperties(nai.linkProperties);
1087 }
1088 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001089 return null;
1090 }
1091
1092 @Override
1093 public NetworkCapabilities getNetworkCapabilities(Network network) {
1094 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001095 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001096 if (nai != null) {
1097 synchronized (nai) {
1098 return new NetworkCapabilities(nai.networkCapabilities);
1099 }
1100 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001101 return null;
1102 }
1103
1104 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001105 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001106 // Require internal since we're handing out IMSI details
1107 enforceConnectivityInternalPermission();
1108
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001109 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001110 for (Network network : getAllNetworks()) {
1111 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1112 if (nai != null) {
1113 synchronized (nai) {
1114 final String subscriberId = (nai.networkMisc != null)
1115 ? nai.networkMisc.subscriberId : null;
1116 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1117 nai.networkCapabilities, network, subscriberId, null));
1118 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001119 }
1120 }
1121 return result.toArray(new NetworkState[result.size()]);
1122 }
1123
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001124 @Override
1125 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1126 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001127 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001128 final long token = Binder.clearCallingIdentity();
1129 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001130 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1131 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001132 try {
1133 return mPolicyManager.getNetworkQuotaInfo(state);
1134 } catch (RemoteException e) {
1135 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001136 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001137 return null;
1138 } finally {
1139 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001140 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001141 }
1142
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001143 @Override
1144 public boolean isActiveNetworkMetered() {
1145 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001146 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001147 final long token = Binder.clearCallingIdentity();
1148 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001149 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001150 } finally {
1151 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001152 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001153 }
1154
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001155 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1156 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1157 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001158 try {
1159 return mPolicyManager.isNetworkMetered(state);
1160 } catch (RemoteException e) {
1161 }
1162 }
1163 return false;
1164 }
1165
Jeff Sharkey216c1812012-08-05 14:29:23 -07001166 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1167 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001168 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001169 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001170 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001171 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001172 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001173
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001174 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001175 * Ensure that a network route exists to deliver traffic to the specified
1176 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001177 * @param networkType the type of the network over which traffic to the
1178 * specified host is to be routed
1179 * @param hostAddress the IP address of the host to which the route is
1180 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001181 * @return {@code true} on success, {@code false} on failure
1182 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001183 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001184 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001185 if (mProtectedNetworks.contains(networkType)) {
1186 enforceConnectivityInternalPermission();
1187 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001188
Chad Brubakerc0234532014-02-14 13:24:29 -08001189 InetAddress addr;
1190 try {
1191 addr = InetAddress.getByAddress(hostAddress);
1192 } catch (UnknownHostException e) {
1193 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1194 return false;
1195 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001196
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001197 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001198 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001199 return false;
1200 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001201
1202 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1203 if (nai == null) {
1204 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1205 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1206 } else {
1207 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1208 }
1209 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001210 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001211
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001212 DetailedState netState;
1213 synchronized (nai) {
1214 netState = nai.networkInfo.getDetailedState();
1215 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001216
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001217 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001218 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001219 log("requestRouteToHostAddress on down network "
1220 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001221 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001222 }
1223 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001224 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001225
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001226 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001227 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001228 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001229 LinkProperties lp;
1230 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001231 synchronized (nai) {
1232 lp = nai.linkProperties;
1233 netId = nai.network.netId;
1234 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001235 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001236 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1237 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001238 } finally {
1239 Binder.restoreCallingIdentity(token);
1240 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001241 }
1242
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001243 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001244 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001245 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001246 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001247 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001248 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001249 if (bestRoute.getGateway().equals(addr)) {
1250 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001251 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001252 } else {
1253 // if we will connect to this through another route, add a direct route
1254 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001255 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001256 }
1257 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001258 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001259 try {
1260 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1261 } catch (Exception e) {
1262 // never crash - catch them all
1263 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001264 return false;
1265 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001266 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001267 }
1268
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001269 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1270 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001271 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001272 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001273 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001274 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001275 }
1276
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001277 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001278 // skip update when we've already applied rules
1279 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1280 if (oldRules == uidRules) return;
1281
1282 mUidRules.put(uid, uidRules);
1283 }
1284
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001285 // TODO: notify UID when it has requested targeted updates
1286 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001287
1288 @Override
1289 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001290 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001291 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001292 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001293 }
1294
1295 synchronized (mRulesLock) {
1296 mMeteredIfaces.clear();
1297 for (String iface : meteredIfaces) {
1298 mMeteredIfaces.add(iface);
1299 }
1300 }
1301 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001302
1303 @Override
1304 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1305 // caller is NPMS, since we only register with them
1306 if (LOGD_RULES) {
1307 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1308 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001309 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001310 };
1311
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001312 private void enforceInternetPermission() {
1313 mContext.enforceCallingOrSelfPermission(
1314 android.Manifest.permission.INTERNET,
1315 "ConnectivityService");
1316 }
1317
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001318 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001319 mContext.enforceCallingOrSelfPermission(
1320 android.Manifest.permission.ACCESS_NETWORK_STATE,
1321 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001322 }
1323
1324 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001325 mContext.enforceCallingOrSelfPermission(
1326 android.Manifest.permission.CHANGE_NETWORK_STATE,
1327 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001328 }
1329
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001330 private void enforceTetherAccessPermission() {
1331 mContext.enforceCallingOrSelfPermission(
1332 android.Manifest.permission.ACCESS_NETWORK_STATE,
1333 "ConnectivityService");
1334 }
1335
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001336 private void enforceConnectivityInternalPermission() {
1337 mContext.enforceCallingOrSelfPermission(
1338 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1339 "ConnectivityService");
1340 }
1341
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001342 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001343 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001344 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1345 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001346 }
1347
1348 private void sendInetConditionBroadcast(NetworkInfo info) {
1349 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1350 }
1351
Wink Saville628b0852011-08-04 15:01:58 -07001352 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001353 if (mLockdownTracker != null) {
1354 info = mLockdownTracker.augmentNetworkInfo(info);
1355 }
1356
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001357 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001358 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001359 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001360 if (info.isFailover()) {
1361 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1362 info.setFailover(false);
1363 }
1364 if (info.getReason() != null) {
1365 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1366 }
1367 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001368 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1369 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001371 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001372 return intent;
1373 }
1374
1375 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1376 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1377 }
1378
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001379 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001380 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1381 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1382 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001383 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001384 final long ident = Binder.clearCallingIdentity();
1385 try {
1386 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1387 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1388 } finally {
1389 Binder.restoreCallingIdentity(ident);
1390 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001391 }
1392
Mike Lockwood0f79b542009-08-14 14:18:49 -04001393 private void sendStickyBroadcast(Intent intent) {
1394 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001395 if (!mSystemReady) {
1396 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001397 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001398 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001399 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001400 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001401 }
1402
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001403 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001404 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1405 final IBatteryStats bs = BatteryStatsService.getService();
1406 try {
1407 NetworkInfo ni = intent.getParcelableExtra(
1408 ConnectivityManager.EXTRA_NETWORK_INFO);
1409 bs.noteConnectivityChanged(intent.getIntExtra(
1410 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1411 ni != null ? ni.getState().toString() : "?");
1412 } catch (RemoteException e) {
1413 }
1414 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001415 try {
1416 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1417 } finally {
1418 Binder.restoreCallingIdentity(ident);
1419 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001420 }
1421 }
1422
1423 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001424 loadGlobalProxy();
1425
Mike Lockwood0f79b542009-08-14 14:18:49 -04001426 synchronized(this) {
1427 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001428 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001429 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001430 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001431 }
1432 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001433 // load the global proxy at startup
1434 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001435
1436 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1437 // for user to unlock device.
1438 if (!updateLockdownVpn()) {
1439 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1440 mContext.registerReceiver(mUserPresentReceiver, filter);
1441 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001442
1443 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001444
1445 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001446 }
1447
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001448 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1449 @Override
1450 public void onReceive(Context context, Intent intent) {
1451 // Try creating lockdown tracker, since user present usually means
1452 // unlocked keystore.
1453 if (updateLockdownVpn()) {
1454 mContext.unregisterReceiver(this);
1455 }
1456 }
1457 };
1458
Wink Savilled747cbc2013-08-07 16:22:47 -07001459 /** @hide */
1460 @Override
1461 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1462 enforceConnectivityInternalPermission();
1463 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001464// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001465 }
1466
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001467 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001468 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001469 *
1470 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001471 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001472 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001473 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1474 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001475
1476 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001477 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001478
Robert Greenwalt7b816022014-04-18 15:25:25 -07001479 if (networkAgent.networkCapabilities.hasTransport(
1480 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001481 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1482 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001483 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001484 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001485 } else if (networkAgent.networkCapabilities.hasTransport(
1486 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001487 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1488 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Haoyu Bai04124232012-06-28 15:26:19 -07001489 0);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001490 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001491 } else {
1492 // do not track any other networks
1493 timeout = 0;
1494 }
1495
Robert Greenwalt7b816022014-04-18 15:25:25 -07001496 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001497 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001498 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001499 } catch (Exception e) {
1500 // You shall not crash!
1501 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001502 }
1503 }
1504 }
1505
1506 /**
1507 * Remove data activity tracking when network disconnects.
1508 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001509 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1510 final String iface = networkAgent.linkProperties.getInterfaceName();
1511 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001512
Robert Greenwalt7b816022014-04-18 15:25:25 -07001513 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1514 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001515 try {
1516 // the call fails silently if no idletimer setup for this interface
1517 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001518 } catch (Exception e) {
1519 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001520 }
1521 }
1522 }
1523
1524 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001525 * Reads the network specific MTU size from reources.
1526 * and set it on it's iface.
1527 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001528 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1529 final String iface = newLp.getInterfaceName();
1530 final int mtu = newLp.getMtu();
1531 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1532 if (VDBG) log("identical MTU - not setting");
1533 return;
1534 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001535
Robert Greenwalt43074032014-08-15 17:53:05 -07001536 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001537 loge("Unexpected mtu value: " + mtu + ", " + iface);
1538 return;
1539 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001540
w1997615afd812014-08-05 15:18:11 -07001541 // Cannot set MTU without interface name
1542 if (TextUtils.isEmpty(iface)) {
1543 loge("Setting MTU size with null iface.");
1544 return;
1545 }
1546
Robert Greenwalt7b816022014-04-18 15:25:25 -07001547 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001548 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001549 mNetd.setMtu(iface, mtu);
1550 } catch (Exception e) {
1551 Slog.e(TAG, "exception in setMtu()" + e);
1552 }
1553 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001554
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001555 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001556
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001557 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1558 if (isDefaultNetwork(nai) == false) {
1559 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001560 }
1561
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001562 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1563 String[] values = null;
1564 if (tcpBufferSizes != null) {
1565 values = tcpBufferSizes.split(",");
1566 }
1567
1568 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001569 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001570 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1571 values = tcpBufferSizes.split(",");
1572 }
1573
1574 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1575
1576 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001577 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001578
1579 final String prefix = "/sys/kernel/ipv4/tcp_";
1580 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1581 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1582 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1583 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1584 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1585 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1586 mCurrentTcpBufferSizes = tcpBufferSizes;
1587 } catch (IOException e) {
1588 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001589 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001590
1591 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1592 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1593 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1594 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1595 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1596 if (rwndValue != 0) {
1597 SystemProperties.set(sysctlKey, rwndValue.toString());
1598 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001599 }
1600
Mattias Falk8b47b362011-08-23 14:15:13 +02001601 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001602 /*
1603 * Tell the VMs to toss their DNS caches
1604 */
1605 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1606 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001607 /*
1608 * Connectivity events can happen before boot has completed ...
1609 */
1610 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001611 final long ident = Binder.clearCallingIdentity();
1612 try {
1613 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1614 } finally {
1615 Binder.restoreCallingIdentity(ident);
1616 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001617 }
1618
Robert Greenwalt562cc542014-05-15 18:07:26 -07001619 @Override
1620 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001621 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1622 NETWORK_RESTORE_DELAY_PROP_NAME);
1623 if(restoreDefaultNetworkDelayStr != null &&
1624 restoreDefaultNetworkDelayStr.length() != 0) {
1625 try {
1626 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1627 } catch (NumberFormatException e) {
1628 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001629 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001630 // if the system property isn't set, use the value for the apn type
1631 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1632
1633 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1634 (mNetConfigs[networkType] != null)) {
1635 ret = mNetConfigs[networkType].restoreTime;
1636 }
1637 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001638 }
1639
1640 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001641 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1642 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001643 if (mContext.checkCallingOrSelfPermission(
1644 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001645 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001646 pw.println("Permission Denial: can't dump ConnectivityService " +
1647 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1648 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001649 return;
1650 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001651
Robert Greenwalta67be032014-05-16 15:49:14 -07001652 pw.println("NetworkFactories for:");
1653 pw.increaseIndent();
1654 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1655 pw.println(nfi.name);
1656 }
1657 pw.decreaseIndent();
1658 pw.println();
1659
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001660 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1661 pw.print("Active default network: ");
1662 if (defaultNai == null) {
1663 pw.println("none");
1664 } else {
1665 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001666 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001667 pw.println();
1668
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001669 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001670 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001671 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1672 pw.println(nai.toString());
1673 pw.increaseIndent();
1674 pw.println("Requests:");
1675 pw.increaseIndent();
1676 for (int i = 0; i < nai.networkRequests.size(); i++) {
1677 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001678 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001679 pw.decreaseIndent();
1680 pw.println("Lingered:");
1681 pw.increaseIndent();
1682 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1683 pw.decreaseIndent();
1684 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001685 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001686 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001687 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001688
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001689 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001690 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001691 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1692 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001693 }
1694 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001695 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001696
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001697 pw.println("mLegacyTypeTracker:");
1698 pw.increaseIndent();
1699 mLegacyTypeTracker.dump(pw);
1700 pw.decreaseIndent();
1701 pw.println();
1702
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001703 synchronized (this) {
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001704 pw.println("NetworkTransitionWakeLock is currently " +
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001705 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1706 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1707 }
1708 pw.println();
1709
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001710 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001711
1712 if (mInetLog != null) {
1713 pw.println();
1714 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001715 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001716 for(int i = 0; i < mInetLog.size(); i++) {
1717 pw.println(mInetLog.get(i));
1718 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001719 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001720 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001721 }
1722
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001723 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001724 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001725 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001726 if (officialNai != null && officialNai.equals(nai)) return true;
1727 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001728 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001729 " - " + nai);
1730 }
1731 return false;
1732 }
1733
Paul Jensenc8b9a742014-09-30 15:37:41 -04001734 private boolean isRequest(NetworkRequest request) {
1735 return mNetworkRequests.get(request).isRequest;
1736 }
1737
Robert Greenwalt42acef32009-08-12 16:08:25 -07001738 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001739 private class NetworkStateTrackerHandler extends Handler {
1740 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001741 super(looper);
1742 }
1743
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001744 @Override
1745 public void handleMessage(Message msg) {
1746 NetworkInfo info;
1747 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001748 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001749 handleAsyncChannelHalfConnect(msg);
1750 break;
1751 }
1752 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1753 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1754 if (nai != null) nai.asyncChannel.disconnect();
1755 break;
1756 }
1757 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1758 handleAsyncChannelDisconnected(msg);
1759 break;
1760 }
1761 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1762 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1763 if (nai == null) {
1764 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1765 } else {
1766 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001767 }
1768 break;
1769 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001770 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1771 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1772 if (nai == null) {
1773 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1774 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001775 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001776 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001777 "; created=" + nai.created);
1778 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001779 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001780 synchronized (nai) {
1781 nai.linkProperties = (LinkProperties)msg.obj;
1782 }
Paul Jenseneec75412014-08-04 12:21:19 -04001783 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001784 }
1785 break;
1786 }
1787 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1788 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1789 if (nai == null) {
1790 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1791 break;
1792 }
1793 info = (NetworkInfo) msg.obj;
1794 updateNetworkInfo(nai, info);
1795 break;
1796 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001797 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1798 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1799 if (nai == null) {
1800 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1801 break;
1802 }
1803 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001804 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001805 break;
1806 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001807 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1808 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1809 if (nai == null) {
1810 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1811 break;
1812 }
1813 try {
1814 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001815 } catch (Exception e) {
1816 // Never crash!
1817 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001818 }
1819 break;
1820 }
1821 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1822 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1823 if (nai == null) {
1824 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1825 break;
1826 }
1827 try {
1828 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001829 } catch (Exception e) {
1830 // Never crash!
1831 loge("Exception in removeVpnUidRanges: " + e);
1832 }
1833 break;
1834 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001835 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1836 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1837 if (nai == null) {
1838 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1839 break;
1840 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001841 if (nai.created && !nai.networkMisc.explicitlySelected) {
1842 loge("ERROR: created network explicitly selected.");
1843 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001844 nai.networkMisc.explicitlySelected = true;
1845 break;
1846 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001847 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001848 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001849 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001850 boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001851 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001852 if (valid) {
1853 if (DBG) log("Validated " + nai.name());
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001854 if (!nai.everValidated) {
1855 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001856 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1857 ReapUnvalidatedNetworks.REAP);
1858 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001859 sendUpdatedScoreToFactories(nai);
1860 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001861 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001862 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001863 // Let the NetworkAgent know the state of its network
1864 nai.asyncChannel.sendMessage(
1865 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1866 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1867 0, null);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001868 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001869 break;
1870 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001871 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001872 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001873 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1874 handleLingerComplete(nai);
1875 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001876 break;
1877 }
Paul Jensen869868be2014-05-15 10:33:05 -04001878 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001879 if (msg.arg1 == 0) {
1880 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1881 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04001882 NetworkAgentInfo nai = null;
1883 synchronized (mNetworkForNetId) {
1884 nai = mNetworkForNetId.get(msg.arg2);
1885 }
1886 if (nai == null) {
1887 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1888 break;
1889 }
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001890 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
1891 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04001892 }
Paul Jensen869868be2014-05-15 10:33:05 -04001893 break;
1894 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001895 }
1896 }
1897 }
1898
Paul Jensen0cc17322014-11-25 15:26:53 -05001899 // Cancel any lingering so the linger timeout doesn't teardown a network.
1900 // This should be called when a network begins satisfying a NetworkRequest.
1901 // Note: depending on what state the NetworkMonitor is in (e.g.,
1902 // if it's awaiting captive portal login, or if validation failed), this
1903 // may trigger a re-evaluation of the network.
1904 private void unlinger(NetworkAgentInfo nai) {
1905 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05001906 // If network has never been validated, it cannot have been lingered, so don't bother
1907 // needlessly triggering a re-evaluation.
1908 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05001909 nai.networkLingered.clear();
1910 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
1911 }
1912
Robert Greenwalt7b816022014-04-18 15:25:25 -07001913 private void handleAsyncChannelHalfConnect(Message msg) {
1914 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07001915 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001916 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1917 if (VDBG) log("NetworkFactory connected");
1918 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07001919 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07001920 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07001921 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07001922 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04001923 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001924 }
1925 } else {
1926 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07001927 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001928 }
1929 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
1930 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1931 if (VDBG) log("NetworkAgent connected");
1932 // A network agent has requested a connection. Establish the connection.
1933 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
1934 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
1935 } else {
1936 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07001937 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07001938 if (nai != null) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001939 synchronized (mNetworkForNetId) {
1940 mNetworkForNetId.remove(nai.network.netId);
1941 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09001942 // Just in case.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001943 mLegacyTypeTracker.remove(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07001944 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001945 }
1946 }
1947 }
Paul Jensen0cc17322014-11-25 15:26:53 -05001948
Robert Greenwalt7b816022014-04-18 15:25:25 -07001949 private void handleAsyncChannelDisconnected(Message msg) {
1950 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1951 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07001952 if (DBG) {
1953 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
1954 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001955 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04001956 if (nai.created) {
1957 // Tell netd to clean up the configuration for this network
1958 // (routing rules, DNS, etc).
1959 try {
1960 mNetd.removeNetwork(nai.network.netId);
1961 } catch (Exception e) {
1962 loge("Exception removing network: " + e);
1963 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001964 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07001965 // TODO - if we move the logic to the network agent (have them disconnect
1966 // because they lost all their requests or because their score isn't good)
1967 // then they would disconnect organically, report their new state and then
1968 // disconnect the channel.
1969 if (nai.networkInfo.isConnected()) {
1970 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
1971 null, null);
1972 }
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07001973 if (isDefaultNetwork(nai)) {
1974 mDefaultInetConditionPublished = 0;
1975 }
Jeff Sharkey69736342014-12-08 14:50:12 -08001976 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07001977 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04001978 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04001979 mNetworkAgentInfos.remove(msg.replyTo);
1980 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001981 mLegacyTypeTracker.remove(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001982 synchronized (mNetworkForNetId) {
1983 mNetworkForNetId.remove(nai.network.netId);
1984 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001985 // Since we've lost the network, go through all the requests that
1986 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001987 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04001988 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07001989 for (int i = 0; i < nai.networkRequests.size(); i++) {
1990 NetworkRequest request = nai.networkRequests.valueAt(i);
1991 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
1992 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001993 if (DBG) {
1994 log("Checking for replacement network to handle request " + request );
1995 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001996 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001997 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04001998 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05001999 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2000 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002001 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002002 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002003 alternative = existing;
2004 }
2005 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002006 if (alternative != null) {
2007 if (DBG) log(" found replacement in " + alternative.name());
2008 if (!toActivate.contains(alternative)) {
2009 toActivate.add(alternative);
2010 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002011 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002012 }
2013 }
2014 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2015 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002016 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002017 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002018 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002019 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002020 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002021 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2022 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002023 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002024 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302025 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2026 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002027 }
2028
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002029 // If this method proves to be too slow then we can maintain a separate
2030 // pendingIntent => NetworkRequestInfo map.
2031 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2032 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2033 Intent intent = pendingIntent.getIntent();
2034 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2035 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2036 if (existingPendingIntent != null &&
2037 existingPendingIntent.getIntent().filterEquals(intent)) {
2038 return entry.getValue();
2039 }
2040 }
2041 return null;
2042 }
2043
2044 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2045 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2046
2047 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2048 if (existingRequest != null) { // remove the existing request.
2049 if (DBG) log("Replacing " + existingRequest.request + " with "
2050 + nri.request + " because their intents matched.");
2051 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2052 }
2053 handleRegisterNetworkRequest(msg);
2054 }
2055
Robert Greenwalt9258c642014-03-26 16:47:06 -07002056 private void handleRegisterNetworkRequest(Message msg) {
2057 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002058
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002059 mNetworkRequests.put(nri.request, nri);
2060
Paul Jensen0cc17322014-11-25 15:26:53 -05002061 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2062
Robert Greenwalt9258c642014-03-26 16:47:06 -07002063 // Check for the best currently alive network that satisfies this request
2064 NetworkAgentInfo bestNetwork = null;
2065 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002066 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002067 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002068 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002069 if (!nri.isRequest) {
2070 // Not setting bestNetwork here as a listening NetworkRequest may be
2071 // satisfied by multiple Networks. Instead the request is added to
2072 // each satisfying Network and notified about each.
2073 network.addRequest(nri.request);
2074 notifyNetworkCallback(network, nri);
2075 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002076 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002077 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002078 }
2079 }
2080 }
2081 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002082 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002083 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002084 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002085 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002086 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002087 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002088 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2089 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002090 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002091
Lorenzo Colittia793a672014-07-31 23:20:17 +09002092 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002093 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002094 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002095 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002096 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002097 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002098 }
2099 }
2100 }
2101
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002102 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2103 int callingUid) {
2104 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2105 if (nri != null) {
2106 handleReleaseNetworkRequest(nri.request, callingUid);
2107 }
2108 }
2109
Paul Jensen99364842014-12-09 11:43:45 -05002110 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2111 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2112 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2113 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2114 private boolean unneeded(NetworkAgentInfo nai) {
2115 if (!nai.created || nai.isVPN()) return false;
2116 boolean unneeded = true;
2117 if (nai.everValidated) {
2118 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2119 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2120 try {
2121 if (isRequest(nr)) unneeded = false;
2122 } catch (Exception e) {
2123 loge("Request " + nr + " not found in mNetworkRequests.");
2124 loge(" it came from request list of " + nai.name());
2125 }
2126 }
2127 } else {
2128 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2129 // If this Network is already the highest scoring Network for a request, or if
2130 // there is hope for it to become one if it validated, then it is needed.
2131 if (nri.isRequest && nai.satisfies(nri.request) &&
2132 (nai.networkRequests.get(nri.request.requestId) != null ||
2133 // Note that this catches two important cases:
2134 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2135 // is currently satisfying the request. This is desirable when
2136 // cellular ends up validating but WiFi does not.
2137 // 2. Unvalidated WiFi will not be reaped when validated cellular
2138 // is currently satsifying the request. This is desirable when
2139 // WiFi ends up validating and out scoring cellular.
2140 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2141 nai.getCurrentScoreAsValidated())) {
2142 unneeded = false;
2143 break;
2144 }
2145 }
2146 }
2147 return unneeded;
2148 }
2149
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002150 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2151 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002152 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002153 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002154 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2155 return;
2156 }
2157 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002158 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002159 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002160 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002161 // Find all networks that are satisfying this request and remove the request
2162 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002163 // TODO - it's my understanding that for a request there is only a single
2164 // network satisfying it, so this loop is wasteful
2165 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002166 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2167 if (nai.networkRequests.get(nri.request.requestId) != null) {
2168 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002169 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002170 log(" Removing from current network " + nai.name() +
2171 ", leaving " + nai.networkRequests.size() +
2172 " requests.");
2173 }
Paul Jensen99364842014-12-09 11:43:45 -05002174 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002175 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002176 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002177 } else {
2178 // suspect there should only be one pass through here
2179 // but if any were kept do the check below
2180 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002181 }
2182 }
2183 }
2184
Robert Greenwalt51481852015-01-08 14:43:31 -08002185 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2186 if (nai != null) {
2187 mNetworkForRequestId.remove(nri.request.requestId);
2188 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002189 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002190 // that a network connected to serve it, even though the network was already
2191 // connected. Now that this request has gone away, we might have to pretend
2192 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002193 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002194 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2195 boolean doRemove = true;
2196 if (wasKept) {
2197 // check if any of the remaining requests for this network are for the
2198 // same legacy type - if so, don't remove the nai
2199 for (int i = 0; i < nai.networkRequests.size(); i++) {
2200 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2201 if (otherRequest.legacyType == nri.request.legacyType &&
2202 isRequest(otherRequest)) {
2203 if (DBG) log(" still have other legacy request - leaving");
2204 doRemove = false;
2205 }
2206 }
2207 }
2208
2209 if (doRemove) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002210 mLegacyTypeTracker.remove(nri.request.legacyType, nai);
2211 }
2212 }
2213
Robert Greenwalta67be032014-05-16 15:49:14 -07002214 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002215 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2216 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002217 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002218 } else {
2219 // listens don't have a singular affectedNetwork. Check all networks to see
2220 // if this listen request applies and remove it.
2221 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2222 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002223 }
2224 }
2225 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2226 }
2227 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002228
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002229 private class InternalHandler extends Handler {
2230 public InternalHandler(Looper looper) {
2231 super(looper);
2232 }
2233
2234 @Override
2235 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002236 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002237 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002238 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002239 String causedBy = null;
2240 synchronized (ConnectivityService.this) {
2241 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2242 mNetTransitionWakeLock.isHeld()) {
2243 mNetTransitionWakeLock.release();
2244 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002245 } else {
2246 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002247 }
2248 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002249 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2250 log("Failed to find a new network - expiring NetTransition Wakelock");
2251 } else {
2252 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2253 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002254 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002255 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002256 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002257 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002258 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002259 break;
2260 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002261 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002262 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002263 sendStickyBroadcast(intent);
2264 break;
2265 }
Jason Monkdecd2952013-10-10 14:02:51 -04002266 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002267 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002268 break;
2269 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002270 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002271 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2272 break;
2273 }
2274 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2275 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002276 break;
2277 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002278 case EVENT_REGISTER_NETWORK_AGENT: {
2279 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2280 break;
2281 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002282 case EVENT_REGISTER_NETWORK_REQUEST:
2283 case EVENT_REGISTER_NETWORK_LISTENER: {
2284 handleRegisterNetworkRequest(msg);
2285 break;
2286 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002287 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2288 handleRegisterNetworkRequestWithIntent(msg);
2289 break;
2290 }
2291 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2292 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2293 break;
2294 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002295 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002296 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002297 break;
2298 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002299 case EVENT_SYSTEM_READY: {
2300 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2301 nai.networkMonitor.systemReady = true;
2302 }
2303 break;
2304 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002305 }
2306 }
2307 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002308
2309 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002310 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002311 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002312 if (isTetheringSupported()) {
2313 return mTethering.tether(iface);
2314 } else {
2315 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2316 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002317 }
2318
2319 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002320 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002321 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002322
2323 if (isTetheringSupported()) {
2324 return mTethering.untether(iface);
2325 } else {
2326 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2327 }
2328 }
2329
2330 // javadoc from interface
2331 public int getLastTetherError(String iface) {
2332 enforceTetherAccessPermission();
2333
2334 if (isTetheringSupported()) {
2335 return mTethering.getLastTetherError(iface);
2336 } else {
2337 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2338 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002339 }
2340
2341 // TODO - proper iface API for selection by property, inspection, etc
2342 public String[] getTetherableUsbRegexs() {
2343 enforceTetherAccessPermission();
2344 if (isTetheringSupported()) {
2345 return mTethering.getTetherableUsbRegexs();
2346 } else {
2347 return new String[0];
2348 }
2349 }
2350
2351 public String[] getTetherableWifiRegexs() {
2352 enforceTetherAccessPermission();
2353 if (isTetheringSupported()) {
2354 return mTethering.getTetherableWifiRegexs();
2355 } else {
2356 return new String[0];
2357 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002358 }
2359
Danica Chang6fdd0c62010-08-11 14:54:43 -07002360 public String[] getTetherableBluetoothRegexs() {
2361 enforceTetherAccessPermission();
2362 if (isTetheringSupported()) {
2363 return mTethering.getTetherableBluetoothRegexs();
2364 } else {
2365 return new String[0];
2366 }
2367 }
2368
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002369 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002370 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002371 if (isTetheringSupported()) {
2372 return mTethering.setUsbTethering(enable);
2373 } else {
2374 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2375 }
2376 }
2377
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002378 // TODO - move iface listing, queries, etc to new module
2379 // javadoc from interface
2380 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002381 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002382 return mTethering.getTetherableIfaces();
2383 }
2384
2385 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002386 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002387 return mTethering.getTetheredIfaces();
2388 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002389
Robert Greenwalt5a735062010-03-02 17:25:02 -08002390 public String[] getTetheringErroredIfaces() {
2391 enforceTetherAccessPermission();
2392 return mTethering.getErroredIfaces();
2393 }
2394
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002395 public String[] getTetheredDhcpRanges() {
2396 enforceConnectivityInternalPermission();
2397 return mTethering.getTetheredDhcpRanges();
2398 }
2399
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002400 // if ro.tether.denied = true we default to no tethering
2401 // gservices could set the secure setting to 1 though to enable it on a build where it
2402 // had previously been turned off.
2403 public boolean isTetheringSupported() {
2404 enforceTetherAccessPermission();
2405 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002406 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002407 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2408 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002409 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2410 mTethering.getTetherableWifiRegexs().length != 0 ||
2411 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2412 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002413 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002414
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002415 // Called when we lose the default network and have no replacement yet.
2416 // This will automatically be cleared after X seconds or a new default network
2417 // becomes CONNECTED, whichever happens first. The timer is started by the
2418 // first caller and not restarted by subsequent callers.
2419 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002420 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002421 synchronized (this) {
2422 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002423 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002424 mNetTransitionWakeLock.acquire();
2425 mNetTransitionWakeLockCausedBy = forWhom;
2426 }
2427 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002428 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002429 mNetTransitionWakeLockTimeout);
2430 return;
2431 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002432
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002433 // 100 percent is full good, 0 is full bad.
2434 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002435 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002436 if (nai == null) return;
2437 boolean isGood = percentage > 50;
2438 // Revalidate if the app report does not match our current validated state.
2439 if (isGood != nai.lastValidated) {
2440 // Make the message logged by reportBadNetwork below less confusing.
2441 if (DBG && isGood) log("reportInetCondition: type=" + networkType + " ok, revalidate");
2442 reportBadNetwork(nai.network);
2443 }
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002444 }
2445
Robert Greenwalt9258c642014-03-26 16:47:06 -07002446 public void reportBadNetwork(Network network) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002447 enforceAccessPermission();
2448 enforceInternetPermission();
2449
2450 if (network == null) return;
2451
2452 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002453 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002454 if (nai == null) return;
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002455 if (DBG) log("reportBadNetwork(" + nai.name() + ") by " + uid);
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002456 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002457 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2458 // which isn't meant to work on uncreated networks.
2459 if (!nai.created) return;
2460
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002461 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002462
2463 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2464 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002465 }
2466
Paul Jensene0bef712014-12-10 15:12:18 -05002467 public ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002468 // this information is already available as a world read/writable jvm property
2469 // so this API change wouldn't have a benifit. It also breaks the passing
2470 // of proxy info to all the JVMs.
2471 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002472 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002473 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002474 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2475 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002476 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002477 }
2478
Paul Jensene0bef712014-12-10 15:12:18 -05002479 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2480 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2481 // proxy is null then there is no proxy in place).
2482 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2483 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2484 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2485 proxy = null;
2486 }
2487 return proxy;
2488 }
2489
2490 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2491 // better for determining if a new proxy broadcast is necessary:
2492 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2493 // avoid unnecessary broadcasts.
2494 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2495 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2496 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2497 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2498 // all set.
2499 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2500 a = canonicalizeProxyInfo(a);
2501 b = canonicalizeProxyInfo(b);
2502 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2503 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2504 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2505 }
2506
Jason Monk207900c2014-04-25 15:00:09 -04002507 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002508 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002509
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002510 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002511 if (proxyProperties == mGlobalProxy) return;
2512 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2513 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2514
2515 String host = "";
2516 int port = 0;
2517 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002518 String pacFileUrl = "";
2519 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002520 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002521 if (!proxyProperties.isValid()) {
2522 if (DBG)
2523 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2524 return;
2525 }
Jason Monk207900c2014-04-25 15:00:09 -04002526 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002527 host = mGlobalProxy.getHost();
2528 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002529 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002530 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002531 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002532 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002533 } else {
2534 mGlobalProxy = null;
2535 }
2536 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002537 final long token = Binder.clearCallingIdentity();
2538 try {
2539 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2540 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2541 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2542 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002543 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002544 } finally {
2545 Binder.restoreCallingIdentity(token);
2546 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002547
Jason Monkcf0f97a2014-10-02 15:39:38 -04002548 if (mGlobalProxy == null) {
2549 proxyProperties = mDefaultProxy;
2550 }
2551 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002552 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002553 }
2554
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002555 private void loadGlobalProxy() {
2556 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002557 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2558 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2559 String exclList = Settings.Global.getString(res,
2560 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002561 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2562 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002563 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002564 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002565 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002566 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002567 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002568 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002569 if (!proxyProperties.isValid()) {
2570 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2571 return;
2572 }
2573
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002574 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002575 mGlobalProxy = proxyProperties;
2576 }
2577 }
2578 }
2579
Jason Monk207900c2014-04-25 15:00:09 -04002580 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002581 // this information is already available as a world read/writable jvm property
2582 // so this API change wouldn't have a benifit. It also breaks the passing
2583 // of proxy info to all the JVMs.
2584 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002585 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002586 return mGlobalProxy;
2587 }
2588 }
2589
Jason Monk207900c2014-04-25 15:00:09 -04002590 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002591 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002592 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002593 proxy = null;
2594 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002595 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002596 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002597 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002598 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002599 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2600 return;
2601 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002602
2603 // This call could be coming from the PacManager, containing the port of the local
2604 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2605 // global (to get the correct local port), and send a broadcast.
2606 // TODO: Switch PacManager to have its own message to send back rather than
2607 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002608 if ((mGlobalProxy != null) && (proxy != null)
2609 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002610 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2611 mGlobalProxy = proxy;
2612 sendProxyBroadcast(mGlobalProxy);
2613 return;
2614 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002615 mDefaultProxy = proxy;
2616
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002617 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002618 if (!mDefaultProxyDisabled) {
2619 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002620 }
2621 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002622 }
2623
Paul Jensene0bef712014-12-10 15:12:18 -05002624 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2625 // This method gets called when any network changes proxy, but the broadcast only ever contains
2626 // the default proxy (even if it hasn't changed).
2627 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2628 // world where an app might be bound to a non-default network.
2629 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2630 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2631 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2632
2633 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2634 sendProxyBroadcast(getDefaultProxy());
2635 }
2636 }
2637
Robert Greenwalt434203a2010-10-11 16:00:27 -07002638 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002639 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2640 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002641 if (!TextUtils.isEmpty(proxy)) {
2642 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002643 if (data.length == 0) {
2644 return;
2645 }
2646
Robert Greenwalt434203a2010-10-11 16:00:27 -07002647 String proxyHost = data[0];
2648 int proxyPort = 8080;
2649 if (data.length > 1) {
2650 try {
2651 proxyPort = Integer.parseInt(data[1]);
2652 } catch (NumberFormatException e) {
2653 return;
2654 }
2655 }
Jason Monk207900c2014-04-25 15:00:09 -04002656 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002657 setGlobalProxy(p);
2658 }
2659 }
2660
Jason Monk207900c2014-04-25 15:00:09 -04002661 private void sendProxyBroadcast(ProxyInfo proxy) {
2662 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002663 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002664 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002665 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002666 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2667 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002668 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002669 final long ident = Binder.clearCallingIdentity();
2670 try {
2671 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2672 } finally {
2673 Binder.restoreCallingIdentity(ident);
2674 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002675 }
2676
2677 private static class SettingsObserver extends ContentObserver {
2678 private int mWhat;
2679 private Handler mHandler;
2680 SettingsObserver(Handler handler, int what) {
2681 super(handler);
2682 mHandler = handler;
2683 mWhat = what;
2684 }
2685
2686 void observe(Context context) {
2687 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002688 resolver.registerContentObserver(Settings.Global.getUriFor(
2689 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002690 }
2691
2692 @Override
2693 public void onChange(boolean selfChange) {
2694 mHandler.obtainMessage(mWhat).sendToTarget();
2695 }
2696 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002697
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002698 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002699 Slog.d(TAG, s);
2700 }
2701
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002702 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002703 Slog.e(TAG, s);
2704 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002705
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002706 private static <T> T checkNotNull(T value, String message) {
2707 if (value == null) {
2708 throw new NullPointerException(message);
2709 }
2710 return value;
2711 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002712
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002713 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002714 * Prepare for a VPN application.
Jeff Davidson9a1da682014-11-11 13:52:58 -08002715 * Permissions are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002716 * @hide
2717 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002718 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002719 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002720 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002721 int user = UserHandle.getUserId(Binder.getCallingUid());
2722 synchronized(mVpns) {
2723 return mVpns.get(user).prepare(oldPackage, newPackage);
2724 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002725 }
2726
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002727 /**
Jeff Davidson05542602014-08-11 14:07:27 -07002728 * Set whether the current VPN package has the ability to launch VPNs without
Jeff Davidson9a1da682014-11-11 13:52:58 -08002729 * user intervention. This method is used by system-privileged apps.
2730 * Permissions are checked in Vpn class.
Jeff Davidson05542602014-08-11 14:07:27 -07002731 * @hide
2732 */
2733 @Override
2734 public void setVpnPackageAuthorization(boolean authorized) {
2735 int user = UserHandle.getUserId(Binder.getCallingUid());
2736 synchronized(mVpns) {
2737 mVpns.get(user).setPackageAuthorization(authorized);
2738 }
2739 }
2740
2741 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002742 * Configure a TUN interface and return its file descriptor. Parameters
2743 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002744 * and not available in ConnectivityManager. Permissions are checked in
2745 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002746 * @hide
2747 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002748 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002749 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002750 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002751 int user = UserHandle.getUserId(Binder.getCallingUid());
2752 synchronized(mVpns) {
2753 return mVpns.get(user).establish(config);
2754 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002755 }
2756
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002757 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07002758 * Start legacy VPN, controlling native daemons as needed. Creates a
2759 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002760 */
2761 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07002762 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002763 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07002764 final LinkProperties egress = getActiveLinkProperties();
2765 if (egress == null) {
2766 throw new IllegalStateException("Missing active network connection");
2767 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002768 int user = UserHandle.getUserId(Binder.getCallingUid());
2769 synchronized(mVpns) {
2770 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2771 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002772 }
2773
2774 /**
2775 * Return the information of the ongoing legacy VPN. This method is used
2776 * by VpnSettings and not available in ConnectivityManager. Permissions
2777 * are checked in Vpn class.
2778 * @hide
2779 */
2780 @Override
2781 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002782 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002783 int user = UserHandle.getUserId(Binder.getCallingUid());
2784 synchronized(mVpns) {
2785 return mVpns.get(user).getLegacyVpnInfo();
2786 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002787 }
2788
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002789 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07002790 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
2791 * not available in ConnectivityManager.
2792 * Permissions are checked in Vpn class.
2793 * @hide
2794 */
2795 @Override
2796 public VpnConfig getVpnConfig() {
2797 int user = UserHandle.getUserId(Binder.getCallingUid());
2798 synchronized(mVpns) {
2799 return mVpns.get(user).getVpnConfig();
2800 }
2801 }
2802
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002803 @Override
2804 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08002805 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
2806 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
2807 return false;
2808 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002809
2810 // Tear down existing lockdown if profile was removed
2811 mLockdownEnabled = LockdownVpnTracker.isEnabled();
2812 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08002813 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002814 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
2815 return false;
2816 }
2817
2818 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
2819 final VpnProfile profile = VpnProfile.decode(
2820 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002821 int user = UserHandle.getUserId(Binder.getCallingUid());
2822 synchronized(mVpns) {
2823 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
2824 profile));
2825 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002826 } else {
2827 setLockdownTracker(null);
2828 }
2829
2830 return true;
2831 }
2832
2833 /**
2834 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
2835 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
2836 */
2837 private void setLockdownTracker(LockdownVpnTracker tracker) {
2838 // Shutdown any existing tracker
2839 final LockdownVpnTracker existing = mLockdownTracker;
2840 mLockdownTracker = null;
2841 if (existing != null) {
2842 existing.shutdown();
2843 }
2844
2845 try {
2846 if (tracker != null) {
2847 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08002848 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002849 mLockdownTracker = tracker;
2850 mLockdownTracker.init();
2851 } else {
2852 mNetd.setFirewallEnabled(false);
2853 }
2854 } catch (RemoteException e) {
2855 // ignored; NMS lives inside system_server
2856 }
2857 }
2858
2859 private void throwIfLockdownEnabled() {
2860 if (mLockdownEnabled) {
2861 throw new IllegalStateException("Unavailable in lockdown mode");
2862 }
2863 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07002864
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07002865 public int findConnectionTypeForIface(String iface) {
2866 enforceConnectivityInternalPermission();
2867
2868 if (TextUtils.isEmpty(iface)) return ConnectivityManager.TYPE_NONE;
Lorenzo Colitti1c3a35b2014-08-19 21:31:08 -07002869
2870 synchronized(mNetworkForNetId) {
2871 for (int i = 0; i < mNetworkForNetId.size(); i++) {
2872 NetworkAgentInfo nai = mNetworkForNetId.valueAt(i);
2873 LinkProperties lp = nai.linkProperties;
2874 if (lp != null && iface.equals(lp.getInterfaceName()) && nai.networkInfo != null) {
2875 return nai.networkInfo.getType();
Robert Greenwalt1b0ca9d2013-04-22 11:13:02 -07002876 }
2877 }
2878 }
2879 return ConnectivityManager.TYPE_NONE;
2880 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002881
Wink Savilleab9321d2013-06-29 21:10:57 -07002882 @Override
Wink Saville948282b2013-08-29 08:55:16 -07002883 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04002884 // TODO: Remove? Any reason to trigger a provisioning check?
2885 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07002886 }
2887
2888 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
2889 private volatile boolean mIsNotificationVisible = false;
2890
Paul Jensen89e0f092014-09-15 15:59:36 -04002891 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07002892 if (DBG) {
2893 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04002894 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07002895 }
Paul Jensen89e0f092014-09-15 15:59:36 -04002896 Intent intent = new Intent(action);
2897 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002898 // Concatenate the range of types onto the range of NetIDs.
2899 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04002900 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04002901 }
2902
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002903 /**
2904 * Show or hide network provisioning notificaitons.
2905 *
2906 * @param id an identifier that uniquely identifies this notification. This must match
2907 * between show and hide calls. We use the NetID value but for legacy callers
2908 * we concatenate the range of types with the range of NetIDs.
2909 */
2910 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04002911 String extraInfo, PendingIntent intent) {
2912 if (DBG) {
2913 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
2914 networkType + " extraInfo=" + extraInfo);
2915 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002916
2917 Resources r = Resources.getSystem();
2918 NotificationManager notificationManager = (NotificationManager) mContext
2919 .getSystemService(Context.NOTIFICATION_SERVICE);
2920
2921 if (visible) {
2922 CharSequence title;
2923 CharSequence details;
2924 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07002925 Notification notification = new Notification();
2926 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07002927 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07002928 title = r.getString(R.string.wifi_available_sign_in, 0);
2929 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07002930 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07002931 icon = R.drawable.stat_notify_wifi_in_range;
2932 break;
2933 case ConnectivityManager.TYPE_MOBILE:
2934 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07002935 title = r.getString(R.string.network_available_sign_in, 0);
2936 // TODO: Change this to pull from NetworkInfo once a printable
2937 // name has been added to it
2938 details = mTelephonyManager.getNetworkOperatorName();
2939 icon = R.drawable.stat_notify_rssi_in_range;
2940 break;
2941 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07002942 title = r.getString(R.string.network_available_sign_in, 0);
2943 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07002944 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07002945 icon = R.drawable.stat_notify_rssi_in_range;
2946 break;
2947 }
2948
Wink Savilleab9321d2013-06-29 21:10:57 -07002949 notification.when = 0;
2950 notification.icon = icon;
2951 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07002952 notification.tickerText = title;
Selim Cinek255dd042014-08-19 22:29:02 +02002953 notification.color = mContext.getResources().getColor(
2954 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07002955 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04002956 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07002957
Wink Saville948282b2013-08-29 08:55:16 -07002958 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002959 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07002960 } catch (NullPointerException npe) {
2961 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
2962 npe.printStackTrace();
2963 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002964 } else {
Wink Saville948282b2013-08-29 08:55:16 -07002965 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002966 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07002967 } catch (NullPointerException npe) {
2968 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
2969 npe.printStackTrace();
2970 }
Wink Savilleab9321d2013-06-29 21:10:57 -07002971 }
Wink Saville948282b2013-08-29 08:55:16 -07002972 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07002973 }
2974
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002975 /** Location to an updatable file listing carrier provisioning urls.
2976 * An example:
2977 *
2978 * <?xml version="1.0" encoding="utf-8"?>
2979 * <provisioningUrls>
2980 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
2981 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
2982 * </provisioningUrls>
2983 */
2984 private static final String PROVISIONING_URL_PATH =
2985 "/data/misc/radio/provisioning_urls.xml";
2986 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07002987
Robert Greenwalte182bfe2013-07-16 12:06:09 -07002988 /** XML tag for root element. */
2989 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
2990 /** XML tag for individual url */
2991 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
2992 /** XML tag for redirected url */
2993 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
2994 /** XML attribute for mcc */
2995 private static final String ATTR_MCC = "mcc";
2996 /** XML attribute for mnc */
2997 private static final String ATTR_MNC = "mnc";
2998
2999 private static final int REDIRECTED_PROVISIONING = 1;
3000 private static final int PROVISIONING = 2;
3001
3002 private String getProvisioningUrlBaseFromFile(int type) {
3003 FileReader fileReader = null;
3004 XmlPullParser parser = null;
3005 Configuration config = mContext.getResources().getConfiguration();
3006 String tagType;
3007
3008 switch (type) {
3009 case PROVISIONING:
3010 tagType = TAG_PROVISIONING_URL;
3011 break;
3012 case REDIRECTED_PROVISIONING:
3013 tagType = TAG_REDIRECTED_URL;
3014 break;
3015 default:
3016 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3017 type);
3018 }
3019
3020 try {
3021 fileReader = new FileReader(mProvisioningUrlFile);
3022 parser = Xml.newPullParser();
3023 parser.setInput(fileReader);
3024 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3025
3026 while (true) {
3027 XmlUtils.nextElement(parser);
3028
3029 String element = parser.getName();
3030 if (element == null) break;
3031
3032 if (element.equals(tagType)) {
3033 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3034 try {
3035 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3036 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3037 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3038 parser.next();
3039 if (parser.getEventType() == XmlPullParser.TEXT) {
3040 return parser.getText();
3041 }
3042 }
3043 }
3044 } catch (NumberFormatException e) {
3045 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3046 }
3047 }
3048 }
3049 return null;
3050 } catch (FileNotFoundException e) {
3051 loge("Carrier Provisioning Urls file not found");
3052 } catch (XmlPullParserException e) {
3053 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3054 } catch (IOException e) {
3055 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3056 } finally {
3057 if (fileReader != null) {
3058 try {
3059 fileReader.close();
3060 } catch (IOException e) {}
3061 }
3062 }
3063 return null;
3064 }
3065
Wink Saville42d4f082013-07-20 20:31:59 -07003066 @Override
3067 public String getMobileRedirectedProvisioningUrl() {
3068 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003069 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3070 if (TextUtils.isEmpty(url)) {
3071 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3072 }
3073 return url;
3074 }
3075
Wink Saville42d4f082013-07-20 20:31:59 -07003076 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003077 public String getMobileProvisioningUrl() {
3078 enforceConnectivityInternalPermission();
3079 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3080 if (TextUtils.isEmpty(url)) {
3081 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003082 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003083 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003084 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003085 }
Wink Saville8cf35602013-07-10 23:00:07 -07003086 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003087 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003088 String phoneNumber = mTelephonyManager.getLine1Number();
3089 if (TextUtils.isEmpty(phoneNumber)) {
3090 phoneNumber = "0000000000";
3091 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003092 url = String.format(url,
3093 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3094 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003095 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003096 }
3097
Wink Savilleab9321d2013-06-29 21:10:57 -07003098 return url;
3099 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003100
Wink Saville948282b2013-08-29 08:55:16 -07003101 @Override
3102 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003103 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003104 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003105 final long ident = Binder.clearCallingIdentity();
3106 try {
3107 setProvNotificationVisible(visible, networkType, action);
3108 } finally {
3109 Binder.restoreCallingIdentity(ident);
3110 }
Wink Saville948282b2013-08-29 08:55:16 -07003111 }
Wink Saville7788c612013-08-29 14:57:08 -07003112
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003113 @Override
3114 public void setAirplaneMode(boolean enable) {
3115 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003116 final long ident = Binder.clearCallingIdentity();
3117 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003118 final ContentResolver cr = mContext.getContentResolver();
3119 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3120 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3121 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003122 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003123 } finally {
3124 Binder.restoreCallingIdentity(ident);
3125 }
3126 }
3127
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003128 private void onUserStart(int userId) {
3129 synchronized(mVpns) {
3130 Vpn userVpn = mVpns.get(userId);
3131 if (userVpn != null) {
3132 loge("Starting user already has a VPN");
3133 return;
3134 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04003135 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, this, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003136 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003137 }
3138 }
3139
3140 private void onUserStop(int userId) {
3141 synchronized(mVpns) {
3142 Vpn userVpn = mVpns.get(userId);
3143 if (userVpn == null) {
3144 loge("Stopping user has no VPN");
3145 return;
3146 }
3147 mVpns.delete(userId);
3148 }
3149 }
3150
3151 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3152 @Override
3153 public void onReceive(Context context, Intent intent) {
3154 final String action = intent.getAction();
3155 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3156 if (userId == UserHandle.USER_NULL) return;
3157
3158 if (Intent.ACTION_USER_STARTING.equals(action)) {
3159 onUserStart(userId);
3160 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3161 onUserStop(userId);
3162 }
3163 }
3164 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003165
Robert Greenwalta67be032014-05-16 15:49:14 -07003166 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3167 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003168 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3169 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003170
Robert Greenwalta67be032014-05-16 15:49:14 -07003171 private static class NetworkFactoryInfo {
3172 public final String name;
3173 public final Messenger messenger;
3174 public final AsyncChannel asyncChannel;
3175
3176 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3177 this.name = name;
3178 this.messenger = messenger;
3179 this.asyncChannel = asyncChannel;
3180 }
3181 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003182
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003183 /**
3184 * Tracks info about the requester.
3185 * Also used to notice when the calling process dies so we can self-expire
3186 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003187 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3188 static final boolean REQUEST = true;
3189 static final boolean LISTEN = false;
3190
3191 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003192 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003193 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003194 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003195 final int mPid;
3196 final int mUid;
3197 final Messenger messenger;
3198 final boolean isRequest;
3199
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003200 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3201 request = r;
3202 mPendingIntent = pi;
3203 messenger = null;
3204 mBinder = null;
3205 mPid = getCallingPid();
3206 mUid = getCallingUid();
3207 this.isRequest = isRequest;
3208 }
3209
Robert Greenwalt9258c642014-03-26 16:47:06 -07003210 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3211 super();
3212 messenger = m;
3213 request = r;
3214 mBinder = binder;
3215 mPid = getCallingPid();
3216 mUid = getCallingUid();
3217 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003218 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003219
3220 try {
3221 mBinder.linkToDeath(this, 0);
3222 } catch (RemoteException e) {
3223 binderDied();
3224 }
3225 }
3226
3227 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003228 if (mBinder != null) {
3229 mBinder.unlinkToDeath(this, 0);
3230 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003231 }
3232
3233 public void binderDied() {
3234 log("ConnectivityService NetworkRequestInfo binderDied(" +
3235 request + ", " + mBinder + ")");
3236 releaseNetworkRequest(request);
3237 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003238
3239 public String toString() {
3240 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003241 mPid + " for " + request +
3242 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003243 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003244 }
3245
3246 @Override
3247 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003248 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003249 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003250 enforceNetworkRequestPermissions(networkCapabilities);
3251 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003252
Robert Greenwalt6078b502014-06-11 16:05:07 -07003253 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003254 throw new IllegalArgumentException("Bad timeout specified");
3255 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003256
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003257 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3258 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003259 if (DBG) log("requestNetwork for " + networkRequest);
3260 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3261 NetworkRequestInfo.REQUEST);
3262
3263 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003264 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003265 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003266 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003267 }
3268 return networkRequest;
3269 }
3270
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003271 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3272 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3273 == false) {
3274 enforceConnectivityInternalPermission();
3275 } else {
3276 enforceChangePermission();
3277 }
3278 }
3279
3280 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3281 // if UID is restricted, don't allow them to bring up metered APNs
3282 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
3283 == false) {
3284 final int uidRules;
3285 final int uid = Binder.getCallingUid();
3286 synchronized(mRulesLock) {
3287 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3288 }
3289 if ((uidRules & RULE_REJECT_METERED) != 0) {
3290 // we could silently fail or we can filter the available nets to only give
3291 // them those they have access to. Chose the more useful
3292 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3293 }
3294 }
3295 }
3296
Robert Greenwalt9258c642014-03-26 16:47:06 -07003297 @Override
3298 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3299 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003300 checkNotNull(operation, "PendingIntent cannot be null.");
3301 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3302 enforceNetworkRequestPermissions(networkCapabilities);
3303 enforceMeteredApnPolicy(networkCapabilities);
3304
3305 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3306 nextNetworkRequestId());
3307 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3308 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3309 NetworkRequestInfo.REQUEST);
3310 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3311 nri));
3312 return networkRequest;
3313 }
3314
Jeremy Joslin79294842014-12-03 17:15:28 -08003315 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3316 mHandler.sendMessageDelayed(
3317 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3318 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3319 }
3320
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003321 @Override
3322 public void releasePendingNetworkRequest(PendingIntent operation) {
3323 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3324 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003325 }
3326
3327 @Override
3328 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3329 Messenger messenger, IBinder binder) {
3330 enforceAccessPermission();
3331
3332 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003333 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003334 if (DBG) log("listenForNetwork for " + networkRequest);
3335 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3336 NetworkRequestInfo.LISTEN);
3337
3338 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3339 return networkRequest;
3340 }
3341
3342 @Override
3343 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3344 PendingIntent operation) {
3345 }
3346
3347 @Override
3348 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003349 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3350 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003351 }
3352
3353 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003354 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003355 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003356 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3357 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003358 }
3359
Robert Greenwalta67be032014-05-16 15:49:14 -07003360 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003361 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003362 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3363 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3364 }
3365
3366 @Override
3367 public void unregisterNetworkFactory(Messenger messenger) {
3368 enforceConnectivityInternalPermission();
3369 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3370 }
3371
3372 private void handleUnregisterNetworkFactory(Messenger messenger) {
3373 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3374 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003375 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003376 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003377 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003378 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003379 }
3380
Robert Greenwalt7b816022014-04-18 15:25:25 -07003381 /**
3382 * NetworkAgentInfo supporting a request by requestId.
3383 * These have already been vetted (their Capabilities satisfy the request)
3384 * and the are the highest scored network available.
3385 * the are keyed off the Requests requestId.
3386 */
3387 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3388 new SparseArray<NetworkAgentInfo>();
3389
Robert Greenwalt9258c642014-03-26 16:47:06 -07003390 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3391 new SparseArray<NetworkAgentInfo>();
3392
Robert Greenwalt7b816022014-04-18 15:25:25 -07003393 // NetworkAgentInfo keyed off its connecting messenger
3394 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
3395 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3396 new HashMap<Messenger, NetworkAgentInfo>();
3397
Paul Jensen2c311d62014-11-17 12:34:51 -05003398 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003399 private final NetworkRequest mDefaultRequest;
3400
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003401 private NetworkAgentInfo getDefaultNetwork() {
3402 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3403 }
3404
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003405 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003406 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003407 }
3408
Robert Greenwalt7b816022014-04-18 15:25:25 -07003409 public void registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
3410 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003411 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003412 enforceConnectivityInternalPermission();
3413
Paul Jensen2c311d62014-11-17 12:34:51 -05003414 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3415 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003416 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Robert Greenwalt7b816022014-04-18 15:25:25 -07003417 new NetworkInfo(networkInfo), new LinkProperties(linkProperties),
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003418 new NetworkCapabilities(networkCapabilities), currentScore, mContext, mTrackerHandler,
Paul Jensen2c311d62014-11-17 12:34:51 -05003419 new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003420 synchronized (this) {
3421 nai.networkMonitor.systemReady = mSystemReady;
3422 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003423 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003424 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
3425 }
3426
3427 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3428 if (VDBG) log("Got NetworkAgent Messenger");
3429 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen60061a62014-08-05 14:13:48 -04003430 assignNextNetId(na);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003431 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3432 NetworkInfo networkInfo = na.networkInfo;
3433 na.networkInfo = null;
3434 updateNetworkInfo(na, networkInfo);
3435 }
3436
3437 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3438 LinkProperties newLp = networkAgent.linkProperties;
3439 int netId = networkAgent.network.netId;
3440
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003441 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3442 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003443 if (networkAgent.clatd != null) {
3444 networkAgent.clatd.fixupLinkProperties(oldLp);
3445 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003446
Paul Jensen992f2522014-04-28 10:33:11 -04003447 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003448 updateMtu(newLp, oldLp);
3449 // TODO - figure out what to do for clat
3450// for (LinkProperties lp : newLp.getStackedLinks()) {
3451// updateMtu(lp, null);
3452// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003453 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003454
3455 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3456 // For now, use it only when the network has Internet access. http://b/18327075
3457 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3458 NetworkCapabilities.NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003459 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003460 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3461
Paul Jensen3b759822014-05-13 11:44:01 -04003462 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003463 if (isDefaultNetwork(networkAgent)) {
3464 handleApplyDefaultProxy(newLp.getHttpProxy());
3465 } else {
3466 updateProxy(newLp, oldLp, networkAgent);
3467 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003468 // TODO - move this check to cover the whole function
3469 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003470 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003471 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3472 }
Paul Jensen3b759822014-05-13 11:44:01 -04003473 }
3474
Lorenzo Colitti95439462014-10-09 13:44:48 +09003475 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3476 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3477 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003478
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003479 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003480 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3481 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003482 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003483 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003484 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003485 }
Paul Jensen992f2522014-04-28 10:33:11 -04003486
3487 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3488 CompareResult<String> interfaceDiff = new CompareResult<String>();
3489 if (oldLp != null) {
3490 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3491 } else if (newLp != null) {
3492 interfaceDiff.added = newLp.getAllInterfaceNames();
3493 }
3494 for (String iface : interfaceDiff.added) {
3495 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003496 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003497 mNetd.addInterfaceToNetwork(iface, netId);
3498 } catch (Exception e) {
3499 loge("Exception adding interface: " + e);
3500 }
3501 }
3502 for (String iface : interfaceDiff.removed) {
3503 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003504 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003505 mNetd.removeInterfaceFromNetwork(iface, netId);
3506 } catch (Exception e) {
3507 loge("Exception removing interface: " + e);
3508 }
3509 }
3510 }
3511
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003512 /**
3513 * Have netd update routes from oldLp to newLp.
3514 * @return true if routes changed between oldLp and newLp
3515 */
3516 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003517 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3518 if (oldLp != null) {
3519 routeDiff = oldLp.compareAllRoutes(newLp);
3520 } else if (newLp != null) {
3521 routeDiff.added = newLp.getAllRoutes();
3522 }
3523
3524 // add routes before removing old in case it helps with continuous connectivity
3525
3526 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3527 for (RouteInfo route : routeDiff.added) {
3528 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003529 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003530 try {
3531 mNetd.addRoute(netId, route);
3532 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003533 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3534 loge("Exception in addRoute for non-gateway: " + e);
3535 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003536 }
3537 }
3538 for (RouteInfo route : routeDiff.added) {
3539 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003540 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003541 try {
3542 mNetd.addRoute(netId, route);
3543 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003544 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3545 loge("Exception in addRoute for gateway: " + e);
3546 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003547 }
3548 }
3549
3550 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003551 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003552 try {
3553 mNetd.removeRoute(netId, route);
3554 } catch (Exception e) {
3555 loge("Exception in removeRoute: " + e);
3556 }
3557 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003558 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003559 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003560 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3561 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003562 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003563 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003564 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003565 dnses = new ArrayList();
3566 dnses.add(mDefaultDns);
3567 if (DBG) {
3568 loge("no dns provided for netId " + netId + ", so using defaults");
3569 }
3570 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003571 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003572 try {
3573 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3574 newLp.getDomains());
3575 } catch (Exception e) {
3576 loge("Exception in setDnsServersForNetwork: " + e);
3577 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003578 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3579 if (defaultNai != null && defaultNai.network.netId == netId) {
3580 setDefaultDnsSystemProperties(dnses);
3581 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003582 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003583 } else if (flush) {
3584 try {
3585 mNetd.flushNetworkDnsCache(netId);
3586 } catch (Exception e) {
3587 loge("Exception in flushNetworkDnsCache: " + e);
3588 }
3589 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003590 }
3591 }
3592
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003593 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3594 int last = 0;
3595 for (InetAddress dns : dnses) {
3596 ++last;
3597 String key = "net.dns" + last;
3598 String value = dns.getHostAddress();
3599 SystemProperties.set(key, value);
3600 }
3601 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3602 String key = "net.dns" + i;
3603 SystemProperties.set(key, "");
3604 }
3605 mNumDnsEntries = last;
3606 }
3607
Robert Greenwalt7b816022014-04-18 15:25:25 -07003608 private void updateCapabilities(NetworkAgentInfo networkAgent,
3609 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003610 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3611 synchronized (networkAgent) {
3612 networkAgent.networkCapabilities = networkCapabilities;
3613 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003614 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003615 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003616 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003617 }
3618
Paul Jensenc8b9a742014-09-30 15:37:41 -04003619 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3620 for (int i = 0; i < nai.networkRequests.size(); i++) {
3621 NetworkRequest nr = nai.networkRequests.valueAt(i);
3622 // Don't send listening requests to factories. b/17393458
3623 if (!isRequest(nr)) continue;
3624 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3625 }
3626 }
3627
Robert Greenwalt7b816022014-04-18 15:25:25 -07003628 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3629 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07003630 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07003631 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3632 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003633 }
3634 }
3635
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003636 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
3637 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08003638 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003639 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08003640 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
3641 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08003642 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003643 sendIntent(nri.mPendingIntent, intent);
3644 }
3645 // else not handled
3646 }
3647
3648 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
3649 mPendingIntentWakeLock.acquire();
3650 try {
3651 if (DBG) log("Sending " + pendingIntent);
3652 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
3653 } catch (PendingIntent.CanceledException e) {
3654 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
3655 mPendingIntentWakeLock.release();
3656 releasePendingNetworkRequest(pendingIntent);
3657 }
3658 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
3659 }
3660
3661 @Override
3662 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
3663 String resultData, Bundle resultExtras) {
3664 if (DBG) log("Finished sending " + pendingIntent);
3665 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08003666 // Release with a delay so the receiving client has an opportunity to put in its
3667 // own request.
3668 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003669 }
3670
Robert Greenwalt9258c642014-03-26 16:47:06 -07003671 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003672 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003673 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003674 Bundle bundle = new Bundle();
3675 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
3676 new NetworkRequest(nri.request));
3677 Message msg = Message.obtain();
3678 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
3679 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
3680 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
3681 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003682 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003683 case ConnectivityManager.CALLBACK_LOSING: {
3684 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
3685 break;
3686 }
3687 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
3688 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
3689 new NetworkCapabilities(networkAgent.networkCapabilities));
3690 break;
3691 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003692 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003693 bundle.putParcelable(LinkProperties.class.getSimpleName(),
3694 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003695 break;
3696 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003697 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003698 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003699 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003700 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003701 if (VDBG) {
3702 log("sending notification " + notifyTypeToName(notificationType) +
3703 " for " + nri.request);
3704 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003705 nri.messenger.send(msg);
3706 } catch (RemoteException e) {
3707 // may occur naturally in the race of binder death.
3708 loge("RemoteException caught trying to send a callback msg for " + nri.request);
3709 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003710 }
3711
Paul Jensenc8b9a742014-09-30 15:37:41 -04003712 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
3713 for (int i = 0; i < nai.networkRequests.size(); i++) {
3714 NetworkRequest nr = nai.networkRequests.valueAt(i);
3715 // Ignore listening requests.
3716 if (!isRequest(nr)) continue;
3717 loge("Dead network still had at least " + nr);
3718 break;
3719 }
3720 nai.asyncChannel.disconnect();
3721 }
3722
Robert Greenwalt7b816022014-04-18 15:25:25 -07003723 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
3724 if (oldNetwork == null) {
3725 loge("Unknown NetworkAgentInfo in handleLingerComplete");
3726 return;
3727 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04003728 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
3729 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003730 }
3731
Paul Jensen27b02b72014-07-14 12:03:33 -04003732 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003733 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04003734 setupDataActivityTracking(newNetwork);
3735 try {
3736 mNetd.setDefaultNetId(newNetwork.network.netId);
3737 } catch (Exception e) {
3738 loge("Exception setting default network :" + e);
3739 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09003740 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04003741 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07003742 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05003743 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04003744 }
3745
Paul Jensen2161a8e2014-09-11 11:00:39 -04003746 // Handles a network appearing or improving its score.
3747 //
3748 // - Evaluates all current NetworkRequests that can be
3749 // satisfied by newNetwork, and reassigns to newNetwork
3750 // any such requests for which newNetwork is the best.
3751 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05003752 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04003753 // needed. A network is needed if it is the best network for
3754 // one or more NetworkRequests, or if it is a VPN.
3755 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003756 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05003757 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
3758 //
3759 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
3760 // networks that have no chance (i.e. even if validated)
3761 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04003762 //
3763 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
3764 // it does not remove NetworkRequests that other Networks could better satisfy.
3765 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
3766 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
3767 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003768 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05003769 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003770 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05003771 // torn down if unneeded.
3772 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
3773 // performed to tear down unvalidated networks that have no chance (i.e. even if
3774 // validated) of becoming the highest scoring network.
3775 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
3776 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05003777 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09003778 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05003779 loge("ERROR: nascent network not validated.");
3780 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04003781 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003782 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05003783 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04003784 if (DBG) log("rematching " + newNetwork.name());
3785 // Find and migrate to this Network any NetworkRequests for
3786 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003787 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04003788 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003789 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09003790 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
3791 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07003792 if (DBG) {
3793 log("Network " + newNetwork.name() + " was already satisfying" +
3794 " request " + nri.request.requestId + ". No change.");
3795 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09003796 keep = true;
3797 continue;
3798 }
3799
3800 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07003801 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05003802 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04003803 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04003804 // This is not a request, it's a callback listener.
3805 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04003806 newNetwork.addRequest(nri.request);
3807 continue;
3808 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04003809
Robert Greenwalt7b816022014-04-18 15:25:25 -07003810 // next check if it's better than any current network we're using for
3811 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07003812 if (VDBG) {
3813 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04003814 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
3815 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07003816 }
3817 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04003818 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003819 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003820 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003821 currentNetwork.networkRequests.remove(nri.request.requestId);
3822 currentNetwork.networkLingered.add(nri.request);
3823 affectedNetworks.add(currentNetwork);
3824 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003825 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07003826 }
Paul Jensen573a0352015-01-08 10:49:34 -05003827 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003828 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07003829 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003830 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04003831 // Tell NetworkFactories about the new score, so they can stop
3832 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003833 // TODO - this could get expensive if we have alot of requests for this
3834 // network. Think about if there is a way to reduce this. Push
3835 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04003836 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003837 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003838 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05003839 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003840 }
3841 }
3842 }
3843 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04003844 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003845 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05003846 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003847 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
3848 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
3849 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05003850 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003851 }
3852 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003853 if (keep) {
3854 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04003855 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04003856 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003857 synchronized (ConnectivityService.this) {
3858 // have a new default network, release the transition wakelock in
3859 // a second if it's held. The second pause is to allow apps
3860 // to reconnect over the new network
3861 if (mNetTransitionWakeLock.isHeld()) {
3862 mHandler.sendMessageDelayed(mHandler.obtainMessage(
3863 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
3864 mNetTransitionWakeLockSerialNumber, 0),
3865 1000);
3866 }
3867 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08003868 }
3869
3870 // do this after the default net is switched, but
3871 // before LegacyTypeTracker sends legacy broadcasts
3872 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
3873
3874 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05003875 // Maintain the illusion: since the legacy API only
3876 // understands one network at a time, we must pretend
3877 // that the current default network disconnected before
3878 // the new one connected.
3879 if (oldDefaultNetwork != null) {
3880 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
3881 oldDefaultNetwork);
3882 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09003883 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05003884 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
3885 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003886 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07003887
3888 // Notify battery stats service about this network, both the normal
3889 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04003890 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07003891 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07003892 final IBatteryStats bs = BatteryStatsService.getService();
3893 final int type = newNetwork.networkInfo.getType();
3894
3895 final String baseIface = newNetwork.linkProperties.getInterfaceName();
3896 bs.noteNetworkInterfaceType(baseIface, type);
3897 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
3898 final String stackedIface = stacked.getInterfaceName();
3899 bs.noteNetworkInterfaceType(stackedIface, type);
3900 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
3901 }
3902 } catch (RemoteException ignored) {
3903 }
3904
Robert Greenwalt152ed372014-12-17 17:19:53 -08003905 // This has to happen after the notifyNetworkCallbacks as that tickles each
3906 // ConnectivityManager instance so that legacy requests correctly bind dns
3907 // requests to this network. The legacy users are listening for this bcast
3908 // and will generally do a dns request so they can ensureRouteToHost and if
3909 // they do that before the callbacks happen they'll use the default network.
3910 //
3911 // TODO: Is there still a race here? We send the broadcast
3912 // after sending the callback, but if the app can receive the
3913 // broadcast before the callback, it might still break.
3914 //
3915 // This *does* introduce a race where if the user uses the new api
3916 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
3917 // they may get old info. Reverse this after the old startUsing api is removed.
3918 // This is on top of the multiple intent sequencing referenced in the todo above.
3919 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
3920 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
3921 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
3922 // legacy type tracker filters out repeat adds
3923 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
3924 }
3925 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07003926
3927 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
3928 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
3929 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
3930 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
3931 if (newNetwork.isVPN()) {
3932 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
3933 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05003934 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003935 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05003936 // validated (and get evaluated against peers, one losing here), or get reaped (see
3937 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
3938 // network. Networks that have been up for a while and are validated should be torn
3939 // down via the lingering process so communication on that network is given time to
3940 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003941 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04003942 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003943 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05003944 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
3945 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05003946 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05003947 if (DBG) log("Reaping " + nai.name());
3948 teardownUnneededNetwork(nai);
3949 }
3950 }
3951 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003952 }
3953
Paul Jensen2161a8e2014-09-11 11:00:39 -04003954 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
3955 // being disconnected.
3956 // If only one Network's score or capabilities have been modified since the last time
3957 // this function was called, pass this Network in via the "changed" arugment, otherwise
3958 // pass null.
3959 // If only one Network has been changed but its NetworkCapabilities have not changed,
3960 // pass in the Network's score (from getCurrentScore()) prior to the change via
3961 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
3962 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
3963 // TODO: This may get slow. The "changed" parameter is provided for future optimization
3964 // to avoid the slowness. It is not simply enough to process just "changed", for
3965 // example in the case where "changed"'s score decreases and another network should begin
3966 // satifying a NetworkRequest that "changed" currently satisfies.
3967
3968 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
3969 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
3970 // rematchNetworkAndRequests() handles.
3971 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05003972 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
3973 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04003974 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05003975 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
3976 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
3977 NascentState.NOT_JUST_VALIDATED,
3978 // Only reap the last time through the loop. Reaping before all rematching
3979 // is complete could incorrectly teardown a network that hasn't yet been
3980 // rematched.
3981 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
3982 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04003983 }
3984 }
3985 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003986
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09003987 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04003988 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09003989 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04003990 // For now only update icons for default connection.
3991 // TODO: Update WiFi and cellular icons separately. b/17237507
3992 if (!isDefaultNetwork(nai)) return;
3993
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09003994 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04003995 // Don't repeat publish.
3996 if (newInetCondition == mDefaultInetConditionPublished) return;
3997
3998 mDefaultInetConditionPublished = newInetCondition;
3999 sendInetConditionBroadcast(nai.networkInfo);
4000 }
4001
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004002 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4003 if (mLockdownTracker != null) {
4004 if (nai != null && nai.isVPN()) {
4005 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4006 } else {
4007 mLockdownTracker.onNetworkInfoChanged();
4008 }
4009 }
4010 }
4011
Robert Greenwalt7b816022014-04-18 15:25:25 -07004012 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4013 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004014 NetworkInfo oldInfo = null;
4015 synchronized (networkAgent) {
4016 oldInfo = networkAgent.networkInfo;
4017 networkAgent.networkInfo = newInfo;
4018 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004019 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004020
4021 if (oldInfo != null && oldInfo.getState() == state) {
4022 if (VDBG) log("ignoring duplicate network state non-change");
4023 return;
4024 }
4025 if (DBG) {
4026 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4027 (oldInfo == null ? "null" : oldInfo.getState()) +
4028 " to " + state);
4029 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004030
Paul Jenseneec75412014-08-04 12:21:19 -04004031 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004032 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004033 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004034 if (networkAgent.isVPN()) {
4035 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004036 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4037 (networkAgent.networkMisc == null ||
4038 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004039 } else {
4040 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4041 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004042 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004043 loge("Error creating network " + networkAgent.network.netId + ": "
4044 + e.getMessage());
4045 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004046 }
Paul Jenseneec75412014-08-04 12:21:19 -04004047 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004048 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004049 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07004050 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Paul Jensenca8f16a2014-05-09 12:47:55 -04004051 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004052 if (networkAgent.isVPN()) {
4053 // Temporarily disable the default proxy (not global).
4054 synchronized (mProxyLock) {
4055 if (!mDefaultProxyDisabled) {
4056 mDefaultProxyDisabled = true;
4057 if (mGlobalProxy == null && mDefaultProxy != null) {
4058 sendProxyBroadcast(null);
4059 }
4060 }
4061 }
4062 // TODO: support proxy per network.
4063 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004064 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004065 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4066 ReapUnvalidatedNetworks.REAP);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004067 } else if (state == NetworkInfo.State.DISCONNECTED ||
4068 state == NetworkInfo.State.SUSPENDED) {
4069 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004070 if (networkAgent.isVPN()) {
4071 synchronized (mProxyLock) {
4072 if (mDefaultProxyDisabled) {
4073 mDefaultProxyDisabled = false;
4074 if (mGlobalProxy == null && mDefaultProxy != null) {
4075 sendProxyBroadcast(mDefaultProxy);
4076 }
4077 }
4078 }
4079 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004080 }
4081 }
4082
Robert Greenwaltac96c522014-06-03 16:43:57 -07004083 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4084 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004085 if (score < 0) {
4086 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4087 "). Bumping score to min of 0");
4088 score = 0;
4089 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004090
Paul Jensen2161a8e2014-09-11 11:00:39 -04004091 final int oldScore = nai.getCurrentScore();
4092 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004093
Paul Jensen57a767f2014-11-19 13:01:46 -05004094 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004095
Paul Jensenc8b9a742014-09-30 15:37:41 -04004096 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004097 }
4098
Robert Greenwalt9258c642014-03-26 16:47:06 -07004099 // notify only this one new request of the current state
4100 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4101 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4102 // TODO - read state from monitor to decide what to send.
4103// if (nai.networkMonitor.isLingering()) {
4104// notifyType = NetworkCallbacks.LOSING;
4105// } else if (nai.networkMonitor.isEvaluating()) {
4106// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4107// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004108 if (nri.mPendingIntent == null) {
4109 callCallbackForRequest(nri, nai, notifyType);
4110 } else {
4111 sendPendingIntentForRequest(nri, nai, notifyType);
4112 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004113 }
4114
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004115 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004116 // The NetworkInfo we actually send out has no bearing on the real
4117 // state of affairs. For example, if the default connection is mobile,
4118 // and a request for HIPRI has just gone away, we need to pretend that
4119 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4120 // the state to DISCONNECTED, even though the network is of type MOBILE
4121 // and is still connected.
4122 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4123 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004124 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004125 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004126 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004127 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004128 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004129 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4130 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4131 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4132 if (info.isFailover()) {
4133 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4134 nai.networkInfo.setFailover(false);
4135 }
4136 if (info.getReason() != null) {
4137 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4138 }
4139 if (info.getExtraInfo() != null) {
4140 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4141 }
4142 NetworkAgentInfo newDefaultAgent = null;
4143 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4144 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4145 if (newDefaultAgent != null) {
4146 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4147 newDefaultAgent.networkInfo);
4148 } else {
4149 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4150 }
4151 }
4152 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4153 mDefaultInetConditionPublished);
4154 final Intent immediateIntent = new Intent(intent);
4155 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
4156 sendStickyBroadcast(immediateIntent);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004157 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004158 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004159 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004160 }
4161 }
4162 }
4163
Robert Greenwalt7b816022014-04-18 15:25:25 -07004164 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004165 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004166 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004167 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4168 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4169 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004170 if (nri.mPendingIntent == null) {
4171 callCallbackForRequest(nri, networkAgent, notifyType);
4172 } else {
4173 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4174 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004175 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004176 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004177
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004178 private String notifyTypeToName(int notifyType) {
4179 switch (notifyType) {
4180 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4181 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4182 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4183 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4184 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4185 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4186 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4187 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4188 }
4189 return "UNKNOWN";
4190 }
4191
Jeff Sharkey69736342014-12-08 14:50:12 -08004192 /**
4193 * Notify other system services that set of active ifaces has changed.
4194 */
4195 private void notifyIfacesChanged() {
4196 try {
4197 mStatsService.forceUpdateIfaces();
4198 } catch (Exception ignored) {
4199 }
4200 }
4201
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004202 @Override
4203 public boolean addVpnAddress(String address, int prefixLength) {
4204 throwIfLockdownEnabled();
4205 int user = UserHandle.getUserId(Binder.getCallingUid());
4206 synchronized (mVpns) {
4207 return mVpns.get(user).addAddress(address, prefixLength);
4208 }
4209 }
4210
4211 @Override
4212 public boolean removeVpnAddress(String address, int prefixLength) {
4213 throwIfLockdownEnabled();
4214 int user = UserHandle.getUserId(Binder.getCallingUid());
4215 synchronized (mVpns) {
4216 return mVpns.get(user).removeAddress(address, prefixLength);
4217 }
4218 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004219
4220 @Override
4221 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4222 throwIfLockdownEnabled();
4223 int user = UserHandle.getUserId(Binder.getCallingUid());
4224 synchronized (mVpns) {
4225 return mVpns.get(user).setUnderlyingNetworks(networks);
4226 }
4227 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004228}