blob: 6f7e1a43e2126bb6232a571b04292b6862a8e5d0 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090026import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
27import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070030import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070031import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070033
Wenchao Tongf5ea3402015-03-04 13:26:38 -080034import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070035import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
49import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070050import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070051import android.net.INetworkPolicyListener;
52import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070053import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080054import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070055import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070056import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070057import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070058import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070062import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070063import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070065import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070066import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070067import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040068import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070069import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040071import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070073import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040074import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070076import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070077import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070078import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Looper;
80import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070081import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070082import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070083import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070084import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070085import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070086import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070088import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040089import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070091import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070092import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070093import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070094import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080095import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070096import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -050097import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070098import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070099import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800100
Wink Savilleab9321d2013-06-29 21:10:57 -0700101import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400102import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700103import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700104import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700105import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700106import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800107import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700108import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700109import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700110import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700111import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700112import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700113import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400114import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900115import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700116import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400117import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400118import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700119import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800120import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700121import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700122import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700123import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700124import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700125import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700126
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700127import org.xmlpull.v1.XmlPullParser;
128import org.xmlpull.v1.XmlPullParserException;
129
130import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import java.io.FileNotFoundException;
133import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700134import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800135import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700136import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700137import java.net.InetAddress;
138import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700139import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700140import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700141import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700142import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700143import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500144import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700145import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700146import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700147import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700148import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800149
150/**
151 * @hide
152 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800153public class ConnectivityService extends IConnectivityManager.Stub
154 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700155 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800156
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700157 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700158 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800159
Jake Hamby786e71a2014-02-06 14:43:50 -0800160 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700161
Jeff Sharkey899223b2012-08-04 15:24:58 -0700162 // TODO: create better separation between radio types and network types
163
Robert Greenwalt42acef32009-08-12 16:08:25 -0700164 // how long to wait before switching back to a radio's default network
165 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
166 // system property that can override the above value
167 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
168 "android.telephony.apn-restore";
169
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900170 // How long to wait before putting up a "This network doesn't have an Internet connection,
171 // connect anyway?" dialog after the user selects a network that doesn't validate.
172 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
173
Jeremy Joslin79294842014-12-03 17:15:28 -0800174 // How long to delay to removal of a pending intent based request.
175 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
176 private final int mReleasePendingIntentDelayMs;
177
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800178 private Tethering mTethering;
179
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700180 private final PermissionMonitor mPermissionMonitor;
181
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700182 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700183
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700184 @GuardedBy("mVpns")
185 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700186
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700187 private boolean mLockdownEnabled;
188 private LockdownVpnTracker mLockdownTracker;
189
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700190 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
191 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192 /** Currently active network rules by UID. */
193 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700194 /** Set of ifaces that are costly. */
195 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700196
Erik Klineda4bfa82015-04-30 12:58:40 +0900197 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800198 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700199 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700200 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800201
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700202 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800203 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800204
205 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700206 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800207
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700208 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800209 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700210 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700211
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700212 private String mCurrentTcpBufferSizes;
213
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700214 private static final int ENABLED = 1;
215 private static final int DISABLED = 0;
216
Paul Jensenb10e37f2014-11-25 12:33:08 -0500217 // Arguments to rematchNetworkAndRequests()
218 private enum NascentState {
219 // Indicates a network was just validated for the first time. If the network is found to
220 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
221 JUST_VALIDATED,
222 // Indicates a network was not validated for the first time immediately prior to this call.
223 NOT_JUST_VALIDATED
224 };
225 private enum ReapUnvalidatedNetworks {
226 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
227 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
228 // known that there may be unvalidated networks that could potentially be reaped, and when
229 // all networks have been rematched against all NetworkRequests.
230 REAP,
231 // Don't reap unvalidated networks. This should be passed when it's known that there are
232 // no unvalidated networks that could potentially be reaped, and when some networks have
233 // not yet been rematched against all NetworkRequests.
234 DONT_REAP
235 };
236
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700238 * used internally to change our mobile data enabled flag
239 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700240 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700241
242 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700244 * from one net to another. Clear happens when we get a new
245 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
246 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700247 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700248 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700249
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250 /**
251 * used internally to reload global proxy settings
252 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700253 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700254
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700255 /**
Wink Saville628b0852011-08-04 15:01:58 -0700256 * used internally to send a sticky broadcast delayed.
257 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700258 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700259
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700260 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400261 * PAC manager has received new port.
262 */
263 private static final int EVENT_PROXY_HAS_CHANGED = 16;
264
Robert Greenwalte049c232014-04-11 15:53:27 -0700265 /**
266 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700267 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700268 */
269 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
270
Robert Greenwalt7b816022014-04-18 15:25:25 -0700271 /**
272 * used internally when registering NetworkAgents
273 * obj = Messenger
274 */
275 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
276
Robert Greenwalt9258c642014-03-26 16:47:06 -0700277 /**
278 * used to add a network request
279 * includes a NetworkRequestInfo
280 */
281 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
282
283 /**
284 * indicates a timeout period is over - check if we had a network yet or not
285 * and if not, call the timeout calback (but leave the request live until they
286 * cancel it.
287 * includes a NetworkRequestInfo
288 */
289 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
290
291 /**
292 * used to add a network listener - no request
293 * includes a NetworkRequestInfo
294 */
295 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
296
297 /**
298 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400299 * arg1 = UID of caller
300 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700301 */
302 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
303
Robert Greenwalta67be032014-05-16 15:49:14 -0700304 /**
305 * used internally when registering NetworkFactories
306 * obj = Messenger
307 */
308 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
309
Robert Greenwalt27711812014-06-25 16:45:57 -0700310 /**
311 * used internally to expire a wakelock when transitioning
312 * from one net to another. Expire happens when we fail to find
313 * a new network (typically after 1 minute) -
314 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
315 * a replacement network.
316 */
317 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
318
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700319 /**
320 * Used internally to indicate the system is ready.
321 */
322 private static final int EVENT_SYSTEM_READY = 25;
323
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800324 /**
325 * used to add a network request with a pending intent
326 * includes a NetworkRequestInfo
327 */
328 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
329
330 /**
331 * used to remove a pending intent and its associated network request.
332 * arg1 = UID of caller
333 * obj = PendingIntent
334 */
335 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
336
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900337 /**
338 * used to specify whether a network should be used even if unvalidated.
339 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
340 * arg2 = whether to remember this choice in the future (1 or 0)
341 * obj = network
342 */
343 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
344
345 /**
346 * used to ask the user to confirm a connection to an unvalidated network.
347 * obj = network
348 */
349 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700350
Erik Klineda4bfa82015-04-30 12:58:40 +0900351 /**
352 * used internally to (re)configure mobile data always-on settings.
353 */
354 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
355
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700356 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700357 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700358 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700359 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700360
Mike Lockwood0f79b542009-08-14 14:18:49 -0400361 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800362 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400363
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700364 private PowerManager.WakeLock mNetTransitionWakeLock;
365 private String mNetTransitionWakeLockCausedBy = "";
366 private int mNetTransitionWakeLockSerialNumber;
367 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800368 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700369
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700370 private InetAddress mDefaultDns;
371
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700372 // used in DBG mode to track inet condition reports
373 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
374 private ArrayList mInetLog;
375
Robert Greenwalt434203a2010-10-11 16:00:27 -0700376 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400377 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700378 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700379 private boolean mDefaultProxyDisabled = false;
380
Robert Greenwalt434203a2010-10-11 16:00:27 -0700381 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400382 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700383
Jason Monk602b2322013-07-03 17:04:33 -0400384 private PacManager mPacManager = null;
385
Erik Klineda4bfa82015-04-30 12:58:40 +0900386 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700387
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400388 private UserManager mUserManager;
389
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700390 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700391 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700392
Robert Greenwalt50393202011-06-21 17:26:14 -0700393 // the set of network types that can only be enabled by system/sig apps
394 List mProtectedNetworks;
395
John Spurlockbf991a82013-06-24 14:20:23 -0400396 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700397
Wink Savilleab9321d2013-06-29 21:10:57 -0700398 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400399
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700400 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
401 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700402 private final static int MAX_NET_ID = 65535;
403 private int mNextNetId = MIN_NET_ID;
404
Robert Greenwalt34524f02014-05-18 16:22:10 -0700405 // sequence number of NetworkRequests
406 private int mNextNetworkRequestId = 1;
407
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700408 /**
409 * Implements support for the legacy "one network per network type" model.
410 *
411 * We used to have a static array of NetworkStateTrackers, one for each
412 * network type, but that doesn't work any more now that we can have,
413 * for example, more that one wifi network. This class stores all the
414 * NetworkAgentInfo objects that support a given type, but the legacy
415 * API will only see the first one.
416 *
417 * It serves two main purposes:
418 *
419 * 1. Provide information about "the network for a given type" (since this
420 * API only supports one).
421 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
422 * the first network for a given type changes, or if the default network
423 * changes.
424 */
425 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900426
427 private static final boolean DBG = true;
428 private static final boolean VDBG = false;
429 private static final String TAG = "CSLegacyTypeTracker";
430
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700431 /**
432 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
433 * Each list holds references to all NetworkAgentInfos that are used to
434 * satisfy requests for that network type.
435 *
436 * This array is built out at startup such that an unsupported network
437 * doesn't get an ArrayList instance, making this a tristate:
438 * unsupported, supported but not active and active.
439 *
440 * The actual lists are populated when we scan the network types that
441 * are supported on this device.
442 */
443 private ArrayList<NetworkAgentInfo> mTypeLists[];
444
445 public LegacyTypeTracker() {
446 mTypeLists = (ArrayList<NetworkAgentInfo>[])
447 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
448 }
449
450 public void addSupportedType(int type) {
451 if (mTypeLists[type] != null) {
452 throw new IllegalStateException(
453 "legacy list for type " + type + "already initialized");
454 }
455 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
456 }
457
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700458 public boolean isTypeSupported(int type) {
459 return isNetworkTypeValid(type) && mTypeLists[type] != null;
460 }
461
462 public NetworkAgentInfo getNetworkForType(int type) {
463 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
464 return mTypeLists[type].get(0);
465 } else {
466 return null;
467 }
468 }
469
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900470 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
471 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900472 if (DBG) {
473 log("Sending " + (connected ? "connected" : "disconnected") +
474 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900475 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900476 }
477 }
478
479 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700480 public void add(int type, NetworkAgentInfo nai) {
481 if (!isTypeSupported(type)) {
482 return; // Invalid network type.
483 }
484 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
485
486 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
487 if (list.contains(nai)) {
488 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
489 return;
490 }
491
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900492 list.add(nai);
493
494 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900495 final boolean isDefaultNetwork = isDefaultNetwork(nai);
496 if (list.size() == 1 || isDefaultNetwork) {
497 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700498 sendLegacyNetworkBroadcast(nai, true, type);
499 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700500 }
501
Lorenzo Colittia793a672014-07-31 23:20:17 +0900502 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900503 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900504 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
505 if (list == null || list.isEmpty()) {
506 return;
507 }
508
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900509 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900510
511 if (!list.remove(nai)) {
512 return;
513 }
514
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900515 if (wasFirstNetwork || wasDefault) {
516 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900517 sendLegacyNetworkBroadcast(nai, false, type);
518 }
519
520 if (!list.isEmpty() && wasFirstNetwork) {
521 if (DBG) log("Other network available for type " + type +
522 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900523 final NetworkAgentInfo replacement = list.get(0);
524 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
525 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900526 }
527 }
528
529 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900530 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
531 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700532 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900533 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700534 }
535 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700536
Lorenzo Colittia793a672014-07-31 23:20:17 +0900537 private String naiToString(NetworkAgentInfo nai) {
538 String name = (nai != null) ? nai.name() : "null";
539 String state = (nai.networkInfo != null) ?
540 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
541 "???/???";
542 return name + " " + state;
543 }
544
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700545 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900546 pw.println("mLegacyTypeTracker:");
547 pw.increaseIndent();
548 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700549 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900550 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700551 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900552 pw.println();
553 pw.println("Current state:");
554 pw.increaseIndent();
555 for (int type = 0; type < mTypeLists.length; type++) {
556 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
557 for (NetworkAgentInfo nai : mTypeLists[type]) {
558 pw.println(type + " " + naiToString(nai));
559 }
560 }
561 pw.decreaseIndent();
562 pw.decreaseIndent();
563 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700564 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900565
566 // This class needs its own log method because it has a different TAG.
567 private void log(String s) {
568 Slog.d(TAG, s);
569 }
570
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700571 }
572 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
573
Jeff Sharkey899223b2012-08-04 15:24:58 -0700574 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700575 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800576 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800577
Erik Klineda4bfa82015-04-30 12:58:40 +0900578 mDefaultRequest = createInternetRequestForTransport(-1);
579 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
580 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
581
582 mDefaultMobileDataRequest = createInternetRequestForTransport(
583 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700584
Wink Savillebb08caf2010-09-02 19:23:52 -0700585 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
586 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700587 mHandler = new InternalHandler(handlerThread.getLooper());
588 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700589
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800590 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800591 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
592 String id = Settings.Secure.getString(context.getContentResolver(),
593 Settings.Secure.ANDROID_ID);
594 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700595 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800596 SystemProperties.set("net.hostname", name);
597 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800598 }
599
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700600 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700601 String dns = Settings.Global.getString(context.getContentResolver(),
602 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700603 if (dns == null || dns.length() == 0) {
604 dns = context.getResources().getString(
605 com.android.internal.R.string.config_default_dns_server);
606 }
607 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800608 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
609 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800610 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700611 }
612
Jeremy Joslin79294842014-12-03 17:15:28 -0800613 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
614 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
615
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700616 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700617 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800618 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700619 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700620 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700621 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700622
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700623 try {
624 mPolicyManager.registerListener(mPolicyListener);
625 } catch (RemoteException e) {
626 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700627 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700628 }
629
630 final PowerManager powerManager = (PowerManager) context.getSystemService(
631 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700632 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
633 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
634 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800635 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700636
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700637 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700638
Wink Saville51f456f2013-04-23 14:26:51 -0700639 // TODO: What is the "correct" way to do determine if this is a wifi only device?
640 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
641 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700642 String[] naStrings = context.getResources().getStringArray(
643 com.android.internal.R.array.networkAttributes);
644 for (String naString : naStrings) {
645 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700646 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700647 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700648 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800649 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700650 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700651 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700652 }
Wink Saville51f456f2013-04-23 14:26:51 -0700653 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
654 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
655 n.type);
656 continue;
657 }
Wink Saville975c8482011-04-07 14:23:45 -0700658 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800659 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700660 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700661 continue;
662 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700663 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700664
Wink Saville975c8482011-04-07 14:23:45 -0700665 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700666 mNetworksDefined++;
667 } catch(Exception e) {
668 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700669 }
670 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700671
672 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
673 if (mNetConfigs[TYPE_VPN] == null) {
674 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
675 // don't need to add TYPE_VPN to mNetConfigs.
676 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
677 mNetworksDefined++; // used only in the log() statement below.
678 }
679
Wink Saville5e56bc52013-07-29 15:00:57 -0700680 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700681
Robert Greenwalt50393202011-06-21 17:26:14 -0700682 mProtectedNetworks = new ArrayList<Integer>();
683 int[] protectedNetworks = context.getResources().getIntArray(
684 com.android.internal.R.array.config_protectedNetworks);
685 for (int p : protectedNetworks) {
686 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
687 mProtectedNetworks.add(p);
688 } else {
689 if (DBG) loge("Ignoring protectedNetwork " + p);
690 }
691 }
692
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700693 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
694 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700695
Robert Greenwaltfab501672014-07-23 11:44:01 -0700696 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800697
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700698 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
699
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700700 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700701 IntentFilter intentFilter = new IntentFilter();
702 intentFilter.addAction(Intent.ACTION_USER_STARTING);
703 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
704 mContext.registerReceiverAsUser(
705 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900706
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700707 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700708 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700709 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700710 } catch (RemoteException e) {
711 loge("Error registering observer :" + e);
712 }
713
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700714 if (DBG) {
715 mInetLog = new ArrayList();
716 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700717
Erik Klineda4bfa82015-04-30 12:58:40 +0900718 mSettingsObserver = new SettingsObserver(mContext, mHandler);
719 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800720
John Spurlockbf991a82013-06-24 14:20:23 -0400721 mDataConnectionStats = new DataConnectionStats(mContext);
722 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400723
Jason Monkdecd2952013-10-10 14:02:51 -0400724 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700725
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400726 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800727 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700728
Erik Klineda4bfa82015-04-30 12:58:40 +0900729 private NetworkRequest createInternetRequestForTransport(int transportType) {
730 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900731 netCap.addCapability(NET_CAPABILITY_INTERNET);
732 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900733 if (transportType > -1) {
734 netCap.addTransportType(transportType);
735 }
736 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
737 }
738
739 private void handleMobileDataAlwaysOn() {
740 final boolean enable = (Settings.Global.getInt(
741 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
742 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
743 if (enable == isEnabled) {
744 return; // Nothing to do.
745 }
746
747 if (enable) {
748 handleRegisterNetworkRequest(new NetworkRequestInfo(
749 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
750 } else {
751 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
752 }
753 }
754
755 private void registerSettingsCallbacks() {
756 // Watch for global HTTP proxy changes.
757 mSettingsObserver.observe(
758 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
759 EVENT_APPLY_GLOBAL_HTTP_PROXY);
760
761 // Watch for whether or not to keep mobile data always on.
762 mSettingsObserver.observe(
763 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
764 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
765 }
766
Robert Greenwalt34524f02014-05-18 16:22:10 -0700767 private synchronized int nextNetworkRequestId() {
768 return mNextNetworkRequestId++;
769 }
770
Paul Jensen31a94f42015-02-13 14:18:39 -0500771 private int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400772 synchronized (mNetworkForNetId) {
773 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
774 int netId = mNextNetId;
775 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
776 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500777 if (!mNetIdInUse.get(netId)) {
778 mNetIdInUse.put(netId, true);
779 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400780 }
781 }
782 }
783 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700784 }
785
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800786 private NetworkState getFilteredNetworkState(int networkType, int uid) {
787 NetworkInfo info = null;
788 LinkProperties lp = null;
789 NetworkCapabilities nc = null;
790 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800791 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800792
793 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
794 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
795 if (nai != null) {
796 synchronized (nai) {
797 info = new NetworkInfo(nai.networkInfo);
798 lp = new LinkProperties(nai.linkProperties);
799 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400800 // Network objects are outwardly immutable so there is no point to duplicating.
801 // Duplicating also precludes sharing socket factories and connection pools.
802 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800803 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800804 }
805 info.setType(networkType);
806 } else {
807 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
808 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
809 info.setIsAvailable(true);
810 lp = new LinkProperties();
811 nc = new NetworkCapabilities();
812 network = null;
813 }
814 info = getFilteredNetworkInfo(info, lp, uid);
815 }
816
Jeff Sharkey32566012014-12-02 18:30:14 -0800817 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400818 }
819
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800820 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
821 if (network == null) {
822 return null;
823 }
824 synchronized (mNetworkForNetId) {
825 return mNetworkForNetId.get(network.netId);
826 }
827 };
828
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900829 private Network[] getVpnUnderlyingNetworks(int uid) {
830 if (!mLockdownEnabled) {
831 int user = UserHandle.getUserId(uid);
832 synchronized (mVpns) {
833 Vpn vpn = mVpns.get(user);
834 if (vpn != null && vpn.appliesToUid(uid)) {
835 return vpn.getUnderlyingNetworks();
836 }
837 }
838 }
839 return null;
840 }
841
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800842 private NetworkState getUnfilteredActiveNetworkState(int uid) {
843 NetworkInfo info = null;
844 LinkProperties lp = null;
845 NetworkCapabilities nc = null;
846 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800847 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800848
849 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800850
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900851 final Network[] networks = getVpnUnderlyingNetworks(uid);
852 if (networks != null) {
853 // getUnderlyingNetworks() returns:
854 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
855 // empty array => the VPN explicitly said "no default network".
856 // non-empty array => the VPN specified one or more default networks; we use the
857 // first one.
858 if (networks.length > 0) {
859 nai = getNetworkAgentInfoForNetwork(networks[0]);
860 } else {
861 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800862 }
863 }
864
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800865 if (nai != null) {
866 synchronized (nai) {
867 info = new NetworkInfo(nai.networkInfo);
868 lp = new LinkProperties(nai.linkProperties);
869 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400870 // Network objects are outwardly immutable so there is no point to duplicating.
871 // Duplicating also precludes sharing socket factories and connection pools.
872 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800873 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800874 }
875 }
876
Jeff Sharkey32566012014-12-02 18:30:14 -0800877 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400878 }
879
880 /**
881 * Check if UID should be blocked from using the network with the given LinkProperties.
882 */
883 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700884 final boolean networkCostly;
885 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700886
Robert Greenwalt12e67352014-05-13 21:41:06 -0700887 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700888 synchronized (mRulesLock) {
889 networkCostly = mMeteredIfaces.contains(iface);
890 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700891 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700892
Amith Yamasani15e472352015-04-24 19:06:07 -0700893 if ((uidRules & RULE_REJECT_ALL) != 0
894 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700895 return true;
896 }
897
898 // no restrictive rules; network is visible
899 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700900 }
901
902 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700903 * Return a filtered {@link NetworkInfo}, potentially marked
904 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800905 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700906 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800907 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
908 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400909 // network is blocked; clone and override state
910 info = new NetworkInfo(info);
911 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900912 if (DBG) {
913 log("returning Blocked NetworkInfo for ifname=" +
914 lp.getInterfaceName() + ", uid=" + uid);
915 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700916 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800917 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700918 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700919 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700920 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700921 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700922 }
923
924 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800925 * Return NetworkInfo for the active (i.e., connected) network interface.
926 * It is assumed that at most one network is active at a time. If more
927 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700928 * @return the info for the active network, or {@code null} if none is
929 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800930 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700931 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800932 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700933 enforceAccessPermission();
934 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935 NetworkState state = getUnfilteredActiveNetworkState(uid);
936 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800937 }
938
Paul Jensen31a94f42015-02-13 14:18:39 -0500939 @Override
940 public Network getActiveNetwork() {
941 enforceAccessPermission();
942 final int uid = Binder.getCallingUid();
943 final int user = UserHandle.getUserId(uid);
944 int vpnNetId = NETID_UNSET;
945 synchronized (mVpns) {
946 final Vpn vpn = mVpns.get(user);
947 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
948 }
949 NetworkAgentInfo nai;
950 if (vpnNetId != NETID_UNSET) {
951 synchronized (mNetworkForNetId) {
952 nai = mNetworkForNetId.get(vpnNetId);
953 }
954 if (nai != null) return nai.network;
955 }
956 nai = getDefaultNetwork();
957 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
958 return nai != null ? nai.network : null;
959 }
960
Wink Saville948282b2013-08-29 08:55:16 -0700961 /**
962 * Find the first Provisioning network.
963 *
964 * @return NetworkInfo or null if none.
965 */
966 private NetworkInfo getProvisioningNetworkInfo() {
967 enforceAccessPermission();
968
969 // Find the first Provisioning Network
970 NetworkInfo provNi = null;
971 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700972 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700973 provNi = ni;
974 break;
975 }
976 }
977 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
978 return provNi;
979 }
980
981 /**
982 * Find the first Provisioning network or the ActiveDefaultNetwork
983 * if there is no Provisioning network
984 *
985 * @return NetworkInfo or null if none.
986 */
987 @Override
988 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
989 enforceAccessPermission();
990
991 NetworkInfo provNi = getProvisioningNetworkInfo();
992 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700994 }
995 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
996 return provNi;
997 }
998
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700999 public NetworkInfo getActiveNetworkInfoUnfiltered() {
1000 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001001 final int uid = Binder.getCallingUid();
1002 NetworkState state = getUnfilteredActiveNetworkState(uid);
1003 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001004 }
1005
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001006 @Override
1007 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
1008 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001009 NetworkState state = getUnfilteredActiveNetworkState(uid);
1010 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001011 }
1012
1013 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001014 public NetworkInfo getNetworkInfo(int networkType) {
1015 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001016 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001017 if (getVpnUnderlyingNetworks(uid) != null) {
1018 // A VPN is active, so we may need to return one of its underlying networks. This
1019 // information is not available in LegacyTypeTracker, so we have to get it from
1020 // getUnfilteredActiveNetworkState.
1021 NetworkState state = getUnfilteredActiveNetworkState(uid);
1022 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1023 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1024 }
1025 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001026 NetworkState state = getFilteredNetworkState(networkType, uid);
1027 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001028 }
1029
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001030 @Override
1031 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1032 enforceAccessPermission();
1033 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001034 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001035 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1036 if (nai != null) {
1037 synchronized (nai) {
1038 info = new NetworkInfo(nai.networkInfo);
1039 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001040 }
1041 }
1042 return info;
1043 }
1044
1045 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001046 public NetworkInfo[] getAllNetworkInfo() {
1047 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001048 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001049 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1050 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001051 NetworkInfo info = getNetworkInfo(networkType);
1052 if (info != null) {
1053 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001054 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001055 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001056 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001057 }
1058
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001059 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001060 public Network getNetworkForType(int networkType) {
1061 enforceAccessPermission();
1062 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001063 NetworkState state = getFilteredNetworkState(networkType, uid);
1064 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1065 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001066 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001067 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001068 }
1069
1070 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001071 public Network[] getAllNetworks() {
1072 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001073 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001074 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001075 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001076 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001077 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001078 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001079 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001080 }
1081
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001082 @Override
1083 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1084 // The basic principle is: if an app's traffic could possibly go over a
1085 // network, without the app doing anything multinetwork-specific,
1086 // (hence, by "default"), then include that network's capabilities in
1087 // the array.
1088 //
1089 // In the normal case, app traffic only goes over the system's default
1090 // network connection, so that's the only network returned.
1091 //
1092 // With a VPN in force, some app traffic may go into the VPN, and thus
1093 // over whatever underlying networks the VPN specifies, while other app
1094 // traffic may go over the system default network (e.g.: a split-tunnel
1095 // VPN, or an app disallowed by the VPN), so the set of networks
1096 // returned includes the VPN's underlying networks and the system
1097 // default.
1098 enforceAccessPermission();
1099
1100 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1101
1102 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001103 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001104 if (nc != null) {
1105 result.put(nai.network, nc);
1106 }
1107
1108 if (!mLockdownEnabled) {
1109 synchronized (mVpns) {
1110 Vpn vpn = mVpns.get(userId);
1111 if (vpn != null) {
1112 Network[] networks = vpn.getUnderlyingNetworks();
1113 if (networks != null) {
1114 for (Network network : networks) {
1115 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001116 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001117 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001118 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001119 }
1120 }
1121 }
1122 }
1123 }
1124 }
1125
1126 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1127 out = result.values().toArray(out);
1128 return out;
1129 }
1130
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001131 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001132 public boolean isNetworkSupported(int networkType) {
1133 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001134 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001135 }
1136
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001137 /**
1138 * Return LinkProperties for the active (i.e., connected) default
1139 * network interface. It is assumed that at most one default network
1140 * is active at a time. If more than one is active, it is indeterminate
1141 * which will be returned.
1142 * @return the ip properties for the active network, or {@code null} if
1143 * none is active
1144 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001145 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001146 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001147 enforceAccessPermission();
1148 final int uid = Binder.getCallingUid();
1149 NetworkState state = getUnfilteredActiveNetworkState(uid);
1150 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001151 }
1152
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001153 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001154 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001155 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001156 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1157 if (nai != null) {
1158 synchronized (nai) {
1159 return new LinkProperties(nai.linkProperties);
1160 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001161 }
1162 return null;
1163 }
1164
Robert Greenwalt12e67352014-05-13 21:41:06 -07001165 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001166 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001167 public LinkProperties getLinkProperties(Network network) {
1168 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001169 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001170 if (nai != null) {
1171 synchronized (nai) {
1172 return new LinkProperties(nai.linkProperties);
1173 }
1174 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001175 return null;
1176 }
1177
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001178 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001179 if (nai != null) {
1180 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001181 if (nai.networkCapabilities != null) {
1182 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001183 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001184 }
1185 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001186 return null;
1187 }
1188
1189 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001190 public NetworkCapabilities getNetworkCapabilities(Network network) {
1191 enforceAccessPermission();
1192 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1193 }
1194
1195 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001196 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001197 // Require internal since we're handing out IMSI details
1198 enforceConnectivityInternalPermission();
1199
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001200 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001201 for (Network network : getAllNetworks()) {
1202 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1203 if (nai != null) {
1204 synchronized (nai) {
1205 final String subscriberId = (nai.networkMisc != null)
1206 ? nai.networkMisc.subscriberId : null;
1207 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1208 nai.networkCapabilities, network, subscriberId, null));
1209 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001210 }
1211 }
1212 return result.toArray(new NetworkState[result.size()]);
1213 }
1214
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001215 @Override
1216 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1217 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001218 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001219 final long token = Binder.clearCallingIdentity();
1220 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001221 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1222 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001223 try {
1224 return mPolicyManager.getNetworkQuotaInfo(state);
1225 } catch (RemoteException e) {
1226 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001227 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001228 return null;
1229 } finally {
1230 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001231 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001232 }
1233
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001234 @Override
1235 public boolean isActiveNetworkMetered() {
1236 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001237 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001238 final long token = Binder.clearCallingIdentity();
1239 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001240 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001241 } finally {
1242 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001243 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001244 }
1245
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001246 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1247 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1248 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001249 try {
1250 return mPolicyManager.isNetworkMetered(state);
1251 } catch (RemoteException e) {
1252 }
1253 }
1254 return false;
1255 }
1256
Jeff Sharkey216c1812012-08-05 14:29:23 -07001257 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1258 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001259 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001260 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001261 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001262 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001263 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001264
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001265 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001266 * Ensure that a network route exists to deliver traffic to the specified
1267 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001268 * @param networkType the type of the network over which traffic to the
1269 * specified host is to be routed
1270 * @param hostAddress the IP address of the host to which the route is
1271 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001272 * @return {@code true} on success, {@code false} on failure
1273 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001274 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001275 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001276 if (mProtectedNetworks.contains(networkType)) {
1277 enforceConnectivityInternalPermission();
1278 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001279
Chad Brubakerc0234532014-02-14 13:24:29 -08001280 InetAddress addr;
1281 try {
1282 addr = InetAddress.getByAddress(hostAddress);
1283 } catch (UnknownHostException e) {
1284 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1285 return false;
1286 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001287
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001288 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001289 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001290 return false;
1291 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001292
1293 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1294 if (nai == null) {
1295 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1296 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1297 } else {
1298 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1299 }
1300 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001301 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001302
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001303 DetailedState netState;
1304 synchronized (nai) {
1305 netState = nai.networkInfo.getDetailedState();
1306 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001307
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001308 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001309 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001310 log("requestRouteToHostAddress on down network "
1311 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001312 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001313 }
1314 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001315 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001316
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001317 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001318 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001319 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001320 LinkProperties lp;
1321 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001322 synchronized (nai) {
1323 lp = nai.linkProperties;
1324 netId = nai.network.netId;
1325 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001326 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001327 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1328 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001329 } finally {
1330 Binder.restoreCallingIdentity(token);
1331 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001332 }
1333
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001334 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001335 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001336 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001337 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001338 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001339 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001340 if (bestRoute.getGateway().equals(addr)) {
1341 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001342 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001343 } else {
1344 // if we will connect to this through another route, add a direct route
1345 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001346 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001347 }
1348 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001349 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001350 try {
1351 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1352 } catch (Exception e) {
1353 // never crash - catch them all
1354 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001355 return false;
1356 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001357 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001358 }
1359
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001360 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1361 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001362 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001363 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001364 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001365 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001366 }
1367
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001368 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001369 // skip update when we've already applied rules
1370 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1371 if (oldRules == uidRules) return;
1372
1373 mUidRules.put(uid, uidRules);
1374 }
1375
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001376 // TODO: notify UID when it has requested targeted updates
1377 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001378
1379 @Override
1380 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001381 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001382 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001383 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001384 }
1385
1386 synchronized (mRulesLock) {
1387 mMeteredIfaces.clear();
1388 for (String iface : meteredIfaces) {
1389 mMeteredIfaces.add(iface);
1390 }
1391 }
1392 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001393
1394 @Override
1395 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1396 // caller is NPMS, since we only register with them
1397 if (LOGD_RULES) {
1398 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1399 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001400 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001401 };
1402
Robin Lee3b3dd942015-05-12 18:14:58 +01001403 /**
1404 * Require that the caller is either in the same user or has appropriate permission to interact
1405 * across users.
1406 *
1407 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1408 */
1409 private void enforceCrossUserPermission(int userId) {
1410 if (userId == UserHandle.getCallingUserId()) {
1411 // Not a cross-user call.
1412 return;
1413 }
1414 mContext.enforceCallingOrSelfPermission(
1415 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1416 "ConnectivityService");
1417 }
1418
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001419 private void enforceInternetPermission() {
1420 mContext.enforceCallingOrSelfPermission(
1421 android.Manifest.permission.INTERNET,
1422 "ConnectivityService");
1423 }
1424
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001426 mContext.enforceCallingOrSelfPermission(
1427 android.Manifest.permission.ACCESS_NETWORK_STATE,
1428 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001429 }
1430
1431 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001432 mContext.enforceCallingOrSelfPermission(
1433 android.Manifest.permission.CHANGE_NETWORK_STATE,
1434 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001435 }
1436
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001437 private void enforceTetherAccessPermission() {
1438 mContext.enforceCallingOrSelfPermission(
1439 android.Manifest.permission.ACCESS_NETWORK_STATE,
1440 "ConnectivityService");
1441 }
1442
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001443 private void enforceConnectivityInternalPermission() {
1444 mContext.enforceCallingOrSelfPermission(
1445 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1446 "ConnectivityService");
1447 }
1448
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001449 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001450 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001451 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001452 }
1453
1454 private void sendInetConditionBroadcast(NetworkInfo info) {
1455 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1456 }
1457
Wink Saville628b0852011-08-04 15:01:58 -07001458 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001459 if (mLockdownTracker != null) {
1460 info = mLockdownTracker.augmentNetworkInfo(info);
1461 }
1462
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001463 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001464 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001465 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 if (info.isFailover()) {
1467 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1468 info.setFailover(false);
1469 }
1470 if (info.getReason() != null) {
1471 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1472 }
1473 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001474 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1475 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001476 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001477 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001478 return intent;
1479 }
1480
1481 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1482 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1483 }
1484
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001485 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001486 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1487 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1488 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001489 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001490 final long ident = Binder.clearCallingIdentity();
1491 try {
1492 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1493 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1494 } finally {
1495 Binder.restoreCallingIdentity(ident);
1496 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001497 }
1498
Mike Lockwood0f79b542009-08-14 14:18:49 -04001499 private void sendStickyBroadcast(Intent intent) {
1500 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001501 if (!mSystemReady) {
1502 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001503 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001504 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001505 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001506 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001507 }
1508
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001509 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001510 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1511 final IBatteryStats bs = BatteryStatsService.getService();
1512 try {
1513 NetworkInfo ni = intent.getParcelableExtra(
1514 ConnectivityManager.EXTRA_NETWORK_INFO);
1515 bs.noteConnectivityChanged(intent.getIntExtra(
1516 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1517 ni != null ? ni.getState().toString() : "?");
1518 } catch (RemoteException e) {
1519 }
1520 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001521 try {
1522 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1523 } finally {
1524 Binder.restoreCallingIdentity(ident);
1525 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001526 }
1527 }
1528
1529 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001530 loadGlobalProxy();
1531
Mike Lockwood0f79b542009-08-14 14:18:49 -04001532 synchronized(this) {
1533 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001534 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001535 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001536 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001537 }
1538 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001539 // load the global proxy at startup
1540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001541
1542 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1543 // for user to unlock device.
1544 if (!updateLockdownVpn()) {
1545 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1546 mContext.registerReceiver(mUserPresentReceiver, filter);
1547 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001548
Erik Klineda4bfa82015-04-30 12:58:40 +09001549 // Configure whether mobile data is always on.
1550 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1551
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001552 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001553
1554 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001555 }
1556
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001557 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1558 @Override
1559 public void onReceive(Context context, Intent intent) {
1560 // Try creating lockdown tracker, since user present usually means
1561 // unlocked keystore.
1562 if (updateLockdownVpn()) {
1563 mContext.unregisterReceiver(this);
1564 }
1565 }
1566 };
1567
Wink Savilled747cbc2013-08-07 16:22:47 -07001568 /** @hide */
1569 @Override
1570 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1571 enforceConnectivityInternalPermission();
1572 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001573// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001574 }
1575
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001576 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001577 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001578 *
1579 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001580 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001581 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001582 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1583 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001584
1585 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001586 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001587
Robert Greenwalt7b816022014-04-18 15:25:25 -07001588 if (networkAgent.networkCapabilities.hasTransport(
1589 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001590 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1591 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001592 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001593 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001594 } else if (networkAgent.networkCapabilities.hasTransport(
1595 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001596 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1597 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001598 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001599 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001600 } else {
1601 // do not track any other networks
1602 timeout = 0;
1603 }
1604
Robert Greenwalt7b816022014-04-18 15:25:25 -07001605 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001606 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001607 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001608 } catch (Exception e) {
1609 // You shall not crash!
1610 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001611 }
1612 }
1613 }
1614
1615 /**
1616 * Remove data activity tracking when network disconnects.
1617 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001618 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1619 final String iface = networkAgent.linkProperties.getInterfaceName();
1620 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001621
Robert Greenwalt7b816022014-04-18 15:25:25 -07001622 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1623 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001624 try {
1625 // the call fails silently if no idletimer setup for this interface
1626 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001627 } catch (Exception e) {
1628 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001629 }
1630 }
1631 }
1632
1633 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001634 * Reads the network specific MTU size from reources.
1635 * and set it on it's iface.
1636 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001637 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1638 final String iface = newLp.getInterfaceName();
1639 final int mtu = newLp.getMtu();
1640 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1641 if (VDBG) log("identical MTU - not setting");
1642 return;
1643 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001644
Robert Greenwalt43074032014-08-15 17:53:05 -07001645 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001646 loge("Unexpected mtu value: " + mtu + ", " + iface);
1647 return;
1648 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001649
w1997615afd812014-08-05 15:18:11 -07001650 // Cannot set MTU without interface name
1651 if (TextUtils.isEmpty(iface)) {
1652 loge("Setting MTU size with null iface.");
1653 return;
1654 }
1655
Robert Greenwalt7b816022014-04-18 15:25:25 -07001656 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001657 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001658 mNetd.setMtu(iface, mtu);
1659 } catch (Exception e) {
1660 Slog.e(TAG, "exception in setMtu()" + e);
1661 }
1662 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001663
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001664 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001665
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001666 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1667 if (isDefaultNetwork(nai) == false) {
1668 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001669 }
1670
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001671 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1672 String[] values = null;
1673 if (tcpBufferSizes != null) {
1674 values = tcpBufferSizes.split(",");
1675 }
1676
1677 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001678 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001679 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1680 values = tcpBufferSizes.split(",");
1681 }
1682
1683 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1684
1685 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001686 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001687
1688 final String prefix = "/sys/kernel/ipv4/tcp_";
1689 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1690 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1691 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1692 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1693 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1694 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1695 mCurrentTcpBufferSizes = tcpBufferSizes;
1696 } catch (IOException e) {
1697 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001698 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001699
1700 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1701 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1702 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1703 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1704 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1705 if (rwndValue != 0) {
1706 SystemProperties.set(sysctlKey, rwndValue.toString());
1707 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001708 }
1709
Mattias Falk8b47b362011-08-23 14:15:13 +02001710 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001711 /*
1712 * Tell the VMs to toss their DNS caches
1713 */
1714 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1715 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001716 /*
1717 * Connectivity events can happen before boot has completed ...
1718 */
1719 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001720 final long ident = Binder.clearCallingIdentity();
1721 try {
1722 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1723 } finally {
1724 Binder.restoreCallingIdentity(ident);
1725 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001726 }
1727
Robert Greenwalt562cc542014-05-15 18:07:26 -07001728 @Override
1729 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001730 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1731 NETWORK_RESTORE_DELAY_PROP_NAME);
1732 if(restoreDefaultNetworkDelayStr != null &&
1733 restoreDefaultNetworkDelayStr.length() != 0) {
1734 try {
1735 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1736 } catch (NumberFormatException e) {
1737 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001738 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001739 // if the system property isn't set, use the value for the apn type
1740 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1741
1742 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1743 (mNetConfigs[networkType] != null)) {
1744 ret = mNetConfigs[networkType].restoreTime;
1745 }
1746 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001747 }
1748
1749 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001750 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1751 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001752 if (mContext.checkCallingOrSelfPermission(
1753 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001754 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001755 pw.println("Permission Denial: can't dump ConnectivityService " +
1756 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1757 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001758 return;
1759 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001760
Lorenzo Colittie3805462015-06-03 11:18:24 +09001761 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001762 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001763 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001764 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001765 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001766 pw.println();
1767
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001768 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1769 pw.print("Active default network: ");
1770 if (defaultNai == null) {
1771 pw.println("none");
1772 } else {
1773 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001774 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001775 pw.println();
1776
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001777 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001778 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001779 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1780 pw.println(nai.toString());
1781 pw.increaseIndent();
1782 pw.println("Requests:");
1783 pw.increaseIndent();
1784 for (int i = 0; i < nai.networkRequests.size(); i++) {
1785 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001786 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001787 pw.decreaseIndent();
1788 pw.println("Lingered:");
1789 pw.increaseIndent();
1790 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1791 pw.decreaseIndent();
1792 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001793 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001794 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001795 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001796
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001797 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001798 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001799 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1800 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001801 }
1802 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001803 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001804
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001805 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001806
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001807 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001808 pw.print("mNetTransitionWakeLock: currently " +
1809 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1810 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1811 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1812 } else {
1813 pw.println(", last requested never");
1814 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001815 }
1816 pw.println();
1817
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001818 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001819
Lorenzo Colittie3805462015-06-03 11:18:24 +09001820 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001821 pw.println();
1822 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001823 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001824 for(int i = 0; i < mInetLog.size(); i++) {
1825 pw.println(mInetLog.get(i));
1826 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001827 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001828 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001829 }
1830
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001831 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001832 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001833 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001834 if (officialNai != null && officialNai.equals(nai)) return true;
1835 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001836 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001837 " - " + nai);
1838 }
1839 return false;
1840 }
1841
Paul Jensenc8b9a742014-09-30 15:37:41 -04001842 private boolean isRequest(NetworkRequest request) {
1843 return mNetworkRequests.get(request).isRequest;
1844 }
1845
Robert Greenwalt42acef32009-08-12 16:08:25 -07001846 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001847 private class NetworkStateTrackerHandler extends Handler {
1848 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001849 super(looper);
1850 }
1851
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001852 @Override
1853 public void handleMessage(Message msg) {
1854 NetworkInfo info;
1855 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001856 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001857 handleAsyncChannelHalfConnect(msg);
1858 break;
1859 }
1860 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1861 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1862 if (nai != null) nai.asyncChannel.disconnect();
1863 break;
1864 }
1865 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1866 handleAsyncChannelDisconnected(msg);
1867 break;
1868 }
1869 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1870 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1871 if (nai == null) {
1872 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1873 } else {
1874 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001875 }
1876 break;
1877 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001878 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1879 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1880 if (nai == null) {
1881 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1882 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001883 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001884 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001885 "; created=" + nai.created);
1886 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001887 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001888 synchronized (nai) {
1889 nai.linkProperties = (LinkProperties)msg.obj;
1890 }
Paul Jenseneec75412014-08-04 12:21:19 -04001891 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001892 }
1893 break;
1894 }
1895 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1896 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1897 if (nai == null) {
1898 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1899 break;
1900 }
1901 info = (NetworkInfo) msg.obj;
1902 updateNetworkInfo(nai, info);
1903 break;
1904 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001905 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1906 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1907 if (nai == null) {
1908 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1909 break;
1910 }
1911 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001912 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001913 break;
1914 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001915 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1916 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1917 if (nai == null) {
1918 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1919 break;
1920 }
1921 try {
1922 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001923 } catch (Exception e) {
1924 // Never crash!
1925 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001926 }
1927 break;
1928 }
1929 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1930 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1931 if (nai == null) {
1932 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1933 break;
1934 }
1935 try {
1936 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001937 } catch (Exception e) {
1938 // Never crash!
1939 loge("Exception in removeVpnUidRanges: " + e);
1940 }
1941 break;
1942 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001943 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1944 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1945 if (nai == null) {
1946 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1947 break;
1948 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001949 if (nai.created && !nai.networkMisc.explicitlySelected) {
1950 loge("ERROR: created network explicitly selected.");
1951 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001952 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001953 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001954 break;
1955 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001956 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001957 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001958 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1959 final boolean valid =
1960 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
1961 final boolean validationChanged = (valid != nai.lastValidated);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001962 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001963 if (valid) {
1964 if (DBG) log("Validated " + nai.name());
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001965 nai.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001966 if (!nai.everValidated) {
1967 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001968 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1969 ReapUnvalidatedNetworks.REAP);
1970 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001971 sendUpdatedScoreToFactories(nai);
1972 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001973 } else {
1974 nai.networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -04001975 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001976 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001977 // Let the NetworkAgent know the state of its network
1978 nai.asyncChannel.sendMessage(
1979 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1980 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1981 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001982
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001983 if (validationChanged) {
1984 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
1985 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001986 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001987 break;
1988 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001989 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001990 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001991 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1992 handleLingerComplete(nai);
1993 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001994 break;
1995 }
Paul Jensen869868be2014-05-15 10:33:05 -04001996 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001997 if (msg.arg1 == 0) {
1998 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1999 } else {
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002000 final NetworkAgentInfo nai;
Paul Jensen5df4bec2014-08-25 22:45:39 -04002001 synchronized (mNetworkForNetId) {
2002 nai = mNetworkForNetId.get(msg.arg2);
2003 }
2004 if (nai == null) {
2005 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2006 break;
2007 }
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002008 nai.captivePortalDetected = true;
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002009 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
2010 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04002011 }
Paul Jensen869868be2014-05-15 10:33:05 -04002012 break;
2013 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002014 }
2015 }
2016 }
2017
Paul Jensen0cc17322014-11-25 15:26:53 -05002018 // Cancel any lingering so the linger timeout doesn't teardown a network.
2019 // This should be called when a network begins satisfying a NetworkRequest.
2020 // Note: depending on what state the NetworkMonitor is in (e.g.,
2021 // if it's awaiting captive portal login, or if validation failed), this
2022 // may trigger a re-evaluation of the network.
2023 private void unlinger(NetworkAgentInfo nai) {
2024 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002025 // If network has never been validated, it cannot have been lingered, so don't bother
2026 // needlessly triggering a re-evaluation.
2027 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002028 nai.networkLingered.clear();
2029 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2030 }
2031
Robert Greenwalt7b816022014-04-18 15:25:25 -07002032 private void handleAsyncChannelHalfConnect(Message msg) {
2033 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002034 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002035 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2036 if (VDBG) log("NetworkFactory connected");
2037 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002038 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002039 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002040 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002041 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002042 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002043 }
2044 } else {
2045 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002046 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002047 }
2048 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2049 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2050 if (VDBG) log("NetworkAgent connected");
2051 // A network agent has requested a connection. Establish the connection.
2052 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2053 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2054 } else {
2055 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002056 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002057 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002058 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002059 synchronized (mNetworkForNetId) {
2060 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002061 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002062 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002063 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002064 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002065 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002066 }
2067 }
2068 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002069
Robert Greenwalt7b816022014-04-18 15:25:25 -07002070 private void handleAsyncChannelDisconnected(Message msg) {
2071 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2072 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002073 if (DBG) {
2074 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2075 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002076 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002077 if (nai.created) {
2078 // Tell netd to clean up the configuration for this network
2079 // (routing rules, DNS, etc).
2080 try {
2081 mNetd.removeNetwork(nai.network.netId);
2082 } catch (Exception e) {
2083 loge("Exception removing network: " + e);
2084 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002085 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002086 // TODO - if we move the logic to the network agent (have them disconnect
2087 // because they lost all their requests or because their score isn't good)
2088 // then they would disconnect organically, report their new state and then
2089 // disconnect the channel.
2090 if (nai.networkInfo.isConnected()) {
2091 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2092 null, null);
2093 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002094 final boolean wasDefault = isDefaultNetwork(nai);
2095 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002096 mDefaultInetConditionPublished = 0;
2097 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002098 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002099 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002100 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002101 mNetworkAgentInfos.remove(msg.replyTo);
2102 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002103 synchronized (mNetworkForNetId) {
2104 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002105 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002106 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002107 // Since we've lost the network, go through all the requests that
2108 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002109 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002110 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002111 for (int i = 0; i < nai.networkRequests.size(); i++) {
2112 NetworkRequest request = nai.networkRequests.valueAt(i);
2113 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2114 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002115 if (DBG) {
2116 log("Checking for replacement network to handle request " + request );
2117 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002118 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002119 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002120 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002121 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2122 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002123 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002124 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002125 alternative = existing;
2126 }
2127 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002128 if (alternative != null) {
2129 if (DBG) log(" found replacement in " + alternative.name());
2130 if (!toActivate.contains(alternative)) {
2131 toActivate.add(alternative);
2132 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002133 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002134 }
2135 }
2136 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2137 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002138 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002139 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002141 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002142 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002143 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002144 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2145 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002146 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002147 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302148 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2149 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002150 }
2151
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002152 // If this method proves to be too slow then we can maintain a separate
2153 // pendingIntent => NetworkRequestInfo map.
2154 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2155 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2156 Intent intent = pendingIntent.getIntent();
2157 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2158 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2159 if (existingPendingIntent != null &&
2160 existingPendingIntent.getIntent().filterEquals(intent)) {
2161 return entry.getValue();
2162 }
2163 }
2164 return null;
2165 }
2166
2167 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2168 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2169
2170 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2171 if (existingRequest != null) { // remove the existing request.
2172 if (DBG) log("Replacing " + existingRequest.request + " with "
2173 + nri.request + " because their intents matched.");
2174 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2175 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002176 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002177 }
2178
Erik Klineda4bfa82015-04-30 12:58:40 +09002179 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002180 mNetworkRequests.put(nri.request, nri);
2181
Paul Jensen0cc17322014-11-25 15:26:53 -05002182 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2183
Robert Greenwalt9258c642014-03-26 16:47:06 -07002184 // Check for the best currently alive network that satisfies this request
2185 NetworkAgentInfo bestNetwork = null;
2186 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002187 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002188 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002189 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002190 if (!nri.isRequest) {
2191 // Not setting bestNetwork here as a listening NetworkRequest may be
2192 // satisfied by multiple Networks. Instead the request is added to
2193 // each satisfying Network and notified about each.
2194 network.addRequest(nri.request);
2195 notifyNetworkCallback(network, nri);
2196 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002197 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002198 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002199 }
2200 }
2201 }
2202 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002203 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002204 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002205 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002206 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002207 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002208 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002209 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2210 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002211 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002212
Lorenzo Colittia793a672014-07-31 23:20:17 +09002213 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002214 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002215 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002216 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002217 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002218 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002219 }
2220 }
2221 }
2222
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002223 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2224 int callingUid) {
2225 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2226 if (nri != null) {
2227 handleReleaseNetworkRequest(nri.request, callingUid);
2228 }
2229 }
2230
Paul Jensen99364842014-12-09 11:43:45 -05002231 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2232 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2233 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2234 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2235 private boolean unneeded(NetworkAgentInfo nai) {
2236 if (!nai.created || nai.isVPN()) return false;
2237 boolean unneeded = true;
2238 if (nai.everValidated) {
2239 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2240 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2241 try {
2242 if (isRequest(nr)) unneeded = false;
2243 } catch (Exception e) {
2244 loge("Request " + nr + " not found in mNetworkRequests.");
2245 loge(" it came from request list of " + nai.name());
2246 }
2247 }
2248 } else {
2249 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2250 // If this Network is already the highest scoring Network for a request, or if
2251 // there is hope for it to become one if it validated, then it is needed.
2252 if (nri.isRequest && nai.satisfies(nri.request) &&
2253 (nai.networkRequests.get(nri.request.requestId) != null ||
2254 // Note that this catches two important cases:
2255 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2256 // is currently satisfying the request. This is desirable when
2257 // cellular ends up validating but WiFi does not.
2258 // 2. Unvalidated WiFi will not be reaped when validated cellular
2259 // is currently satsifying the request. This is desirable when
2260 // WiFi ends up validating and out scoring cellular.
2261 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2262 nai.getCurrentScoreAsValidated())) {
2263 unneeded = false;
2264 break;
2265 }
2266 }
2267 }
2268 return unneeded;
2269 }
2270
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002271 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2272 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002273 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002274 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002275 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2276 return;
2277 }
2278 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002279 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002280 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002281 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002282 // Find all networks that are satisfying this request and remove the request
2283 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002284 // TODO - it's my understanding that for a request there is only a single
2285 // network satisfying it, so this loop is wasteful
2286 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002287 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2288 if (nai.networkRequests.get(nri.request.requestId) != null) {
2289 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002290 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002291 log(" Removing from current network " + nai.name() +
2292 ", leaving " + nai.networkRequests.size() +
2293 " requests.");
2294 }
Paul Jensen99364842014-12-09 11:43:45 -05002295 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002296 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002297 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002298 } else {
2299 // suspect there should only be one pass through here
2300 // but if any were kept do the check below
2301 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002302 }
2303 }
2304 }
2305
Robert Greenwalt51481852015-01-08 14:43:31 -08002306 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2307 if (nai != null) {
2308 mNetworkForRequestId.remove(nri.request.requestId);
2309 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002310 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002311 // that a network connected to serve it, even though the network was already
2312 // connected. Now that this request has gone away, we might have to pretend
2313 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002314 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002315 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2316 boolean doRemove = true;
2317 if (wasKept) {
2318 // check if any of the remaining requests for this network are for the
2319 // same legacy type - if so, don't remove the nai
2320 for (int i = 0; i < nai.networkRequests.size(); i++) {
2321 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2322 if (otherRequest.legacyType == nri.request.legacyType &&
2323 isRequest(otherRequest)) {
2324 if (DBG) log(" still have other legacy request - leaving");
2325 doRemove = false;
2326 }
2327 }
2328 }
2329
2330 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002331 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002332 }
2333 }
2334
Robert Greenwalta67be032014-05-16 15:49:14 -07002335 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002336 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2337 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002338 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002339 } else {
2340 // listens don't have a singular affectedNetwork. Check all networks to see
2341 // if this listen request applies and remove it.
2342 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2343 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002344 }
2345 }
2346 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2347 }
2348 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002349
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002350 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2351 enforceConnectivityInternalPermission();
2352 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2353 accept ? 1 : 0, always ? 1: 0, network));
2354 }
2355
2356 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2357 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2358 " accept=" + accept + " always=" + always);
2359
2360 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2361 if (nai == null) {
2362 // Nothing to do.
2363 return;
2364 }
2365
2366 if (nai.everValidated) {
2367 // The network validated while the dialog box was up. Don't make any changes. There's a
2368 // TODO in the dialog code to make it go away if the network validates; once that's
2369 // implemented, taking action here will be confusing.
2370 return;
2371 }
2372
2373 if (!nai.networkMisc.explicitlySelected) {
2374 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2375 }
2376
2377 if (accept != nai.networkMisc.acceptUnvalidated) {
2378 int oldScore = nai.getCurrentScore();
2379 nai.networkMisc.acceptUnvalidated = accept;
2380 rematchAllNetworksAndRequests(nai, oldScore);
2381 sendUpdatedScoreToFactories(nai);
2382 }
2383
2384 if (always) {
2385 nai.asyncChannel.sendMessage(
2386 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2387 }
2388
2389 // TODO: should we also disconnect from the network if accept is false?
2390 }
2391
2392 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2393 mHandler.sendMessageDelayed(
2394 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2395 PROMPT_UNVALIDATED_DELAY_MS);
2396 }
2397
2398 private void handlePromptUnvalidated(Network network) {
2399 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2400
2401 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2402 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002403 // Also don't prompt on captive portals because we're already prompting the user to sign in.
2404 if (nai == null || nai.everValidated || nai.captivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002405 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2406 return;
2407 }
2408
2409 // TODO: What should we do if we've already switched to this network because we had no
2410 // better option? There are two obvious alternatives.
2411 //
2412 // 1. Decide that there's no point prompting because this is our only usable network.
2413 // However, because we didn't prompt, if later on a validated network comes along, we'll
2414 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2415 // unvalidated network - or b) prompt the user at that later time - bad because the user
2416 // might not understand why they are now being prompted.
2417 //
2418 // 2. Always prompt the user, even if we have no other network to use. The user could then
2419 // try to find an alternative network to join (remember, if we got here, then the user
2420 // selected this network manually). This is bad because the prompt isn't really very
2421 // useful.
2422 //
2423 // For now we do #1, but we can revisit that later.
2424 if (isDefaultNetwork(nai)) {
2425 return;
2426 }
2427
2428 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2429 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2430 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2431 intent.setClassName("com.android.settings",
2432 "com.android.settings.wifi.WifiNoInternetDialog");
2433 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2434 }
2435
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002436 private class InternalHandler extends Handler {
2437 public InternalHandler(Looper looper) {
2438 super(looper);
2439 }
2440
2441 @Override
2442 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002443 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002444 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002445 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002446 String causedBy = null;
2447 synchronized (ConnectivityService.this) {
2448 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2449 mNetTransitionWakeLock.isHeld()) {
2450 mNetTransitionWakeLock.release();
2451 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002452 } else {
2453 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002454 }
2455 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002456 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2457 log("Failed to find a new network - expiring NetTransition Wakelock");
2458 } else {
2459 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2460 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002461 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002462 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002463 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002464 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002465 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002466 break;
2467 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002468 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002469 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002470 sendStickyBroadcast(intent);
2471 break;
2472 }
Jason Monkdecd2952013-10-10 14:02:51 -04002473 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002474 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002475 break;
2476 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002477 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002478 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2479 break;
2480 }
2481 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2482 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002483 break;
2484 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002485 case EVENT_REGISTER_NETWORK_AGENT: {
2486 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2487 break;
2488 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002489 case EVENT_REGISTER_NETWORK_REQUEST:
2490 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002491 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002492 break;
2493 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002494 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2495 handleRegisterNetworkRequestWithIntent(msg);
2496 break;
2497 }
2498 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2499 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2500 break;
2501 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002502 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002503 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002504 break;
2505 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002506 case EVENT_SET_ACCEPT_UNVALIDATED: {
2507 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2508 break;
2509 }
2510 case EVENT_PROMPT_UNVALIDATED: {
2511 handlePromptUnvalidated((Network) msg.obj);
2512 break;
2513 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002514 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2515 handleMobileDataAlwaysOn();
2516 break;
2517 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002518 case EVENT_SYSTEM_READY: {
2519 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2520 nai.networkMonitor.systemReady = true;
2521 }
2522 break;
2523 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002524 }
2525 }
2526 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002527
2528 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002529 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002530 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002531 if (isTetheringSupported()) {
2532 return mTethering.tether(iface);
2533 } else {
2534 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2535 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002536 }
2537
2538 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002539 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002540 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002541
2542 if (isTetheringSupported()) {
2543 return mTethering.untether(iface);
2544 } else {
2545 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2546 }
2547 }
2548
2549 // javadoc from interface
2550 public int getLastTetherError(String iface) {
2551 enforceTetherAccessPermission();
2552
2553 if (isTetheringSupported()) {
2554 return mTethering.getLastTetherError(iface);
2555 } else {
2556 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2557 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002558 }
2559
2560 // TODO - proper iface API for selection by property, inspection, etc
2561 public String[] getTetherableUsbRegexs() {
2562 enforceTetherAccessPermission();
2563 if (isTetheringSupported()) {
2564 return mTethering.getTetherableUsbRegexs();
2565 } else {
2566 return new String[0];
2567 }
2568 }
2569
2570 public String[] getTetherableWifiRegexs() {
2571 enforceTetherAccessPermission();
2572 if (isTetheringSupported()) {
2573 return mTethering.getTetherableWifiRegexs();
2574 } else {
2575 return new String[0];
2576 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002577 }
2578
Danica Chang6fdd0c62010-08-11 14:54:43 -07002579 public String[] getTetherableBluetoothRegexs() {
2580 enforceTetherAccessPermission();
2581 if (isTetheringSupported()) {
2582 return mTethering.getTetherableBluetoothRegexs();
2583 } else {
2584 return new String[0];
2585 }
2586 }
2587
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002588 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002589 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002590 if (isTetheringSupported()) {
2591 return mTethering.setUsbTethering(enable);
2592 } else {
2593 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2594 }
2595 }
2596
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002597 // TODO - move iface listing, queries, etc to new module
2598 // javadoc from interface
2599 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002600 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002601 return mTethering.getTetherableIfaces();
2602 }
2603
2604 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002605 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002606 return mTethering.getTetheredIfaces();
2607 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002608
Robert Greenwalt5a735062010-03-02 17:25:02 -08002609 public String[] getTetheringErroredIfaces() {
2610 enforceTetherAccessPermission();
2611 return mTethering.getErroredIfaces();
2612 }
2613
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002614 public String[] getTetheredDhcpRanges() {
2615 enforceConnectivityInternalPermission();
2616 return mTethering.getTetheredDhcpRanges();
2617 }
2618
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002619 // if ro.tether.denied = true we default to no tethering
2620 // gservices could set the secure setting to 1 though to enable it on a build where it
2621 // had previously been turned off.
2622 public boolean isTetheringSupported() {
2623 enforceTetherAccessPermission();
2624 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002625 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002626 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2627 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002628 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2629 mTethering.getTetherableWifiRegexs().length != 0 ||
2630 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2631 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002632 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002633
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002634 // Called when we lose the default network and have no replacement yet.
2635 // This will automatically be cleared after X seconds or a new default network
2636 // becomes CONNECTED, whichever happens first. The timer is started by the
2637 // first caller and not restarted by subsequent callers.
2638 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002639 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002640 synchronized (this) {
2641 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002642 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002643 mNetTransitionWakeLock.acquire();
2644 mNetTransitionWakeLockCausedBy = forWhom;
2645 }
2646 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002647 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002648 mNetTransitionWakeLockTimeout);
2649 return;
2650 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002651
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002652 // 100 percent is full good, 0 is full bad.
2653 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002654 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002655 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002656 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002657 }
2658
Paul Jensenbfd17b72015-04-07 12:43:13 -04002659 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002660 enforceAccessPermission();
2661 enforceInternetPermission();
2662
Paul Jensenbfd17b72015-04-07 12:43:13 -04002663 NetworkAgentInfo nai;
2664 if (network == null) {
2665 nai = getDefaultNetwork();
2666 } else {
2667 nai = getNetworkAgentInfoForNetwork(network);
2668 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002669 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002670 // Revalidate if the app report does not match our current validated state.
2671 if (hasConnectivity == nai.lastValidated) return;
2672 final int uid = Binder.getCallingUid();
2673 if (DBG) {
2674 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2675 ") by " + uid);
2676 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002677 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002678 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2679 // which isn't meant to work on uncreated networks.
2680 if (!nai.created) return;
2681
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002682 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002683
2684 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2685 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002686 }
2687
Paul Jensen25a217c2015-02-27 22:55:47 -05002688 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2689 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2690 enforceConnectivityInternalPermission();
2691 }
2692 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2693 if (nai == null) return;
2694 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2695 actionToken);
2696 }
2697
Paul Jensencee9b512015-05-06 07:32:40 -04002698 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002699 // this information is already available as a world read/writable jvm property
2700 // so this API change wouldn't have a benifit. It also breaks the passing
2701 // of proxy info to all the JVMs.
2702 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002703 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002704 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002705 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2706 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002707 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002708 }
2709
Paul Jensencee9b512015-05-06 07:32:40 -04002710 public ProxyInfo getProxyForNetwork(Network network) {
2711 if (network == null) return getDefaultProxy();
2712 final ProxyInfo globalProxy = getGlobalProxy();
2713 if (globalProxy != null) return globalProxy;
2714 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2715 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2716 // caller may not have.
2717 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2718 if (nai == null) return null;
2719 synchronized (nai) {
2720 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2721 if (proxyInfo == null) return null;
2722 return new ProxyInfo(proxyInfo);
2723 }
2724 }
2725
Paul Jensene0bef712014-12-10 15:12:18 -05002726 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2727 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2728 // proxy is null then there is no proxy in place).
2729 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2730 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2731 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2732 proxy = null;
2733 }
2734 return proxy;
2735 }
2736
2737 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2738 // better for determining if a new proxy broadcast is necessary:
2739 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2740 // avoid unnecessary broadcasts.
2741 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2742 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2743 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2744 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2745 // all set.
2746 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2747 a = canonicalizeProxyInfo(a);
2748 b = canonicalizeProxyInfo(b);
2749 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2750 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2751 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2752 }
2753
Jason Monk207900c2014-04-25 15:00:09 -04002754 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002755 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002756
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002757 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002758 if (proxyProperties == mGlobalProxy) return;
2759 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2760 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2761
2762 String host = "";
2763 int port = 0;
2764 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002765 String pacFileUrl = "";
2766 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002767 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002768 if (!proxyProperties.isValid()) {
2769 if (DBG)
2770 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2771 return;
2772 }
Jason Monk207900c2014-04-25 15:00:09 -04002773 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002774 host = mGlobalProxy.getHost();
2775 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002776 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002777 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002778 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002779 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002780 } else {
2781 mGlobalProxy = null;
2782 }
2783 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002784 final long token = Binder.clearCallingIdentity();
2785 try {
2786 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2787 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2788 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2789 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002790 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002791 } finally {
2792 Binder.restoreCallingIdentity(token);
2793 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002794
Jason Monkcf0f97a2014-10-02 15:39:38 -04002795 if (mGlobalProxy == null) {
2796 proxyProperties = mDefaultProxy;
2797 }
2798 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002799 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002800 }
2801
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002802 private void loadGlobalProxy() {
2803 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002804 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2805 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2806 String exclList = Settings.Global.getString(res,
2807 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002808 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2809 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002810 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002811 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002812 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002813 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002814 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002815 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002816 if (!proxyProperties.isValid()) {
2817 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2818 return;
2819 }
2820
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002821 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002822 mGlobalProxy = proxyProperties;
2823 }
2824 }
2825 }
2826
Jason Monk207900c2014-04-25 15:00:09 -04002827 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002828 // this information is already available as a world read/writable jvm property
2829 // so this API change wouldn't have a benifit. It also breaks the passing
2830 // of proxy info to all the JVMs.
2831 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002832 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002833 return mGlobalProxy;
2834 }
2835 }
2836
Jason Monk207900c2014-04-25 15:00:09 -04002837 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002838 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002839 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002840 proxy = null;
2841 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002842 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002843 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002844 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002845 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002846 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2847 return;
2848 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002849
2850 // This call could be coming from the PacManager, containing the port of the local
2851 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2852 // global (to get the correct local port), and send a broadcast.
2853 // TODO: Switch PacManager to have its own message to send back rather than
2854 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002855 if ((mGlobalProxy != null) && (proxy != null)
2856 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002857 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2858 mGlobalProxy = proxy;
2859 sendProxyBroadcast(mGlobalProxy);
2860 return;
2861 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002862 mDefaultProxy = proxy;
2863
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002864 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002865 if (!mDefaultProxyDisabled) {
2866 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002867 }
2868 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002869 }
2870
Paul Jensene0bef712014-12-10 15:12:18 -05002871 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2872 // This method gets called when any network changes proxy, but the broadcast only ever contains
2873 // the default proxy (even if it hasn't changed).
2874 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2875 // world where an app might be bound to a non-default network.
2876 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2877 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2878 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2879
2880 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2881 sendProxyBroadcast(getDefaultProxy());
2882 }
2883 }
2884
Robert Greenwalt434203a2010-10-11 16:00:27 -07002885 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002886 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2887 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002888 if (!TextUtils.isEmpty(proxy)) {
2889 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002890 if (data.length == 0) {
2891 return;
2892 }
2893
Robert Greenwalt434203a2010-10-11 16:00:27 -07002894 String proxyHost = data[0];
2895 int proxyPort = 8080;
2896 if (data.length > 1) {
2897 try {
2898 proxyPort = Integer.parseInt(data[1]);
2899 } catch (NumberFormatException e) {
2900 return;
2901 }
2902 }
Jason Monk207900c2014-04-25 15:00:09 -04002903 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002904 setGlobalProxy(p);
2905 }
2906 }
2907
Jason Monk207900c2014-04-25 15:00:09 -04002908 private void sendProxyBroadcast(ProxyInfo proxy) {
2909 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002910 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002911 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002912 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002913 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2914 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002915 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002916 final long ident = Binder.clearCallingIdentity();
2917 try {
2918 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2919 } finally {
2920 Binder.restoreCallingIdentity(ident);
2921 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002922 }
2923
2924 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002925 final private HashMap<Uri, Integer> mUriEventMap;
2926 final private Context mContext;
2927 final private Handler mHandler;
2928
2929 SettingsObserver(Context context, Handler handler) {
2930 super(null);
2931 mUriEventMap = new HashMap<Uri, Integer>();
2932 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002933 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002934 }
2935
Erik Klineda4bfa82015-04-30 12:58:40 +09002936 void observe(Uri uri, int what) {
2937 mUriEventMap.put(uri, what);
2938 final ContentResolver resolver = mContext.getContentResolver();
2939 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002940 }
2941
2942 @Override
2943 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002944 Slog.wtf(TAG, "Should never be reached.");
2945 }
2946
2947 @Override
2948 public void onChange(boolean selfChange, Uri uri) {
2949 final Integer what = mUriEventMap.get(uri);
2950 if (what != null) {
2951 mHandler.obtainMessage(what.intValue()).sendToTarget();
2952 } else {
2953 loge("No matching event to send for URI=" + uri);
2954 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002955 }
2956 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002957
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002958 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002959 Slog.d(TAG, s);
2960 }
2961
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002962 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002963 Slog.e(TAG, s);
2964 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002965
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002966 private static <T> T checkNotNull(T value, String message) {
2967 if (value == null) {
2968 throw new NullPointerException(message);
2969 }
2970 return value;
2971 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002972
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002973 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002974 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01002975 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
2976 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
2977 *
2978 * @param oldPackage Package name of the application which currently controls VPN, which will
2979 * be replaced. If there is no such application, this should should either be
2980 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
2981 * @param newPackage Package name of the application which should gain control of VPN, or
2982 * {@code null} to disable.
2983 * @param userId User for whom to prepare the new VPN.
2984 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002985 * @hide
2986 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002987 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01002988 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
2989 int userId) {
2990 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002991 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01002992
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002993 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01002994 return mVpns.get(userId).prepare(oldPackage, newPackage);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002995 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002996 }
2997
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002998 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01002999 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3000 * This method is used by system-privileged apps.
3001 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3002 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3003 *
3004 * @param packageName The package for which authorization state should change.
3005 * @param userId User for whom {@code packageName} is installed.
3006 * @param authorized {@code true} if this app should be able to start a VPN connection without
3007 * explicit user approval, {@code false} if not.
3008 *
Jeff Davidson05542602014-08-11 14:07:27 -07003009 * @hide
3010 */
3011 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003012 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3013 enforceCrossUserPermission(userId);
3014
Jeff Davidson05542602014-08-11 14:07:27 -07003015 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003016 mVpns.get(userId).setPackageAuthorization(packageName, authorized);
Jeff Davidson05542602014-08-11 14:07:27 -07003017 }
3018 }
3019
3020 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003021 * Configure a TUN interface and return its file descriptor. Parameters
3022 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003023 * and not available in ConnectivityManager. Permissions are checked in
3024 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003025 * @hide
3026 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003027 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003028 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003029 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003030 int user = UserHandle.getUserId(Binder.getCallingUid());
3031 synchronized(mVpns) {
3032 return mVpns.get(user).establish(config);
3033 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003034 }
3035
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003036 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003037 * Start legacy VPN, controlling native daemons as needed. Creates a
3038 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003039 */
3040 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003041 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003042 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003043 final LinkProperties egress = getActiveLinkProperties();
3044 if (egress == null) {
3045 throw new IllegalStateException("Missing active network connection");
3046 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003047 int user = UserHandle.getUserId(Binder.getCallingUid());
3048 synchronized(mVpns) {
3049 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3050 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003051 }
3052
3053 /**
3054 * Return the information of the ongoing legacy VPN. This method is used
3055 * by VpnSettings and not available in ConnectivityManager. Permissions
3056 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003057 */
3058 @Override
3059 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003060 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003061 int user = UserHandle.getUserId(Binder.getCallingUid());
3062 synchronized(mVpns) {
3063 return mVpns.get(user).getLegacyVpnInfo();
3064 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003065 }
3066
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003067 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003068 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3069 * and not available in ConnectivityManager.
3070 */
3071 @Override
3072 public VpnInfo[] getAllVpnInfo() {
3073 enforceConnectivityInternalPermission();
3074 if (mLockdownEnabled) {
3075 return new VpnInfo[0];
3076 }
3077
3078 synchronized(mVpns) {
3079 List<VpnInfo> infoList = new ArrayList<>();
3080 for (int i = 0; i < mVpns.size(); i++) {
3081 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3082 if (info != null) {
3083 infoList.add(info);
3084 }
3085 }
3086 return infoList.toArray(new VpnInfo[infoList.size()]);
3087 }
3088 }
3089
3090 /**
3091 * @return VPN information for accounting, or null if we can't retrieve all required
3092 * information, e.g primary underlying iface.
3093 */
3094 @Nullable
3095 private VpnInfo createVpnInfo(Vpn vpn) {
3096 VpnInfo info = vpn.getVpnInfo();
3097 if (info == null) {
3098 return null;
3099 }
3100 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3101 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3102 // the underlyingNetworks list.
3103 if (underlyingNetworks == null) {
3104 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3105 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3106 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3107 }
3108 } else if (underlyingNetworks.length > 0) {
3109 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3110 if (linkProperties != null) {
3111 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3112 }
3113 }
3114 return info.primaryUnderlyingIface == null ? null : info;
3115 }
3116
3117 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003118 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3119 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003120 * Permissions are checked in Vpn class.
3121 * @hide
3122 */
3123 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003124 public VpnConfig getVpnConfig(int userId) {
3125 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003126 synchronized(mVpns) {
Robin Lee3b3dd942015-05-12 18:14:58 +01003127 return mVpns.get(userId).getVpnConfig();
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003128 }
3129 }
3130
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003131 @Override
3132 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003133 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3134 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3135 return false;
3136 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003137
3138 // Tear down existing lockdown if profile was removed
3139 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3140 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003141 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003142 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3143 return false;
3144 }
3145
3146 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3147 final VpnProfile profile = VpnProfile.decode(
3148 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003149 int user = UserHandle.getUserId(Binder.getCallingUid());
3150 synchronized(mVpns) {
3151 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3152 profile));
3153 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003154 } else {
3155 setLockdownTracker(null);
3156 }
3157
3158 return true;
3159 }
3160
3161 /**
3162 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3163 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3164 */
3165 private void setLockdownTracker(LockdownVpnTracker tracker) {
3166 // Shutdown any existing tracker
3167 final LockdownVpnTracker existing = mLockdownTracker;
3168 mLockdownTracker = null;
3169 if (existing != null) {
3170 existing.shutdown();
3171 }
3172
3173 try {
3174 if (tracker != null) {
3175 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003176 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003177 mLockdownTracker = tracker;
3178 mLockdownTracker.init();
3179 } else {
3180 mNetd.setFirewallEnabled(false);
3181 }
3182 } catch (RemoteException e) {
3183 // ignored; NMS lives inside system_server
3184 }
3185 }
3186
3187 private void throwIfLockdownEnabled() {
3188 if (mLockdownEnabled) {
3189 throw new IllegalStateException("Unavailable in lockdown mode");
3190 }
3191 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003192
Wink Savilleab9321d2013-06-29 21:10:57 -07003193 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003194 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003195 // TODO: Remove? Any reason to trigger a provisioning check?
3196 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003197 }
3198
3199 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3200 private volatile boolean mIsNotificationVisible = false;
3201
Paul Jensen89e0f092014-09-15 15:59:36 -04003202 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003203 if (DBG) {
3204 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003205 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003206 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003207 Intent intent = new Intent(action);
3208 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003209 // Concatenate the range of types onto the range of NetIDs.
3210 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003211 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003212 }
3213
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003214 /**
3215 * Show or hide network provisioning notificaitons.
3216 *
3217 * @param id an identifier that uniquely identifies this notification. This must match
3218 * between show and hide calls. We use the NetID value but for legacy callers
3219 * we concatenate the range of types with the range of NetIDs.
3220 */
3221 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003222 String extraInfo, PendingIntent intent) {
3223 if (DBG) {
3224 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3225 networkType + " extraInfo=" + extraInfo);
3226 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003227
3228 Resources r = Resources.getSystem();
3229 NotificationManager notificationManager = (NotificationManager) mContext
3230 .getSystemService(Context.NOTIFICATION_SERVICE);
3231
3232 if (visible) {
3233 CharSequence title;
3234 CharSequence details;
3235 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003236 Notification notification = new Notification();
3237 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003238 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003239 title = r.getString(R.string.wifi_available_sign_in, 0);
3240 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003241 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003242 icon = R.drawable.stat_notify_wifi_in_range;
3243 break;
3244 case ConnectivityManager.TYPE_MOBILE:
3245 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003246 title = r.getString(R.string.network_available_sign_in, 0);
3247 // TODO: Change this to pull from NetworkInfo once a printable
3248 // name has been added to it
3249 details = mTelephonyManager.getNetworkOperatorName();
3250 icon = R.drawable.stat_notify_rssi_in_range;
3251 break;
3252 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003253 title = r.getString(R.string.network_available_sign_in, 0);
3254 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003255 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003256 icon = R.drawable.stat_notify_rssi_in_range;
3257 break;
3258 }
3259
Wink Savilleab9321d2013-06-29 21:10:57 -07003260 notification.when = 0;
3261 notification.icon = icon;
3262 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003263 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003264 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003265 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003266 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003267 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003268
Wink Saville948282b2013-08-29 08:55:16 -07003269 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003270 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003271 } catch (NullPointerException npe) {
3272 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3273 npe.printStackTrace();
3274 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003275 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003276 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003277 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003278 } catch (NullPointerException npe) {
3279 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3280 npe.printStackTrace();
3281 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003282 }
Wink Saville948282b2013-08-29 08:55:16 -07003283 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003284 }
3285
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003286 /** Location to an updatable file listing carrier provisioning urls.
3287 * An example:
3288 *
3289 * <?xml version="1.0" encoding="utf-8"?>
3290 * <provisioningUrls>
3291 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3292 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3293 * </provisioningUrls>
3294 */
3295 private static final String PROVISIONING_URL_PATH =
3296 "/data/misc/radio/provisioning_urls.xml";
3297 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003298
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003299 /** XML tag for root element. */
3300 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3301 /** XML tag for individual url */
3302 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3303 /** XML tag for redirected url */
3304 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3305 /** XML attribute for mcc */
3306 private static final String ATTR_MCC = "mcc";
3307 /** XML attribute for mnc */
3308 private static final String ATTR_MNC = "mnc";
3309
3310 private static final int REDIRECTED_PROVISIONING = 1;
3311 private static final int PROVISIONING = 2;
3312
3313 private String getProvisioningUrlBaseFromFile(int type) {
3314 FileReader fileReader = null;
3315 XmlPullParser parser = null;
3316 Configuration config = mContext.getResources().getConfiguration();
3317 String tagType;
3318
3319 switch (type) {
3320 case PROVISIONING:
3321 tagType = TAG_PROVISIONING_URL;
3322 break;
3323 case REDIRECTED_PROVISIONING:
3324 tagType = TAG_REDIRECTED_URL;
3325 break;
3326 default:
3327 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3328 type);
3329 }
3330
3331 try {
3332 fileReader = new FileReader(mProvisioningUrlFile);
3333 parser = Xml.newPullParser();
3334 parser.setInput(fileReader);
3335 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3336
3337 while (true) {
3338 XmlUtils.nextElement(parser);
3339
3340 String element = parser.getName();
3341 if (element == null) break;
3342
3343 if (element.equals(tagType)) {
3344 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3345 try {
3346 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3347 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3348 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3349 parser.next();
3350 if (parser.getEventType() == XmlPullParser.TEXT) {
3351 return parser.getText();
3352 }
3353 }
3354 }
3355 } catch (NumberFormatException e) {
3356 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3357 }
3358 }
3359 }
3360 return null;
3361 } catch (FileNotFoundException e) {
3362 loge("Carrier Provisioning Urls file not found");
3363 } catch (XmlPullParserException e) {
3364 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3365 } catch (IOException e) {
3366 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3367 } finally {
3368 if (fileReader != null) {
3369 try {
3370 fileReader.close();
3371 } catch (IOException e) {}
3372 }
3373 }
3374 return null;
3375 }
3376
Wink Saville42d4f082013-07-20 20:31:59 -07003377 @Override
3378 public String getMobileRedirectedProvisioningUrl() {
3379 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003380 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3381 if (TextUtils.isEmpty(url)) {
3382 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3383 }
3384 return url;
3385 }
3386
Wink Saville42d4f082013-07-20 20:31:59 -07003387 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003388 public String getMobileProvisioningUrl() {
3389 enforceConnectivityInternalPermission();
3390 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3391 if (TextUtils.isEmpty(url)) {
3392 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003393 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003394 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003395 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003396 }
Wink Saville8cf35602013-07-10 23:00:07 -07003397 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003398 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003399 String phoneNumber = mTelephonyManager.getLine1Number();
3400 if (TextUtils.isEmpty(phoneNumber)) {
3401 phoneNumber = "0000000000";
3402 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003403 url = String.format(url,
3404 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3405 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003406 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003407 }
3408
Wink Savilleab9321d2013-06-29 21:10:57 -07003409 return url;
3410 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003411
Wink Saville948282b2013-08-29 08:55:16 -07003412 @Override
3413 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003414 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003415 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003416 final long ident = Binder.clearCallingIdentity();
3417 try {
3418 setProvNotificationVisible(visible, networkType, action);
3419 } finally {
3420 Binder.restoreCallingIdentity(ident);
3421 }
Wink Saville948282b2013-08-29 08:55:16 -07003422 }
Wink Saville7788c612013-08-29 14:57:08 -07003423
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003424 @Override
3425 public void setAirplaneMode(boolean enable) {
3426 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003427 final long ident = Binder.clearCallingIdentity();
3428 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003429 final ContentResolver cr = mContext.getContentResolver();
3430 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3431 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3432 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003433 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003434 } finally {
3435 Binder.restoreCallingIdentity(ident);
3436 }
3437 }
3438
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003439 private void onUserStart(int userId) {
3440 synchronized(mVpns) {
3441 Vpn userVpn = mVpns.get(userId);
3442 if (userVpn != null) {
3443 loge("Starting user already has a VPN");
3444 return;
3445 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003446 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003447 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003448 }
3449 }
3450
3451 private void onUserStop(int userId) {
3452 synchronized(mVpns) {
3453 Vpn userVpn = mVpns.get(userId);
3454 if (userVpn == null) {
3455 loge("Stopping user has no VPN");
3456 return;
3457 }
3458 mVpns.delete(userId);
3459 }
3460 }
3461
3462 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3463 @Override
3464 public void onReceive(Context context, Intent intent) {
3465 final String action = intent.getAction();
3466 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3467 if (userId == UserHandle.USER_NULL) return;
3468
3469 if (Intent.ACTION_USER_STARTING.equals(action)) {
3470 onUserStart(userId);
3471 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3472 onUserStop(userId);
3473 }
3474 }
3475 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003476
Robert Greenwalta67be032014-05-16 15:49:14 -07003477 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3478 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003479 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3480 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003481
Robert Greenwalta67be032014-05-16 15:49:14 -07003482 private static class NetworkFactoryInfo {
3483 public final String name;
3484 public final Messenger messenger;
3485 public final AsyncChannel asyncChannel;
3486
3487 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3488 this.name = name;
3489 this.messenger = messenger;
3490 this.asyncChannel = asyncChannel;
3491 }
3492 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003493
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003494 /**
3495 * Tracks info about the requester.
3496 * Also used to notice when the calling process dies so we can self-expire
3497 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003498 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3499 static final boolean REQUEST = true;
3500 static final boolean LISTEN = false;
3501
3502 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003503 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003504 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003505 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003506 final int mPid;
3507 final int mUid;
3508 final Messenger messenger;
3509 final boolean isRequest;
3510
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003511 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3512 request = r;
3513 mPendingIntent = pi;
3514 messenger = null;
3515 mBinder = null;
3516 mPid = getCallingPid();
3517 mUid = getCallingUid();
3518 this.isRequest = isRequest;
3519 }
3520
Robert Greenwalt9258c642014-03-26 16:47:06 -07003521 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3522 super();
3523 messenger = m;
3524 request = r;
3525 mBinder = binder;
3526 mPid = getCallingPid();
3527 mUid = getCallingUid();
3528 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003529 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003530
3531 try {
3532 mBinder.linkToDeath(this, 0);
3533 } catch (RemoteException e) {
3534 binderDied();
3535 }
3536 }
3537
3538 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003539 if (mBinder != null) {
3540 mBinder.unlinkToDeath(this, 0);
3541 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003542 }
3543
3544 public void binderDied() {
3545 log("ConnectivityService NetworkRequestInfo binderDied(" +
3546 request + ", " + mBinder + ")");
3547 releaseNetworkRequest(request);
3548 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003549
3550 public String toString() {
3551 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003552 mPid + " for " + request +
3553 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003554 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003555 }
3556
3557 @Override
3558 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003559 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003560 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003561 enforceNetworkRequestPermissions(networkCapabilities);
3562 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003563
Robert Greenwalt6078b502014-06-11 16:05:07 -07003564 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003565 throw new IllegalArgumentException("Bad timeout specified");
3566 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003567
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003568 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3569 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003570 if (DBG) log("requestNetwork for " + networkRequest);
3571 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3572 NetworkRequestInfo.REQUEST);
3573
3574 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003575 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003576 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003577 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003578 }
3579 return networkRequest;
3580 }
3581
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003582 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003583 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003584 enforceConnectivityInternalPermission();
3585 } else {
3586 enforceChangePermission();
3587 }
3588 }
3589
fenglub15e72b2015-03-20 11:29:56 -07003590 @Override
fengludb571472015-04-21 17:12:05 -07003591 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003592 enforceAccessPermission();
3593 NetworkAgentInfo nai = null;
3594 if (network == null) {
3595 return false;
3596 }
3597 synchronized (mNetworkForNetId) {
3598 nai = mNetworkForNetId.get(network.netId);
3599 }
3600 if (nai != null) {
3601 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3602 return true;
3603 }
3604 return false;
3605 }
3606
3607
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003608 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3609 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003610 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003611 final int uidRules;
3612 final int uid = Binder.getCallingUid();
3613 synchronized(mRulesLock) {
3614 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3615 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003616 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003617 // we could silently fail or we can filter the available nets to only give
3618 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003619 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003620 }
3621 }
3622 }
3623
Robert Greenwalt9258c642014-03-26 16:47:06 -07003624 @Override
3625 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3626 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003627 checkNotNull(operation, "PendingIntent cannot be null.");
3628 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3629 enforceNetworkRequestPermissions(networkCapabilities);
3630 enforceMeteredApnPolicy(networkCapabilities);
3631
3632 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3633 nextNetworkRequestId());
3634 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3635 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3636 NetworkRequestInfo.REQUEST);
3637 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3638 nri));
3639 return networkRequest;
3640 }
3641
Jeremy Joslin79294842014-12-03 17:15:28 -08003642 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3643 mHandler.sendMessageDelayed(
3644 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3645 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3646 }
3647
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003648 @Override
3649 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003650 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003651 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3652 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003653 }
3654
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003655 // In order to implement the compatibility measure for pre-M apps that call
3656 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3657 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3658 // This ensures it has permission to do so.
3659 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3660 if (nc == null) {
3661 return false;
3662 }
3663 int[] transportTypes = nc.getTransportTypes();
3664 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3665 return false;
3666 }
3667 try {
3668 mContext.enforceCallingOrSelfPermission(
3669 android.Manifest.permission.ACCESS_WIFI_STATE,
3670 "ConnectivityService");
3671 } catch (SecurityException e) {
3672 return false;
3673 }
3674 return true;
3675 }
3676
Robert Greenwalt9258c642014-03-26 16:47:06 -07003677 @Override
3678 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3679 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003680 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3681 enforceAccessPermission();
3682 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003683
3684 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003685 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003686 if (DBG) log("listenForNetwork for " + networkRequest);
3687 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3688 NetworkRequestInfo.LISTEN);
3689
3690 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3691 return networkRequest;
3692 }
3693
3694 @Override
3695 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3696 PendingIntent operation) {
3697 }
3698
3699 @Override
3700 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003701 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3702 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003703 }
3704
3705 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003706 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003707 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003708 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3709 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003710 }
3711
Robert Greenwalta67be032014-05-16 15:49:14 -07003712 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003713 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003714 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3715 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3716 }
3717
3718 @Override
3719 public void unregisterNetworkFactory(Messenger messenger) {
3720 enforceConnectivityInternalPermission();
3721 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3722 }
3723
3724 private void handleUnregisterNetworkFactory(Messenger messenger) {
3725 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3726 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003727 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003728 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003729 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003730 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003731 }
3732
Robert Greenwalt7b816022014-04-18 15:25:25 -07003733 /**
3734 * NetworkAgentInfo supporting a request by requestId.
3735 * These have already been vetted (their Capabilities satisfy the request)
3736 * and the are the highest scored network available.
3737 * the are keyed off the Requests requestId.
3738 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003739 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003740 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3741 new SparseArray<NetworkAgentInfo>();
3742
Paul Jensen31a94f42015-02-13 14:18:39 -05003743 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3744 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003745 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3746 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003747 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3748 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3749 // there may not be a strict 1:1 correlation between the two.
3750 @GuardedBy("mNetworkForNetId")
3751 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003752
Robert Greenwalt7b816022014-04-18 15:25:25 -07003753 // NetworkAgentInfo keyed off its connecting messenger
3754 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003755 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003756 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3757 new HashMap<Messenger, NetworkAgentInfo>();
3758
Paul Jensen2c311d62014-11-17 12:34:51 -05003759 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003760 private final NetworkRequest mDefaultRequest;
3761
Erik Klineda4bfa82015-04-30 12:58:40 +09003762 // Request used to optionally keep mobile data active even when higher
3763 // priority networks like Wi-Fi are active.
3764 private final NetworkRequest mDefaultMobileDataRequest;
3765
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003766 private NetworkAgentInfo getDefaultNetwork() {
3767 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3768 }
3769
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003770 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003771 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003772 }
3773
Paul Jensen31a94f42015-02-13 14:18:39 -05003774 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003775 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003776 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003777 enforceConnectivityInternalPermission();
3778
Paul Jensen2c311d62014-11-17 12:34:51 -05003779 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3780 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003781 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003782 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3783 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3784 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003785 synchronized (this) {
3786 nai.networkMonitor.systemReady = mSystemReady;
3787 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003788 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003789 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003790 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003791 }
3792
3793 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3794 if (VDBG) log("Got NetworkAgent Messenger");
3795 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003796 synchronized (mNetworkForNetId) {
3797 mNetworkForNetId.put(na.network.netId, na);
3798 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003799 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3800 NetworkInfo networkInfo = na.networkInfo;
3801 na.networkInfo = null;
3802 updateNetworkInfo(na, networkInfo);
3803 }
3804
3805 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3806 LinkProperties newLp = networkAgent.linkProperties;
3807 int netId = networkAgent.network.netId;
3808
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003809 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3810 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003811 if (networkAgent.clatd != null) {
3812 networkAgent.clatd.fixupLinkProperties(oldLp);
3813 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003814
Paul Jensen992f2522014-04-28 10:33:11 -04003815 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003816 updateMtu(newLp, oldLp);
3817 // TODO - figure out what to do for clat
3818// for (LinkProperties lp : newLp.getStackedLinks()) {
3819// updateMtu(lp, null);
3820// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003821 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003822
3823 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3824 // For now, use it only when the network has Internet access. http://b/18327075
3825 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003826 NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003827 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003828 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3829
Paul Jensen3b759822014-05-13 11:44:01 -04003830 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003831 if (isDefaultNetwork(networkAgent)) {
3832 handleApplyDefaultProxy(newLp.getHttpProxy());
3833 } else {
3834 updateProxy(newLp, oldLp, networkAgent);
3835 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003836 // TODO - move this check to cover the whole function
3837 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003838 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003839 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3840 }
Paul Jensen3b759822014-05-13 11:44:01 -04003841 }
3842
Lorenzo Colitti95439462014-10-09 13:44:48 +09003843 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3844 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3845 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003846
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003847 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003848 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3849 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003850 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003851 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003852 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003853 }
Paul Jensen992f2522014-04-28 10:33:11 -04003854
3855 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3856 CompareResult<String> interfaceDiff = new CompareResult<String>();
3857 if (oldLp != null) {
3858 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3859 } else if (newLp != null) {
3860 interfaceDiff.added = newLp.getAllInterfaceNames();
3861 }
3862 for (String iface : interfaceDiff.added) {
3863 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003864 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003865 mNetd.addInterfaceToNetwork(iface, netId);
3866 } catch (Exception e) {
3867 loge("Exception adding interface: " + e);
3868 }
3869 }
3870 for (String iface : interfaceDiff.removed) {
3871 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003872 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003873 mNetd.removeInterfaceFromNetwork(iface, netId);
3874 } catch (Exception e) {
3875 loge("Exception removing interface: " + e);
3876 }
3877 }
3878 }
3879
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003880 /**
3881 * Have netd update routes from oldLp to newLp.
3882 * @return true if routes changed between oldLp and newLp
3883 */
3884 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003885 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3886 if (oldLp != null) {
3887 routeDiff = oldLp.compareAllRoutes(newLp);
3888 } else if (newLp != null) {
3889 routeDiff.added = newLp.getAllRoutes();
3890 }
3891
3892 // add routes before removing old in case it helps with continuous connectivity
3893
3894 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3895 for (RouteInfo route : routeDiff.added) {
3896 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003897 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003898 try {
3899 mNetd.addRoute(netId, route);
3900 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003901 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3902 loge("Exception in addRoute for non-gateway: " + e);
3903 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003904 }
3905 }
3906 for (RouteInfo route : routeDiff.added) {
3907 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003908 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003909 try {
3910 mNetd.addRoute(netId, route);
3911 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003912 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3913 loge("Exception in addRoute for gateway: " + e);
3914 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003915 }
3916 }
3917
3918 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003919 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003920 try {
3921 mNetd.removeRoute(netId, route);
3922 } catch (Exception e) {
3923 loge("Exception in removeRoute: " + e);
3924 }
3925 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003926 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003927 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003928 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3929 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003930 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003931 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003932 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003933 dnses = new ArrayList();
3934 dnses.add(mDefaultDns);
3935 if (DBG) {
3936 loge("no dns provided for netId " + netId + ", so using defaults");
3937 }
3938 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003939 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003940 try {
3941 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3942 newLp.getDomains());
3943 } catch (Exception e) {
3944 loge("Exception in setDnsServersForNetwork: " + e);
3945 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003946 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3947 if (defaultNai != null && defaultNai.network.netId == netId) {
3948 setDefaultDnsSystemProperties(dnses);
3949 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003950 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003951 } else if (flush) {
3952 try {
3953 mNetd.flushNetworkDnsCache(netId);
3954 } catch (Exception e) {
3955 loge("Exception in flushNetworkDnsCache: " + e);
3956 }
3957 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003958 }
3959 }
3960
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003961 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3962 int last = 0;
3963 for (InetAddress dns : dnses) {
3964 ++last;
3965 String key = "net.dns" + last;
3966 String value = dns.getHostAddress();
3967 SystemProperties.set(key, value);
3968 }
3969 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3970 String key = "net.dns" + i;
3971 SystemProperties.set(key, "");
3972 }
3973 mNumDnsEntries = last;
3974 }
3975
Robert Greenwalt7b816022014-04-18 15:25:25 -07003976 private void updateCapabilities(NetworkAgentInfo networkAgent,
3977 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003978 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3979 synchronized (networkAgent) {
3980 networkAgent.networkCapabilities = networkCapabilities;
3981 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003982 if (networkAgent.lastValidated) {
3983 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
3984 // There's no need to remove the capability if we think the network is unvalidated,
3985 // because NetworkAgents don't set the validated capability.
3986 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003987 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003988 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003989 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003990 }
3991
Paul Jensenc8b9a742014-09-30 15:37:41 -04003992 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3993 for (int i = 0; i < nai.networkRequests.size(); i++) {
3994 NetworkRequest nr = nai.networkRequests.valueAt(i);
3995 // Don't send listening requests to factories. b/17393458
3996 if (!isRequest(nr)) continue;
3997 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3998 }
3999 }
4000
Robert Greenwalt7b816022014-04-18 15:25:25 -07004001 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4002 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004003 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004004 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4005 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004006 }
4007 }
4008
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004009 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4010 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004011 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004012 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004013 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4014 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004015 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004016 sendIntent(nri.mPendingIntent, intent);
4017 }
4018 // else not handled
4019 }
4020
4021 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4022 mPendingIntentWakeLock.acquire();
4023 try {
4024 if (DBG) log("Sending " + pendingIntent);
4025 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4026 } catch (PendingIntent.CanceledException e) {
4027 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4028 mPendingIntentWakeLock.release();
4029 releasePendingNetworkRequest(pendingIntent);
4030 }
4031 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4032 }
4033
4034 @Override
4035 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4036 String resultData, Bundle resultExtras) {
4037 if (DBG) log("Finished sending " + pendingIntent);
4038 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004039 // Release with a delay so the receiving client has an opportunity to put in its
4040 // own request.
4041 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004042 }
4043
Robert Greenwalt9258c642014-03-26 16:47:06 -07004044 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004045 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004046 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004047 Bundle bundle = new Bundle();
4048 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4049 new NetworkRequest(nri.request));
4050 Message msg = Message.obtain();
4051 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4052 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4053 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4054 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004055 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004056 case ConnectivityManager.CALLBACK_LOSING: {
4057 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4058 break;
4059 }
4060 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4061 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4062 new NetworkCapabilities(networkAgent.networkCapabilities));
4063 break;
4064 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004065 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004066 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4067 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004068 break;
4069 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004070 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004071 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004072 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004073 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004074 if (VDBG) {
4075 log("sending notification " + notifyTypeToName(notificationType) +
4076 " for " + nri.request);
4077 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004078 nri.messenger.send(msg);
4079 } catch (RemoteException e) {
4080 // may occur naturally in the race of binder death.
4081 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4082 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004083 }
4084
Paul Jensenc8b9a742014-09-30 15:37:41 -04004085 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4086 for (int i = 0; i < nai.networkRequests.size(); i++) {
4087 NetworkRequest nr = nai.networkRequests.valueAt(i);
4088 // Ignore listening requests.
4089 if (!isRequest(nr)) continue;
4090 loge("Dead network still had at least " + nr);
4091 break;
4092 }
4093 nai.asyncChannel.disconnect();
4094 }
4095
Robert Greenwalt7b816022014-04-18 15:25:25 -07004096 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4097 if (oldNetwork == null) {
4098 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4099 return;
4100 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004101 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4102 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004103 }
4104
Paul Jensen27b02b72014-07-14 12:03:33 -04004105 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004106 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004107 setupDataActivityTracking(newNetwork);
4108 try {
4109 mNetd.setDefaultNetId(newNetwork.network.netId);
4110 } catch (Exception e) {
4111 loge("Exception setting default network :" + e);
4112 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004113 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004114 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004115 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004116 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004117 }
4118
Paul Jensen2161a8e2014-09-11 11:00:39 -04004119 // Handles a network appearing or improving its score.
4120 //
4121 // - Evaluates all current NetworkRequests that can be
4122 // satisfied by newNetwork, and reassigns to newNetwork
4123 // any such requests for which newNetwork is the best.
4124 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004125 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004126 // needed. A network is needed if it is the best network for
4127 // one or more NetworkRequests, or if it is a VPN.
4128 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004129 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004130 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4131 //
4132 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4133 // networks that have no chance (i.e. even if validated)
4134 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004135 //
4136 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4137 // it does not remove NetworkRequests that other Networks could better satisfy.
4138 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4139 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4140 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004141 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004142 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004143 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004144 // torn down if unneeded.
4145 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4146 // performed to tear down unvalidated networks that have no chance (i.e. even if
4147 // validated) of becoming the highest scoring network.
4148 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4149 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004150 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004151 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004152 loge("ERROR: nascent network not validated.");
4153 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004154 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004155 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004156 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004157 if (DBG) log("rematching " + newNetwork.name());
4158 // Find and migrate to this Network any NetworkRequests for
4159 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004160 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004161 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004162 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004163 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4164 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004165 if (DBG) {
4166 log("Network " + newNetwork.name() + " was already satisfying" +
4167 " request " + nri.request.requestId + ". No change.");
4168 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004169 keep = true;
4170 continue;
4171 }
4172
4173 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004174 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004175 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004176 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004177 // This is not a request, it's a callback listener.
4178 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004179 newNetwork.addRequest(nri.request);
4180 continue;
4181 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004182
Robert Greenwalt7b816022014-04-18 15:25:25 -07004183 // next check if it's better than any current network we're using for
4184 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004185 if (VDBG) {
4186 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004187 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4188 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004189 }
4190 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004191 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004192 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004193 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004194 currentNetwork.networkRequests.remove(nri.request.requestId);
4195 currentNetwork.networkLingered.add(nri.request);
4196 affectedNetworks.add(currentNetwork);
4197 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004198 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004199 }
Paul Jensen573a0352015-01-08 10:49:34 -05004200 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004201 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004202 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004203 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004204 // Tell NetworkFactories about the new score, so they can stop
4205 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004206 // TODO - this could get expensive if we have alot of requests for this
4207 // network. Think about if there is a way to reduce this. Push
4208 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004209 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004210 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004211 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004212 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004213 }
4214 }
4215 }
4216 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004217 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004218 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004219 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004220 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4221 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4222 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004223 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004224 }
4225 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004226 if (keep) {
4227 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004228 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004229 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004230 synchronized (ConnectivityService.this) {
4231 // have a new default network, release the transition wakelock in
4232 // a second if it's held. The second pause is to allow apps
4233 // to reconnect over the new network
4234 if (mNetTransitionWakeLock.isHeld()) {
4235 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4236 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4237 mNetTransitionWakeLockSerialNumber, 0),
4238 1000);
4239 }
4240 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004241 }
4242
4243 // do this after the default net is switched, but
4244 // before LegacyTypeTracker sends legacy broadcasts
4245 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4246
4247 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004248 // Maintain the illusion: since the legacy API only
4249 // understands one network at a time, we must pretend
4250 // that the current default network disconnected before
4251 // the new one connected.
4252 if (oldDefaultNetwork != null) {
4253 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004254 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004255 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004256 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004257 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4258 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004259 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004260
4261 // Notify battery stats service about this network, both the normal
4262 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004263 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004264 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004265 final IBatteryStats bs = BatteryStatsService.getService();
4266 final int type = newNetwork.networkInfo.getType();
4267
4268 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4269 bs.noteNetworkInterfaceType(baseIface, type);
4270 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4271 final String stackedIface = stacked.getInterfaceName();
4272 bs.noteNetworkInterfaceType(stackedIface, type);
4273 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4274 }
4275 } catch (RemoteException ignored) {
4276 }
4277
Robert Greenwalt152ed372014-12-17 17:19:53 -08004278 // This has to happen after the notifyNetworkCallbacks as that tickles each
4279 // ConnectivityManager instance so that legacy requests correctly bind dns
4280 // requests to this network. The legacy users are listening for this bcast
4281 // and will generally do a dns request so they can ensureRouteToHost and if
4282 // they do that before the callbacks happen they'll use the default network.
4283 //
4284 // TODO: Is there still a race here? We send the broadcast
4285 // after sending the callback, but if the app can receive the
4286 // broadcast before the callback, it might still break.
4287 //
4288 // This *does* introduce a race where if the user uses the new api
4289 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4290 // they may get old info. Reverse this after the old startUsing api is removed.
4291 // This is on top of the multiple intent sequencing referenced in the todo above.
4292 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4293 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4294 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4295 // legacy type tracker filters out repeat adds
4296 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4297 }
4298 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004299
4300 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4301 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4302 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4303 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4304 if (newNetwork.isVPN()) {
4305 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4306 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004307 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004308 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004309 // validated (and get evaluated against peers, one losing here), or get reaped (see
4310 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4311 // network. Networks that have been up for a while and are validated should be torn
4312 // down via the lingering process so communication on that network is given time to
4313 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004314 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004315 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004316 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004317 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4318 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004319 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004320 if (DBG) log("Reaping " + nai.name());
4321 teardownUnneededNetwork(nai);
4322 }
4323 }
4324 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004325 }
4326
Paul Jensen2161a8e2014-09-11 11:00:39 -04004327 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4328 // being disconnected.
4329 // If only one Network's score or capabilities have been modified since the last time
4330 // this function was called, pass this Network in via the "changed" arugment, otherwise
4331 // pass null.
4332 // If only one Network has been changed but its NetworkCapabilities have not changed,
4333 // pass in the Network's score (from getCurrentScore()) prior to the change via
4334 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4335 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4336 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4337 // to avoid the slowness. It is not simply enough to process just "changed", for
4338 // example in the case where "changed"'s score decreases and another network should begin
4339 // satifying a NetworkRequest that "changed" currently satisfies.
4340
4341 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4342 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4343 // rematchNetworkAndRequests() handles.
4344 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004345 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4346 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004347 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004348 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4349 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4350 NascentState.NOT_JUST_VALIDATED,
4351 // Only reap the last time through the loop. Reaping before all rematching
4352 // is complete could incorrectly teardown a network that hasn't yet been
4353 // rematched.
4354 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4355 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004356 }
4357 }
4358 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004359
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004360 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004361 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004362 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004363 // For now only update icons for default connection.
4364 // TODO: Update WiFi and cellular icons separately. b/17237507
4365 if (!isDefaultNetwork(nai)) return;
4366
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004367 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004368 // Don't repeat publish.
4369 if (newInetCondition == mDefaultInetConditionPublished) return;
4370
4371 mDefaultInetConditionPublished = newInetCondition;
4372 sendInetConditionBroadcast(nai.networkInfo);
4373 }
4374
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004375 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4376 if (mLockdownTracker != null) {
4377 if (nai != null && nai.isVPN()) {
4378 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4379 } else {
4380 mLockdownTracker.onNetworkInfoChanged();
4381 }
4382 }
4383 }
4384
Robert Greenwalt7b816022014-04-18 15:25:25 -07004385 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4386 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004387 NetworkInfo oldInfo = null;
4388 synchronized (networkAgent) {
4389 oldInfo = networkAgent.networkInfo;
4390 networkAgent.networkInfo = newInfo;
4391 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004392 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004393
4394 if (oldInfo != null && oldInfo.getState() == state) {
4395 if (VDBG) log("ignoring duplicate network state non-change");
4396 return;
4397 }
4398 if (DBG) {
4399 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4400 (oldInfo == null ? "null" : oldInfo.getState()) +
4401 " to " + state);
4402 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004403
Paul Jenseneec75412014-08-04 12:21:19 -04004404 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004405 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004406 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004407 if (networkAgent.isVPN()) {
4408 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004409 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4410 (networkAgent.networkMisc == null ||
4411 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004412 } else {
4413 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4414 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004415 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004416 loge("Error creating network " + networkAgent.network.netId + ": "
4417 + e.getMessage());
4418 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004419 }
Paul Jenseneec75412014-08-04 12:21:19 -04004420 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004421 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004422 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004423
Paul Jensenca8f16a2014-05-09 12:47:55 -04004424 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004425 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004426
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004427 if (networkAgent.isVPN()) {
4428 // Temporarily disable the default proxy (not global).
4429 synchronized (mProxyLock) {
4430 if (!mDefaultProxyDisabled) {
4431 mDefaultProxyDisabled = true;
4432 if (mGlobalProxy == null && mDefaultProxy != null) {
4433 sendProxyBroadcast(null);
4434 }
4435 }
4436 }
4437 // TODO: support proxy per network.
4438 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004439
Paul Jensen2161a8e2014-09-11 11:00:39 -04004440 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004441 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4442 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004443
4444 // This has to happen after matching the requests, because callbacks are just requests.
4445 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004446 } else if (state == NetworkInfo.State.DISCONNECTED ||
4447 state == NetworkInfo.State.SUSPENDED) {
4448 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004449 if (networkAgent.isVPN()) {
4450 synchronized (mProxyLock) {
4451 if (mDefaultProxyDisabled) {
4452 mDefaultProxyDisabled = false;
4453 if (mGlobalProxy == null && mDefaultProxy != null) {
4454 sendProxyBroadcast(mDefaultProxy);
4455 }
4456 }
4457 }
4458 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004459 }
4460 }
4461
Robert Greenwaltac96c522014-06-03 16:43:57 -07004462 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4463 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004464 if (score < 0) {
4465 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4466 "). Bumping score to min of 0");
4467 score = 0;
4468 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004469
Paul Jensen2161a8e2014-09-11 11:00:39 -04004470 final int oldScore = nai.getCurrentScore();
4471 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004472
Paul Jensen57a767f2014-11-19 13:01:46 -05004473 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004474
Paul Jensenc8b9a742014-09-30 15:37:41 -04004475 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004476 }
4477
Robert Greenwalt9258c642014-03-26 16:47:06 -07004478 // notify only this one new request of the current state
4479 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4480 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4481 // TODO - read state from monitor to decide what to send.
4482// if (nai.networkMonitor.isLingering()) {
4483// notifyType = NetworkCallbacks.LOSING;
4484// } else if (nai.networkMonitor.isEvaluating()) {
4485// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4486// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004487 if (nri.mPendingIntent == null) {
4488 callCallbackForRequest(nri, nai, notifyType);
4489 } else {
4490 sendPendingIntentForRequest(nri, nai, notifyType);
4491 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004492 }
4493
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004494 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004495 // The NetworkInfo we actually send out has no bearing on the real
4496 // state of affairs. For example, if the default connection is mobile,
4497 // and a request for HIPRI has just gone away, we need to pretend that
4498 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4499 // the state to DISCONNECTED, even though the network is of type MOBILE
4500 // and is still connected.
4501 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4502 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004503 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004504 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004505 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004506 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004507 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004508 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4509 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4510 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4511 if (info.isFailover()) {
4512 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4513 nai.networkInfo.setFailover(false);
4514 }
4515 if (info.getReason() != null) {
4516 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4517 }
4518 if (info.getExtraInfo() != null) {
4519 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4520 }
4521 NetworkAgentInfo newDefaultAgent = null;
4522 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4523 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4524 if (newDefaultAgent != null) {
4525 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4526 newDefaultAgent.networkInfo);
4527 } else {
4528 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4529 }
4530 }
4531 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4532 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004533 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004534 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004535 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004536 }
4537 }
4538 }
4539
Robert Greenwalt7b816022014-04-18 15:25:25 -07004540 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004541 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004542 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004543 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4544 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4545 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004546 if (nri.mPendingIntent == null) {
4547 callCallbackForRequest(nri, networkAgent, notifyType);
4548 } else {
4549 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4550 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004551 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004552 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004553
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004554 private String notifyTypeToName(int notifyType) {
4555 switch (notifyType) {
4556 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4557 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4558 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4559 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4560 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4561 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4562 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4563 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4564 }
4565 return "UNKNOWN";
4566 }
4567
Jeff Sharkey69736342014-12-08 14:50:12 -08004568 /**
4569 * Notify other system services that set of active ifaces has changed.
4570 */
4571 private void notifyIfacesChanged() {
4572 try {
4573 mStatsService.forceUpdateIfaces();
4574 } catch (Exception ignored) {
4575 }
4576 }
4577
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004578 @Override
4579 public boolean addVpnAddress(String address, int prefixLength) {
4580 throwIfLockdownEnabled();
4581 int user = UserHandle.getUserId(Binder.getCallingUid());
4582 synchronized (mVpns) {
4583 return mVpns.get(user).addAddress(address, prefixLength);
4584 }
4585 }
4586
4587 @Override
4588 public boolean removeVpnAddress(String address, int prefixLength) {
4589 throwIfLockdownEnabled();
4590 int user = UserHandle.getUserId(Binder.getCallingUid());
4591 synchronized (mVpns) {
4592 return mVpns.get(user).removeAddress(address, prefixLength);
4593 }
4594 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004595
4596 @Override
4597 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4598 throwIfLockdownEnabled();
4599 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004600 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004601 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004602 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004603 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004604 if (success) {
4605 notifyIfacesChanged();
4606 }
4607 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004608 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004609
4610 @Override
4611 public void factoryReset() {
4612 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004613
4614 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4615 return;
4616 }
4617
Robin Lee3b3dd942015-05-12 18:14:58 +01004618 final int userId = UserHandle.getCallingUserId();
4619
Stuart Scottf1fb3972015-04-02 18:00:02 -07004620 // Turn airplane mode off
4621 setAirplaneMode(false);
4622
Stuart Scotte3e314d2015-04-20 14:07:45 -07004623 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4624 // Untether
4625 for (String tether : getTetheredIfaces()) {
4626 untether(tether);
4627 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004628 }
4629
Stuart Scotte3e314d2015-04-20 14:07:45 -07004630 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4631 // Turn VPN off
4632 VpnConfig vpnConfig = getVpnConfig(userId);
4633 if (vpnConfig != null) {
4634 if (vpnConfig.legacy) {
4635 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4636 } else {
4637 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4638 // in the future without user intervention.
4639 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004640
Stuart Scotte3e314d2015-04-20 14:07:45 -07004641 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4642 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004643 }
4644 }
4645 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004646}