blob: eceac51af3fa821ec5de0bd3c566af398de82679 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
26import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070027import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070028import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070029
Wenchao Tongf5ea3402015-03-04 13:26:38 -080030import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070031import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070032import android.app.Notification;
33import android.app.NotificationManager;
34import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070035import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080036import android.content.ContentResolver;
37import android.content.Context;
38import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070041import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090042import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070043import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.net.ConnectivityManager;
45import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070046import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070047import android.net.INetworkPolicyListener;
48import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070049import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080050import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070051import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070052import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070053import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070054import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070055import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080056import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070057import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070058import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070059import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070060import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070061import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070062import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070063import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040064import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070065import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040066import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040067import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080068import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070069import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040070import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080071import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070072import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070073import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070074import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Looper;
76import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070077import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070078import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070079import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070080import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070081import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070082import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080083import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070084import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040085import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080086import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070087import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070088import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070089import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070090import android.text.TextUtils;
Joe Onorato8a9b2202010-02-26 18:56:32 -080091import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070092import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -050093import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070094import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070095import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080096
Wink Savilleab9321d2013-06-29 21:10:57 -070097import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -040098import com.android.internal.annotations.GuardedBy;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -070099import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700100import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700101import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700102import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800103import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700104import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700105import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700106import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700107import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700108import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700109import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400110import com.android.server.connectivity.DataConnectionStats;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900111import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700112import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400113import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400114import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700115import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800116import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700117import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700118import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700119import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700120import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700121import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700122
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700123import org.xmlpull.v1.XmlPullParser;
124import org.xmlpull.v1.XmlPullParserException;
125
126import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800127import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700128import java.io.FileNotFoundException;
129import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700130import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800131import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700132import java.net.Inet4Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700133import java.net.InetAddress;
134import java.net.UnknownHostException;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700135import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700136import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700137import java.util.Collection;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700138import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700139import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500140import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700141import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700142import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700143import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700144import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800145
146/**
147 * @hide
148 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800149public class ConnectivityService extends IConnectivityManager.Stub
150 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700151 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800152
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700153 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700154 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800155
Jake Hamby786e71a2014-02-06 14:43:50 -0800156 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700157
Jeff Sharkey899223b2012-08-04 15:24:58 -0700158 // TODO: create better separation between radio types and network types
159
Robert Greenwalt42acef32009-08-12 16:08:25 -0700160 // how long to wait before switching back to a radio's default network
161 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
162 // system property that can override the above value
163 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
164 "android.telephony.apn-restore";
165
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900166 // How long to wait before putting up a "This network doesn't have an Internet connection,
167 // connect anyway?" dialog after the user selects a network that doesn't validate.
168 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
169
Jeremy Joslin79294842014-12-03 17:15:28 -0800170 // How long to delay to removal of a pending intent based request.
171 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
172 private final int mReleasePendingIntentDelayMs;
173
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800174 private Tethering mTethering;
175
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700176 private final PermissionMonitor mPermissionMonitor;
177
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700178 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700179
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700180 @GuardedBy("mVpns")
181 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700182
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700183 private boolean mLockdownEnabled;
184 private LockdownVpnTracker mLockdownTracker;
185
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700186 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
187 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700188 /** Currently active network rules by UID. */
189 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700190 /** Set of ifaces that are costly. */
191 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700192
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800193 private Context mContext;
194 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700195 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700196 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800197
Chia-chi Yeh44bb2512011-07-14 18:01:57 -0700198 private Object mDnsLock = new Object();
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800199 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800200
201 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700202 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800203
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700204 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800205 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700206 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700207
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700208 private String mCurrentTcpBufferSizes;
209
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700210 private static final int ENABLED = 1;
211 private static final int DISABLED = 0;
212
Paul Jensenb10e37f2014-11-25 12:33:08 -0500213 // Arguments to rematchNetworkAndRequests()
214 private enum NascentState {
215 // Indicates a network was just validated for the first time. If the network is found to
216 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
217 JUST_VALIDATED,
218 // Indicates a network was not validated for the first time immediately prior to this call.
219 NOT_JUST_VALIDATED
220 };
221 private enum ReapUnvalidatedNetworks {
222 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
223 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
224 // known that there may be unvalidated networks that could potentially be reaped, and when
225 // all networks have been rematched against all NetworkRequests.
226 REAP,
227 // Don't reap unvalidated networks. This should be passed when it's known that there are
228 // no unvalidated networks that could potentially be reaped, and when some networks have
229 // not yet been rematched against all NetworkRequests.
230 DONT_REAP
231 };
232
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700233 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700234 * used internally to change our mobile data enabled flag
235 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700236 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700237
238 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700239 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700240 * from one net to another. Clear happens when we get a new
241 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
242 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700243 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700244 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700245
Robert Greenwalt434203a2010-10-11 16:00:27 -0700246 /**
247 * used internally to reload global proxy settings
248 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700249 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700250
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700251 /**
Wink Saville628b0852011-08-04 15:01:58 -0700252 * used internally to send a sticky broadcast delayed.
253 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700254 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700255
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700256 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400257 * PAC manager has received new port.
258 */
259 private static final int EVENT_PROXY_HAS_CHANGED = 16;
260
Robert Greenwalte049c232014-04-11 15:53:27 -0700261 /**
262 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700263 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700264 */
265 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
266
Robert Greenwalt7b816022014-04-18 15:25:25 -0700267 /**
268 * used internally when registering NetworkAgents
269 * obj = Messenger
270 */
271 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
272
Robert Greenwalt9258c642014-03-26 16:47:06 -0700273 /**
274 * used to add a network request
275 * includes a NetworkRequestInfo
276 */
277 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
278
279 /**
280 * indicates a timeout period is over - check if we had a network yet or not
281 * and if not, call the timeout calback (but leave the request live until they
282 * cancel it.
283 * includes a NetworkRequestInfo
284 */
285 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
286
287 /**
288 * used to add a network listener - no request
289 * includes a NetworkRequestInfo
290 */
291 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
292
293 /**
294 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400295 * arg1 = UID of caller
296 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700297 */
298 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
299
Robert Greenwalta67be032014-05-16 15:49:14 -0700300 /**
301 * used internally when registering NetworkFactories
302 * obj = Messenger
303 */
304 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
305
Robert Greenwalt27711812014-06-25 16:45:57 -0700306 /**
307 * used internally to expire a wakelock when transitioning
308 * from one net to another. Expire happens when we fail to find
309 * a new network (typically after 1 minute) -
310 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
311 * a replacement network.
312 */
313 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
314
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700315 /**
316 * Used internally to indicate the system is ready.
317 */
318 private static final int EVENT_SYSTEM_READY = 25;
319
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800320 /**
321 * used to add a network request with a pending intent
322 * includes a NetworkRequestInfo
323 */
324 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
325
326 /**
327 * used to remove a pending intent and its associated network request.
328 * arg1 = UID of caller
329 * obj = PendingIntent
330 */
331 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
332
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900333 /**
334 * used to specify whether a network should be used even if unvalidated.
335 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
336 * arg2 = whether to remember this choice in the future (1 or 0)
337 * obj = network
338 */
339 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
340
341 /**
342 * used to ask the user to confirm a connection to an unvalidated network.
343 * obj = network
344 */
345 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700346
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700347 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700348 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700349 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700350 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700351
Mike Lockwood0f79b542009-08-14 14:18:49 -0400352 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800353 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400354
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700355 private PowerManager.WakeLock mNetTransitionWakeLock;
356 private String mNetTransitionWakeLockCausedBy = "";
357 private int mNetTransitionWakeLockSerialNumber;
358 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800359 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700360
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700361 private InetAddress mDefaultDns;
362
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700363 // used in DBG mode to track inet condition reports
364 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
365 private ArrayList mInetLog;
366
Robert Greenwalt434203a2010-10-11 16:00:27 -0700367 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400368 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700369 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700370 private boolean mDefaultProxyDisabled = false;
371
Robert Greenwalt434203a2010-10-11 16:00:27 -0700372 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400373 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700374
Jason Monk602b2322013-07-03 17:04:33 -0400375 private PacManager mPacManager = null;
376
Robert Greenwalt434203a2010-10-11 16:00:27 -0700377 private SettingsObserver mSettingsObserver;
378
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400379 private UserManager mUserManager;
380
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700381 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700382 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700383
Robert Greenwalt50393202011-06-21 17:26:14 -0700384 // the set of network types that can only be enabled by system/sig apps
385 List mProtectedNetworks;
386
John Spurlockbf991a82013-06-24 14:20:23 -0400387 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700388
Wink Savilleab9321d2013-06-29 21:10:57 -0700389 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400390
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700391 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
392 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700393 private final static int MAX_NET_ID = 65535;
394 private int mNextNetId = MIN_NET_ID;
395
Robert Greenwalt34524f02014-05-18 16:22:10 -0700396 // sequence number of NetworkRequests
397 private int mNextNetworkRequestId = 1;
398
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700399 /**
400 * Implements support for the legacy "one network per network type" model.
401 *
402 * We used to have a static array of NetworkStateTrackers, one for each
403 * network type, but that doesn't work any more now that we can have,
404 * for example, more that one wifi network. This class stores all the
405 * NetworkAgentInfo objects that support a given type, but the legacy
406 * API will only see the first one.
407 *
408 * It serves two main purposes:
409 *
410 * 1. Provide information about "the network for a given type" (since this
411 * API only supports one).
412 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
413 * the first network for a given type changes, or if the default network
414 * changes.
415 */
416 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900417
418 private static final boolean DBG = true;
419 private static final boolean VDBG = false;
420 private static final String TAG = "CSLegacyTypeTracker";
421
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700422 /**
423 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
424 * Each list holds references to all NetworkAgentInfos that are used to
425 * satisfy requests for that network type.
426 *
427 * This array is built out at startup such that an unsupported network
428 * doesn't get an ArrayList instance, making this a tristate:
429 * unsupported, supported but not active and active.
430 *
431 * The actual lists are populated when we scan the network types that
432 * are supported on this device.
433 */
434 private ArrayList<NetworkAgentInfo> mTypeLists[];
435
436 public LegacyTypeTracker() {
437 mTypeLists = (ArrayList<NetworkAgentInfo>[])
438 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
439 }
440
441 public void addSupportedType(int type) {
442 if (mTypeLists[type] != null) {
443 throw new IllegalStateException(
444 "legacy list for type " + type + "already initialized");
445 }
446 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
447 }
448
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700449 public boolean isTypeSupported(int type) {
450 return isNetworkTypeValid(type) && mTypeLists[type] != null;
451 }
452
453 public NetworkAgentInfo getNetworkForType(int type) {
454 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
455 return mTypeLists[type].get(0);
456 } else {
457 return null;
458 }
459 }
460
Lorenzo Colittia793a672014-07-31 23:20:17 +0900461 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
462 if (DBG) {
463 log("Sending " + (connected ? "connected" : "disconnected") +
464 " broadcast for type " + type + " " + nai.name() +
465 " isDefaultNetwork=" + isDefaultNetwork(nai));
466 }
467 }
468
469 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700470 public void add(int type, NetworkAgentInfo nai) {
471 if (!isTypeSupported(type)) {
472 return; // Invalid network type.
473 }
474 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
475
476 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
477 if (list.contains(nai)) {
478 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
479 return;
480 }
481
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900482 list.add(nai);
483
484 // Send a broadcast if this is the first network of its type or if it's the default.
485 if (list.size() == 1 || isDefaultNetwork(nai)) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900486 maybeLogBroadcast(nai, true, type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700487 sendLegacyNetworkBroadcast(nai, true, type);
488 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700489 }
490
Lorenzo Colittia793a672014-07-31 23:20:17 +0900491 /** Removes the given network from the specified legacy type list. */
492 public void remove(int type, NetworkAgentInfo nai) {
493 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
494 if (list == null || list.isEmpty()) {
495 return;
496 }
497
498 boolean wasFirstNetwork = list.get(0).equals(nai);
499
500 if (!list.remove(nai)) {
501 return;
502 }
503
504 if (wasFirstNetwork || isDefaultNetwork(nai)) {
505 maybeLogBroadcast(nai, false, type);
506 sendLegacyNetworkBroadcast(nai, false, type);
507 }
508
509 if (!list.isEmpty() && wasFirstNetwork) {
510 if (DBG) log("Other network available for type " + type +
511 ", sending connected broadcast");
512 maybeLogBroadcast(list.get(0), false, type);
513 sendLegacyNetworkBroadcast(list.get(0), false, type);
514 }
515 }
516
517 /** Removes the given network from all legacy type lists. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700518 public void remove(NetworkAgentInfo nai) {
519 if (VDBG) log("Removing agent " + nai);
520 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900521 remove(type, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700522 }
523 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700524
Lorenzo Colittia793a672014-07-31 23:20:17 +0900525 private String naiToString(NetworkAgentInfo nai) {
526 String name = (nai != null) ? nai.name() : "null";
527 String state = (nai.networkInfo != null) ?
528 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
529 "???/???";
530 return name + " " + state;
531 }
532
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700533 public void dump(IndentingPrintWriter pw) {
534 for (int type = 0; type < mTypeLists.length; type++) {
535 if (mTypeLists[type] == null) continue;
536 pw.print(type + " ");
537 pw.increaseIndent();
538 if (mTypeLists[type].size() == 0) pw.println("none");
539 for (NetworkAgentInfo nai : mTypeLists[type]) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900540 pw.println(naiToString(nai));
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700541 }
542 pw.decreaseIndent();
543 }
544 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900545
546 // This class needs its own log method because it has a different TAG.
547 private void log(String s) {
548 Slog.d(TAG, s);
549 }
550
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700551 }
552 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
553
Jeff Sharkey899223b2012-08-04 15:24:58 -0700554 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700555 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800556 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800557
Robert Greenwalte049c232014-04-11 15:53:27 -0700558 NetworkCapabilities netCap = new NetworkCapabilities();
Robert Greenwalt7569f182014-06-08 16:42:59 -0700559 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET);
560 netCap.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 mDefaultRequest = new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -0700562 NetworkRequestInfo nri = new NetworkRequestInfo(null, mDefaultRequest, new Binder(),
563 NetworkRequestInfo.REQUEST);
564 mNetworkRequests.put(mDefaultRequest, nri);
Robert Greenwalte049c232014-04-11 15:53:27 -0700565
Wink Savillebb08caf2010-09-02 19:23:52 -0700566 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
567 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700568 mHandler = new InternalHandler(handlerThread.getLooper());
569 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700570
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800571 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800572 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
573 String id = Settings.Secure.getString(context.getContentResolver(),
574 Settings.Secure.ANDROID_ID);
575 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700576 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800577 SystemProperties.set("net.hostname", name);
578 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800579 }
580
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700581 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700582 String dns = Settings.Global.getString(context.getContentResolver(),
583 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700584 if (dns == null || dns.length() == 0) {
585 dns = context.getResources().getString(
586 com.android.internal.R.string.config_default_dns_server);
587 }
588 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800589 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
590 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800591 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700592 }
593
Jeremy Joslin79294842014-12-03 17:15:28 -0800594 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
595 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
596
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700597 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700598 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800599 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700600 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700601 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700602 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700603
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700604 try {
605 mPolicyManager.registerListener(mPolicyListener);
606 } catch (RemoteException e) {
607 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700608 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700609 }
610
611 final PowerManager powerManager = (PowerManager) context.getSystemService(
612 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700613 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
614 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
615 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800616 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700617
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700618 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700619
Wink Saville51f456f2013-04-23 14:26:51 -0700620 // TODO: What is the "correct" way to do determine if this is a wifi only device?
621 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
622 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700623 String[] naStrings = context.getResources().getStringArray(
624 com.android.internal.R.array.networkAttributes);
625 for (String naString : naStrings) {
626 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700627 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700628 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700629 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800630 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700631 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700632 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700633 }
Wink Saville51f456f2013-04-23 14:26:51 -0700634 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
635 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
636 n.type);
637 continue;
638 }
Wink Saville975c8482011-04-07 14:23:45 -0700639 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800640 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700641 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700642 continue;
643 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700644 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700645
Wink Saville975c8482011-04-07 14:23:45 -0700646 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700647 mNetworksDefined++;
648 } catch(Exception e) {
649 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700650 }
651 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700652
653 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
654 if (mNetConfigs[TYPE_VPN] == null) {
655 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
656 // don't need to add TYPE_VPN to mNetConfigs.
657 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
658 mNetworksDefined++; // used only in the log() statement below.
659 }
660
Wink Saville5e56bc52013-07-29 15:00:57 -0700661 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700662
Robert Greenwalt50393202011-06-21 17:26:14 -0700663 mProtectedNetworks = new ArrayList<Integer>();
664 int[] protectedNetworks = context.getResources().getIntArray(
665 com.android.internal.R.array.config_protectedNetworks);
666 for (int p : protectedNetworks) {
667 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
668 mProtectedNetworks.add(p);
669 } else {
670 if (DBG) loge("Ignoring protectedNetwork " + p);
671 }
672 }
673
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700674 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
675 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700676
Robert Greenwaltfab501672014-07-23 11:44:01 -0700677 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800678
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700679 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
680
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700681 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700682 IntentFilter intentFilter = new IntentFilter();
683 intentFilter.addAction(Intent.ACTION_USER_STARTING);
684 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
685 mContext.registerReceiverAsUser(
686 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900687
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700688 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700689 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700690 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700691 } catch (RemoteException e) {
692 loge("Error registering observer :" + e);
693 }
694
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700695 if (DBG) {
696 mInetLog = new ArrayList();
697 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700698
699 mSettingsObserver = new SettingsObserver(mHandler, EVENT_APPLY_GLOBAL_HTTP_PROXY);
700 mSettingsObserver.observe(mContext);
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800701
John Spurlockbf991a82013-06-24 14:20:23 -0400702 mDataConnectionStats = new DataConnectionStats(mContext);
703 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400704
Jason Monkdecd2952013-10-10 14:02:51 -0400705 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700706
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400707 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800708 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700709
Robert Greenwalt34524f02014-05-18 16:22:10 -0700710 private synchronized int nextNetworkRequestId() {
711 return mNextNetworkRequestId++;
712 }
713
Paul Jensen31a94f42015-02-13 14:18:39 -0500714 private int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400715 synchronized (mNetworkForNetId) {
716 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
717 int netId = mNextNetId;
718 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
719 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500720 if (!mNetIdInUse.get(netId)) {
721 mNetIdInUse.put(netId, true);
722 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400723 }
724 }
725 }
726 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700727 }
728
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800729 private NetworkState getFilteredNetworkState(int networkType, int uid) {
730 NetworkInfo info = null;
731 LinkProperties lp = null;
732 NetworkCapabilities nc = null;
733 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800734 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800735
736 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
737 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
738 if (nai != null) {
739 synchronized (nai) {
740 info = new NetworkInfo(nai.networkInfo);
741 lp = new LinkProperties(nai.linkProperties);
742 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400743 // Network objects are outwardly immutable so there is no point to duplicating.
744 // Duplicating also precludes sharing socket factories and connection pools.
745 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800746 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800747 }
748 info.setType(networkType);
749 } else {
750 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
751 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
752 info.setIsAvailable(true);
753 lp = new LinkProperties();
754 nc = new NetworkCapabilities();
755 network = null;
756 }
757 info = getFilteredNetworkInfo(info, lp, uid);
758 }
759
Jeff Sharkey32566012014-12-02 18:30:14 -0800760 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400761 }
762
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800763 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
764 if (network == null) {
765 return null;
766 }
767 synchronized (mNetworkForNetId) {
768 return mNetworkForNetId.get(network.netId);
769 }
770 };
771
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900772 private Network[] getVpnUnderlyingNetworks(int uid) {
773 if (!mLockdownEnabled) {
774 int user = UserHandle.getUserId(uid);
775 synchronized (mVpns) {
776 Vpn vpn = mVpns.get(user);
777 if (vpn != null && vpn.appliesToUid(uid)) {
778 return vpn.getUnderlyingNetworks();
779 }
780 }
781 }
782 return null;
783 }
784
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800785 private NetworkState getUnfilteredActiveNetworkState(int uid) {
786 NetworkInfo info = null;
787 LinkProperties lp = null;
788 NetworkCapabilities nc = null;
789 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800790 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800791
792 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800793
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900794 final Network[] networks = getVpnUnderlyingNetworks(uid);
795 if (networks != null) {
796 // getUnderlyingNetworks() returns:
797 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
798 // empty array => the VPN explicitly said "no default network".
799 // non-empty array => the VPN specified one or more default networks; we use the
800 // first one.
801 if (networks.length > 0) {
802 nai = getNetworkAgentInfoForNetwork(networks[0]);
803 } else {
804 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800805 }
806 }
807
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800808 if (nai != null) {
809 synchronized (nai) {
810 info = new NetworkInfo(nai.networkInfo);
811 lp = new LinkProperties(nai.linkProperties);
812 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400813 // Network objects are outwardly immutable so there is no point to duplicating.
814 // Duplicating also precludes sharing socket factories and connection pools.
815 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800816 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800817 }
818 }
819
Jeff Sharkey32566012014-12-02 18:30:14 -0800820 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400821 }
822
823 /**
824 * Check if UID should be blocked from using the network with the given LinkProperties.
825 */
826 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700827 final boolean networkCostly;
828 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700829
Robert Greenwalt12e67352014-05-13 21:41:06 -0700830 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700831 synchronized (mRulesLock) {
832 networkCostly = mMeteredIfaces.contains(iface);
833 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700834 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700835
Amith Yamasani15e472352015-04-24 19:06:07 -0700836 if ((uidRules & RULE_REJECT_ALL) != 0
837 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700838 return true;
839 }
840
841 // no restrictive rules; network is visible
842 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700843 }
844
845 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700846 * Return a filtered {@link NetworkInfo}, potentially marked
847 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800848 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700849 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800850 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
851 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400852 // network is blocked; clone and override state
853 info = new NetworkInfo(info);
854 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900855 if (DBG) {
856 log("returning Blocked NetworkInfo for ifname=" +
857 lp.getInterfaceName() + ", uid=" + uid);
858 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700859 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800860 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700861 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700862 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700863 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700864 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700865 }
866
867 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800868 * Return NetworkInfo for the active (i.e., connected) network interface.
869 * It is assumed that at most one network is active at a time. If more
870 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700871 * @return the info for the active network, or {@code null} if none is
872 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800873 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700874 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800875 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700876 enforceAccessPermission();
877 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800878 NetworkState state = getUnfilteredActiveNetworkState(uid);
879 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800880 }
881
Paul Jensen31a94f42015-02-13 14:18:39 -0500882 @Override
883 public Network getActiveNetwork() {
884 enforceAccessPermission();
885 final int uid = Binder.getCallingUid();
886 final int user = UserHandle.getUserId(uid);
887 int vpnNetId = NETID_UNSET;
888 synchronized (mVpns) {
889 final Vpn vpn = mVpns.get(user);
890 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
891 }
892 NetworkAgentInfo nai;
893 if (vpnNetId != NETID_UNSET) {
894 synchronized (mNetworkForNetId) {
895 nai = mNetworkForNetId.get(vpnNetId);
896 }
897 if (nai != null) return nai.network;
898 }
899 nai = getDefaultNetwork();
900 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
901 return nai != null ? nai.network : null;
902 }
903
Wink Saville948282b2013-08-29 08:55:16 -0700904 /**
905 * Find the first Provisioning network.
906 *
907 * @return NetworkInfo or null if none.
908 */
909 private NetworkInfo getProvisioningNetworkInfo() {
910 enforceAccessPermission();
911
912 // Find the first Provisioning Network
913 NetworkInfo provNi = null;
914 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700915 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700916 provNi = ni;
917 break;
918 }
919 }
920 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
921 return provNi;
922 }
923
924 /**
925 * Find the first Provisioning network or the ActiveDefaultNetwork
926 * if there is no Provisioning network
927 *
928 * @return NetworkInfo or null if none.
929 */
930 @Override
931 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
932 enforceAccessPermission();
933
934 NetworkInfo provNi = getProvisioningNetworkInfo();
935 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800936 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700937 }
938 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
939 return provNi;
940 }
941
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700942 public NetworkInfo getActiveNetworkInfoUnfiltered() {
943 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800944 final int uid = Binder.getCallingUid();
945 NetworkState state = getUnfilteredActiveNetworkState(uid);
946 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700947 }
948
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700949 @Override
950 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
951 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800952 NetworkState state = getUnfilteredActiveNetworkState(uid);
953 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700954 }
955
956 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800957 public NetworkInfo getNetworkInfo(int networkType) {
958 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700959 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900960 if (getVpnUnderlyingNetworks(uid) != null) {
961 // A VPN is active, so we may need to return one of its underlying networks. This
962 // information is not available in LegacyTypeTracker, so we have to get it from
963 // getUnfilteredActiveNetworkState.
964 NetworkState state = getUnfilteredActiveNetworkState(uid);
965 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
966 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
967 }
968 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800969 NetworkState state = getFilteredNetworkState(networkType, uid);
970 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800971 }
972
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800973 @Override
974 public NetworkInfo getNetworkInfoForNetwork(Network network) {
975 enforceAccessPermission();
976 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700977 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800978 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
979 if (nai != null) {
980 synchronized (nai) {
981 info = new NetworkInfo(nai.networkInfo);
982 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700983 }
984 }
985 return info;
986 }
987
988 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800989 public NetworkInfo[] getAllNetworkInfo() {
990 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700991 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -0400992 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
993 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800994 NetworkInfo info = getNetworkInfo(networkType);
995 if (info != null) {
996 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700997 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800998 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700999 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001000 }
1001
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001002 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001003 public Network getNetworkForType(int networkType) {
1004 enforceAccessPermission();
1005 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001006 NetworkState state = getFilteredNetworkState(networkType, uid);
1007 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1008 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001009 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001010 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001011 }
1012
1013 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001014 public Network[] getAllNetworks() {
1015 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001016 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001017 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001018 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001019 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001020 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001021 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001022 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001023 }
1024
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001025 private NetworkCapabilities getNetworkCapabilitiesAndValidation(NetworkAgentInfo nai) {
1026 if (nai != null) {
1027 synchronized (nai) {
1028 if (nai.created) {
1029 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001030 if (nai.lastValidated) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001031 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1032 } else {
1033 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1034 }
1035 return nc;
1036 }
1037 }
1038 }
1039 return null;
1040 }
1041
1042 @Override
1043 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1044 // The basic principle is: if an app's traffic could possibly go over a
1045 // network, without the app doing anything multinetwork-specific,
1046 // (hence, by "default"), then include that network's capabilities in
1047 // the array.
1048 //
1049 // In the normal case, app traffic only goes over the system's default
1050 // network connection, so that's the only network returned.
1051 //
1052 // With a VPN in force, some app traffic may go into the VPN, and thus
1053 // over whatever underlying networks the VPN specifies, while other app
1054 // traffic may go over the system default network (e.g.: a split-tunnel
1055 // VPN, or an app disallowed by the VPN), so the set of networks
1056 // returned includes the VPN's underlying networks and the system
1057 // default.
1058 enforceAccessPermission();
1059
1060 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1061
1062 NetworkAgentInfo nai = getDefaultNetwork();
1063 NetworkCapabilities nc = getNetworkCapabilitiesAndValidation(getDefaultNetwork());
1064 if (nc != null) {
1065 result.put(nai.network, nc);
1066 }
1067
1068 if (!mLockdownEnabled) {
1069 synchronized (mVpns) {
1070 Vpn vpn = mVpns.get(userId);
1071 if (vpn != null) {
1072 Network[] networks = vpn.getUnderlyingNetworks();
1073 if (networks != null) {
1074 for (Network network : networks) {
1075 nai = getNetworkAgentInfoForNetwork(network);
1076 nc = getNetworkCapabilitiesAndValidation(nai);
1077 if (nc != null) {
1078 result.put(nai.network, nc);
1079 }
1080 }
1081 }
1082 }
1083 }
1084 }
1085
1086 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1087 out = result.values().toArray(out);
1088 return out;
1089 }
1090
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001091 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001092 public boolean isNetworkSupported(int networkType) {
1093 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001094 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001095 }
1096
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001097 /**
1098 * Return LinkProperties for the active (i.e., connected) default
1099 * network interface. It is assumed that at most one default network
1100 * is active at a time. If more than one is active, it is indeterminate
1101 * which will be returned.
1102 * @return the ip properties for the active network, or {@code null} if
1103 * none is active
1104 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001105 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001106 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001107 enforceAccessPermission();
1108 final int uid = Binder.getCallingUid();
1109 NetworkState state = getUnfilteredActiveNetworkState(uid);
1110 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001111 }
1112
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001113 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001114 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001115 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001116 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1117 if (nai != null) {
1118 synchronized (nai) {
1119 return new LinkProperties(nai.linkProperties);
1120 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001121 }
1122 return null;
1123 }
1124
Robert Greenwalt12e67352014-05-13 21:41:06 -07001125 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001126 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001127 public LinkProperties getLinkProperties(Network network) {
1128 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001129 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001130 if (nai != null) {
1131 synchronized (nai) {
1132 return new LinkProperties(nai.linkProperties);
1133 }
1134 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001135 return null;
1136 }
1137
1138 @Override
1139 public NetworkCapabilities getNetworkCapabilities(Network network) {
1140 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001141 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001142 if (nai != null) {
1143 synchronized (nai) {
Sanket Padawe7094d222015-05-01 16:55:00 -07001144 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
1145 if (nai.lastValidated) {
1146 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1147 } else {
1148 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1149 }
1150 return nc;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001151 }
1152 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001153 return null;
1154 }
1155
1156 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001157 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001158 // Require internal since we're handing out IMSI details
1159 enforceConnectivityInternalPermission();
1160
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001161 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001162 for (Network network : getAllNetworks()) {
1163 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1164 if (nai != null) {
1165 synchronized (nai) {
1166 final String subscriberId = (nai.networkMisc != null)
1167 ? nai.networkMisc.subscriberId : null;
1168 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1169 nai.networkCapabilities, network, subscriberId, null));
1170 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001171 }
1172 }
1173 return result.toArray(new NetworkState[result.size()]);
1174 }
1175
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001176 @Override
1177 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1178 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001179 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001180 final long token = Binder.clearCallingIdentity();
1181 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001182 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1183 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001184 try {
1185 return mPolicyManager.getNetworkQuotaInfo(state);
1186 } catch (RemoteException e) {
1187 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001188 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001189 return null;
1190 } finally {
1191 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001192 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001193 }
1194
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001195 @Override
1196 public boolean isActiveNetworkMetered() {
1197 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001198 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001199 final long token = Binder.clearCallingIdentity();
1200 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001201 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001202 } finally {
1203 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001204 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001205 }
1206
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001207 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1208 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1209 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001210 try {
1211 return mPolicyManager.isNetworkMetered(state);
1212 } catch (RemoteException e) {
1213 }
1214 }
1215 return false;
1216 }
1217
Jeff Sharkey216c1812012-08-05 14:29:23 -07001218 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1219 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001220 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001221 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001222 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001223 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001224 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001225
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001226 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001227 * Ensure that a network route exists to deliver traffic to the specified
1228 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001229 * @param networkType the type of the network over which traffic to the
1230 * specified host is to be routed
1231 * @param hostAddress the IP address of the host to which the route is
1232 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001233 * @return {@code true} on success, {@code false} on failure
1234 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001235 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001236 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001237 if (mProtectedNetworks.contains(networkType)) {
1238 enforceConnectivityInternalPermission();
1239 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001240
Chad Brubakerc0234532014-02-14 13:24:29 -08001241 InetAddress addr;
1242 try {
1243 addr = InetAddress.getByAddress(hostAddress);
1244 } catch (UnknownHostException e) {
1245 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1246 return false;
1247 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001248
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001249 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001250 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001251 return false;
1252 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001253
1254 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1255 if (nai == null) {
1256 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1257 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1258 } else {
1259 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1260 }
1261 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001262 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001263
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001264 DetailedState netState;
1265 synchronized (nai) {
1266 netState = nai.networkInfo.getDetailedState();
1267 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001268
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001269 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001270 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001271 log("requestRouteToHostAddress on down network "
1272 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001273 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001274 }
1275 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001276 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001277
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001278 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001279 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001280 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001281 LinkProperties lp;
1282 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001283 synchronized (nai) {
1284 lp = nai.linkProperties;
1285 netId = nai.network.netId;
1286 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001287 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001288 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1289 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001290 } finally {
1291 Binder.restoreCallingIdentity(token);
1292 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001293 }
1294
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001295 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001296 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001297 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001298 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001299 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001300 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001301 if (bestRoute.getGateway().equals(addr)) {
1302 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001303 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001304 } else {
1305 // if we will connect to this through another route, add a direct route
1306 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001307 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001308 }
1309 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001310 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001311 try {
1312 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1313 } catch (Exception e) {
1314 // never crash - catch them all
1315 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001316 return false;
1317 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001318 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001319 }
1320
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001321 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1322 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001323 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001324 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001325 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001326 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001327 }
1328
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001329 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001330 // skip update when we've already applied rules
1331 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1332 if (oldRules == uidRules) return;
1333
1334 mUidRules.put(uid, uidRules);
1335 }
1336
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001337 // TODO: notify UID when it has requested targeted updates
1338 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001339
1340 @Override
1341 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001342 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001343 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001344 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001345 }
1346
1347 synchronized (mRulesLock) {
1348 mMeteredIfaces.clear();
1349 for (String iface : meteredIfaces) {
1350 mMeteredIfaces.add(iface);
1351 }
1352 }
1353 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001354
1355 @Override
1356 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1357 // caller is NPMS, since we only register with them
1358 if (LOGD_RULES) {
1359 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1360 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001361 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001362 };
1363
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001364 private void enforceInternetPermission() {
1365 mContext.enforceCallingOrSelfPermission(
1366 android.Manifest.permission.INTERNET,
1367 "ConnectivityService");
1368 }
1369
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001370 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001371 mContext.enforceCallingOrSelfPermission(
1372 android.Manifest.permission.ACCESS_NETWORK_STATE,
1373 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001374 }
1375
1376 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001377 mContext.enforceCallingOrSelfPermission(
1378 android.Manifest.permission.CHANGE_NETWORK_STATE,
1379 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001380 }
1381
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001382 private void enforceTetherAccessPermission() {
1383 mContext.enforceCallingOrSelfPermission(
1384 android.Manifest.permission.ACCESS_NETWORK_STATE,
1385 "ConnectivityService");
1386 }
1387
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001388 private void enforceConnectivityInternalPermission() {
1389 mContext.enforceCallingOrSelfPermission(
1390 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1391 "ConnectivityService");
1392 }
1393
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001394 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001395 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001396 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001397 }
1398
1399 private void sendInetConditionBroadcast(NetworkInfo info) {
1400 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1401 }
1402
Wink Saville628b0852011-08-04 15:01:58 -07001403 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001404 if (mLockdownTracker != null) {
1405 info = mLockdownTracker.augmentNetworkInfo(info);
1406 }
1407
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001408 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001409 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001410 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001411 if (info.isFailover()) {
1412 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1413 info.setFailover(false);
1414 }
1415 if (info.getReason() != null) {
1416 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1417 }
1418 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001419 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1420 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001421 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001422 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001423 return intent;
1424 }
1425
1426 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1427 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1428 }
1429
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001430 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001431 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1432 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1433 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001434 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001435 final long ident = Binder.clearCallingIdentity();
1436 try {
1437 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1438 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1439 } finally {
1440 Binder.restoreCallingIdentity(ident);
1441 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001442 }
1443
Mike Lockwood0f79b542009-08-14 14:18:49 -04001444 private void sendStickyBroadcast(Intent intent) {
1445 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001446 if (!mSystemReady) {
1447 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001448 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001449 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001450 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001451 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001452 }
1453
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001454 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001455 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1456 final IBatteryStats bs = BatteryStatsService.getService();
1457 try {
1458 NetworkInfo ni = intent.getParcelableExtra(
1459 ConnectivityManager.EXTRA_NETWORK_INFO);
1460 bs.noteConnectivityChanged(intent.getIntExtra(
1461 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1462 ni != null ? ni.getState().toString() : "?");
1463 } catch (RemoteException e) {
1464 }
1465 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001466 try {
1467 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1468 } finally {
1469 Binder.restoreCallingIdentity(ident);
1470 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001471 }
1472 }
1473
1474 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001475 loadGlobalProxy();
1476
Mike Lockwood0f79b542009-08-14 14:18:49 -04001477 synchronized(this) {
1478 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001479 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001480 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001481 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001482 }
1483 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001484 // load the global proxy at startup
1485 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001486
1487 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1488 // for user to unlock device.
1489 if (!updateLockdownVpn()) {
1490 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1491 mContext.registerReceiver(mUserPresentReceiver, filter);
1492 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001493
1494 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001495
1496 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001497 }
1498
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001499 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1500 @Override
1501 public void onReceive(Context context, Intent intent) {
1502 // Try creating lockdown tracker, since user present usually means
1503 // unlocked keystore.
1504 if (updateLockdownVpn()) {
1505 mContext.unregisterReceiver(this);
1506 }
1507 }
1508 };
1509
Wink Savilled747cbc2013-08-07 16:22:47 -07001510 /** @hide */
1511 @Override
1512 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1513 enforceConnectivityInternalPermission();
1514 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001515// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001516 }
1517
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001518 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001519 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001520 *
1521 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001522 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001523 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001524 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1525 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001526
1527 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001528 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001529
Robert Greenwalt7b816022014-04-18 15:25:25 -07001530 if (networkAgent.networkCapabilities.hasTransport(
1531 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001532 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1533 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001534 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001535 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001536 } else if (networkAgent.networkCapabilities.hasTransport(
1537 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001538 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1539 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001540 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001541 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001542 } else {
1543 // do not track any other networks
1544 timeout = 0;
1545 }
1546
Robert Greenwalt7b816022014-04-18 15:25:25 -07001547 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001548 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001549 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001550 } catch (Exception e) {
1551 // You shall not crash!
1552 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001553 }
1554 }
1555 }
1556
1557 /**
1558 * Remove data activity tracking when network disconnects.
1559 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001560 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1561 final String iface = networkAgent.linkProperties.getInterfaceName();
1562 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001563
Robert Greenwalt7b816022014-04-18 15:25:25 -07001564 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1565 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001566 try {
1567 // the call fails silently if no idletimer setup for this interface
1568 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001569 } catch (Exception e) {
1570 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001571 }
1572 }
1573 }
1574
1575 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001576 * Reads the network specific MTU size from reources.
1577 * and set it on it's iface.
1578 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001579 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1580 final String iface = newLp.getInterfaceName();
1581 final int mtu = newLp.getMtu();
1582 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1583 if (VDBG) log("identical MTU - not setting");
1584 return;
1585 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001586
Robert Greenwalt43074032014-08-15 17:53:05 -07001587 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001588 loge("Unexpected mtu value: " + mtu + ", " + iface);
1589 return;
1590 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001591
w1997615afd812014-08-05 15:18:11 -07001592 // Cannot set MTU without interface name
1593 if (TextUtils.isEmpty(iface)) {
1594 loge("Setting MTU size with null iface.");
1595 return;
1596 }
1597
Robert Greenwalt7b816022014-04-18 15:25:25 -07001598 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001599 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001600 mNetd.setMtu(iface, mtu);
1601 } catch (Exception e) {
1602 Slog.e(TAG, "exception in setMtu()" + e);
1603 }
1604 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001605
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001606 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001607
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001608 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1609 if (isDefaultNetwork(nai) == false) {
1610 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001611 }
1612
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001613 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1614 String[] values = null;
1615 if (tcpBufferSizes != null) {
1616 values = tcpBufferSizes.split(",");
1617 }
1618
1619 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001620 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001621 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1622 values = tcpBufferSizes.split(",");
1623 }
1624
1625 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1626
1627 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001628 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001629
1630 final String prefix = "/sys/kernel/ipv4/tcp_";
1631 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1632 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1633 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1634 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1635 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1636 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1637 mCurrentTcpBufferSizes = tcpBufferSizes;
1638 } catch (IOException e) {
1639 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001640 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001641
1642 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1643 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1644 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1645 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1646 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1647 if (rwndValue != 0) {
1648 SystemProperties.set(sysctlKey, rwndValue.toString());
1649 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001650 }
1651
Mattias Falk8b47b362011-08-23 14:15:13 +02001652 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001653 /*
1654 * Tell the VMs to toss their DNS caches
1655 */
1656 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1657 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001658 /*
1659 * Connectivity events can happen before boot has completed ...
1660 */
1661 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001662 final long ident = Binder.clearCallingIdentity();
1663 try {
1664 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1665 } finally {
1666 Binder.restoreCallingIdentity(ident);
1667 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001668 }
1669
Robert Greenwalt562cc542014-05-15 18:07:26 -07001670 @Override
1671 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001672 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1673 NETWORK_RESTORE_DELAY_PROP_NAME);
1674 if(restoreDefaultNetworkDelayStr != null &&
1675 restoreDefaultNetworkDelayStr.length() != 0) {
1676 try {
1677 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1678 } catch (NumberFormatException e) {
1679 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001680 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001681 // if the system property isn't set, use the value for the apn type
1682 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1683
1684 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1685 (mNetConfigs[networkType] != null)) {
1686 ret = mNetConfigs[networkType].restoreTime;
1687 }
1688 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001689 }
1690
1691 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001692 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1693 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001694 if (mContext.checkCallingOrSelfPermission(
1695 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001696 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001697 pw.println("Permission Denial: can't dump ConnectivityService " +
1698 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1699 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001700 return;
1701 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001702
Robert Greenwalta67be032014-05-16 15:49:14 -07001703 pw.println("NetworkFactories for:");
1704 pw.increaseIndent();
1705 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1706 pw.println(nfi.name);
1707 }
1708 pw.decreaseIndent();
1709 pw.println();
1710
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001711 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1712 pw.print("Active default network: ");
1713 if (defaultNai == null) {
1714 pw.println("none");
1715 } else {
1716 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001717 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001718 pw.println();
1719
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001720 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001721 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001722 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1723 pw.println(nai.toString());
1724 pw.increaseIndent();
1725 pw.println("Requests:");
1726 pw.increaseIndent();
1727 for (int i = 0; i < nai.networkRequests.size(); i++) {
1728 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001729 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001730 pw.decreaseIndent();
1731 pw.println("Lingered:");
1732 pw.increaseIndent();
1733 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1734 pw.decreaseIndent();
1735 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001736 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001737 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001738 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001739
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001740 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001741 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001742 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1743 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001744 }
1745 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001746 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001747
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001748 pw.println("mLegacyTypeTracker:");
1749 pw.increaseIndent();
1750 mLegacyTypeTracker.dump(pw);
1751 pw.decreaseIndent();
1752 pw.println();
1753
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001754 synchronized (this) {
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001755 pw.println("NetworkTransitionWakeLock is currently " +
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001756 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1757 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1758 }
1759 pw.println();
1760
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001761 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001762
1763 if (mInetLog != null) {
1764 pw.println();
1765 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001766 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001767 for(int i = 0; i < mInetLog.size(); i++) {
1768 pw.println(mInetLog.get(i));
1769 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001770 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001771 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001772 }
1773
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001774 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001775 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001776 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001777 if (officialNai != null && officialNai.equals(nai)) return true;
1778 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001779 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001780 " - " + nai);
1781 }
1782 return false;
1783 }
1784
Paul Jensenc8b9a742014-09-30 15:37:41 -04001785 private boolean isRequest(NetworkRequest request) {
1786 return mNetworkRequests.get(request).isRequest;
1787 }
1788
Robert Greenwalt42acef32009-08-12 16:08:25 -07001789 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001790 private class NetworkStateTrackerHandler extends Handler {
1791 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001792 super(looper);
1793 }
1794
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001795 @Override
1796 public void handleMessage(Message msg) {
1797 NetworkInfo info;
1798 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001799 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001800 handleAsyncChannelHalfConnect(msg);
1801 break;
1802 }
1803 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1804 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1805 if (nai != null) nai.asyncChannel.disconnect();
1806 break;
1807 }
1808 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1809 handleAsyncChannelDisconnected(msg);
1810 break;
1811 }
1812 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1813 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1814 if (nai == null) {
1815 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1816 } else {
1817 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001818 }
1819 break;
1820 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001821 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1822 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1823 if (nai == null) {
1824 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1825 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001826 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001827 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001828 "; created=" + nai.created);
1829 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001830 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001831 synchronized (nai) {
1832 nai.linkProperties = (LinkProperties)msg.obj;
1833 }
Paul Jenseneec75412014-08-04 12:21:19 -04001834 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001835 }
1836 break;
1837 }
1838 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1839 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1840 if (nai == null) {
1841 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1842 break;
1843 }
1844 info = (NetworkInfo) msg.obj;
1845 updateNetworkInfo(nai, info);
1846 break;
1847 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001848 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1849 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1850 if (nai == null) {
1851 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1852 break;
1853 }
1854 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001855 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001856 break;
1857 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001858 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1859 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1860 if (nai == null) {
1861 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1862 break;
1863 }
1864 try {
1865 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001866 } catch (Exception e) {
1867 // Never crash!
1868 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001869 }
1870 break;
1871 }
1872 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1873 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1874 if (nai == null) {
1875 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1876 break;
1877 }
1878 try {
1879 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001880 } catch (Exception e) {
1881 // Never crash!
1882 loge("Exception in removeVpnUidRanges: " + e);
1883 }
1884 break;
1885 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001886 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1887 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1888 if (nai == null) {
1889 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1890 break;
1891 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001892 if (nai.created && !nai.networkMisc.explicitlySelected) {
1893 loge("ERROR: created network explicitly selected.");
1894 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001895 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001896 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001897 break;
1898 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001899 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001900 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001901 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001902 boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001903 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001904 if (valid) {
1905 if (DBG) log("Validated " + nai.name());
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001906 if (!nai.everValidated) {
1907 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001908 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1909 ReapUnvalidatedNetworks.REAP);
1910 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001911 sendUpdatedScoreToFactories(nai);
1912 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001913 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001914 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001915 // Let the NetworkAgent know the state of its network
1916 nai.asyncChannel.sendMessage(
1917 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1918 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1919 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001920
1921 // TODO: trigger a NetworkCapabilities update so that the dialog can know
1922 // that the network is now validated and close itself.
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001923 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001924 break;
1925 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001926 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001927 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001928 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1929 handleLingerComplete(nai);
1930 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001931 break;
1932 }
Paul Jensen869868be2014-05-15 10:33:05 -04001933 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001934 if (msg.arg1 == 0) {
1935 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1936 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04001937 NetworkAgentInfo nai = null;
1938 synchronized (mNetworkForNetId) {
1939 nai = mNetworkForNetId.get(msg.arg2);
1940 }
1941 if (nai == null) {
1942 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1943 break;
1944 }
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001945 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
1946 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04001947 }
Paul Jensen869868be2014-05-15 10:33:05 -04001948 break;
1949 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001950 }
1951 }
1952 }
1953
Paul Jensen0cc17322014-11-25 15:26:53 -05001954 // Cancel any lingering so the linger timeout doesn't teardown a network.
1955 // This should be called when a network begins satisfying a NetworkRequest.
1956 // Note: depending on what state the NetworkMonitor is in (e.g.,
1957 // if it's awaiting captive portal login, or if validation failed), this
1958 // may trigger a re-evaluation of the network.
1959 private void unlinger(NetworkAgentInfo nai) {
1960 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05001961 // If network has never been validated, it cannot have been lingered, so don't bother
1962 // needlessly triggering a re-evaluation.
1963 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05001964 nai.networkLingered.clear();
1965 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
1966 }
1967
Robert Greenwalt7b816022014-04-18 15:25:25 -07001968 private void handleAsyncChannelHalfConnect(Message msg) {
1969 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07001970 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001971 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1972 if (VDBG) log("NetworkFactory connected");
1973 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07001974 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07001975 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07001976 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07001977 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04001978 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001979 }
1980 } else {
1981 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07001982 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001983 }
1984 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
1985 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1986 if (VDBG) log("NetworkAgent connected");
1987 // A network agent has requested a connection. Establish the connection.
1988 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
1989 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
1990 } else {
1991 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07001992 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07001993 if (nai != null) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001994 synchronized (mNetworkForNetId) {
1995 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05001996 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001997 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09001998 // Just in case.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001999 mLegacyTypeTracker.remove(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002000 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002001 }
2002 }
2003 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002004
Robert Greenwalt7b816022014-04-18 15:25:25 -07002005 private void handleAsyncChannelDisconnected(Message msg) {
2006 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2007 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002008 if (DBG) {
2009 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2010 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002011 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002012 if (nai.created) {
2013 // Tell netd to clean up the configuration for this network
2014 // (routing rules, DNS, etc).
2015 try {
2016 mNetd.removeNetwork(nai.network.netId);
2017 } catch (Exception e) {
2018 loge("Exception removing network: " + e);
2019 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002020 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002021 // TODO - if we move the logic to the network agent (have them disconnect
2022 // because they lost all their requests or because their score isn't good)
2023 // then they would disconnect organically, report their new state and then
2024 // disconnect the channel.
2025 if (nai.networkInfo.isConnected()) {
2026 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2027 null, null);
2028 }
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002029 if (isDefaultNetwork(nai)) {
2030 mDefaultInetConditionPublished = 0;
2031 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002032 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002033 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002034 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002035 mNetworkAgentInfos.remove(msg.replyTo);
2036 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002037 mLegacyTypeTracker.remove(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002038 synchronized (mNetworkForNetId) {
2039 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002040 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002041 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002042 // Since we've lost the network, go through all the requests that
2043 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002044 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002045 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002046 for (int i = 0; i < nai.networkRequests.size(); i++) {
2047 NetworkRequest request = nai.networkRequests.valueAt(i);
2048 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2049 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002050 if (DBG) {
2051 log("Checking for replacement network to handle request " + request );
2052 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002053 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002054 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002055 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002056 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2057 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002058 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002059 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002060 alternative = existing;
2061 }
2062 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002063 if (alternative != null) {
2064 if (DBG) log(" found replacement in " + alternative.name());
2065 if (!toActivate.contains(alternative)) {
2066 toActivate.add(alternative);
2067 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002068 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002069 }
2070 }
2071 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2072 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002073 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002074 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002075 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002076 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002077 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002078 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2079 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002080 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002081 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302082 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2083 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002084 }
2085
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002086 // If this method proves to be too slow then we can maintain a separate
2087 // pendingIntent => NetworkRequestInfo map.
2088 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2089 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2090 Intent intent = pendingIntent.getIntent();
2091 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2092 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2093 if (existingPendingIntent != null &&
2094 existingPendingIntent.getIntent().filterEquals(intent)) {
2095 return entry.getValue();
2096 }
2097 }
2098 return null;
2099 }
2100
2101 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2102 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2103
2104 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2105 if (existingRequest != null) { // remove the existing request.
2106 if (DBG) log("Replacing " + existingRequest.request + " with "
2107 + nri.request + " because their intents matched.");
2108 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2109 }
2110 handleRegisterNetworkRequest(msg);
2111 }
2112
Robert Greenwalt9258c642014-03-26 16:47:06 -07002113 private void handleRegisterNetworkRequest(Message msg) {
2114 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002115
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002116 mNetworkRequests.put(nri.request, nri);
2117
Paul Jensen0cc17322014-11-25 15:26:53 -05002118 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2119
Robert Greenwalt9258c642014-03-26 16:47:06 -07002120 // Check for the best currently alive network that satisfies this request
2121 NetworkAgentInfo bestNetwork = null;
2122 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002123 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002124 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002125 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002126 if (!nri.isRequest) {
2127 // Not setting bestNetwork here as a listening NetworkRequest may be
2128 // satisfied by multiple Networks. Instead the request is added to
2129 // each satisfying Network and notified about each.
2130 network.addRequest(nri.request);
2131 notifyNetworkCallback(network, nri);
2132 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002133 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002134 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002135 }
2136 }
2137 }
2138 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002139 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002140 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002141 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002142 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002143 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002144 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002145 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2146 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002147 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002148
Lorenzo Colittia793a672014-07-31 23:20:17 +09002149 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002150 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002151 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002152 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002153 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002154 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002155 }
2156 }
2157 }
2158
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002159 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2160 int callingUid) {
2161 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2162 if (nri != null) {
2163 handleReleaseNetworkRequest(nri.request, callingUid);
2164 }
2165 }
2166
Paul Jensen99364842014-12-09 11:43:45 -05002167 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2168 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2169 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2170 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2171 private boolean unneeded(NetworkAgentInfo nai) {
2172 if (!nai.created || nai.isVPN()) return false;
2173 boolean unneeded = true;
2174 if (nai.everValidated) {
2175 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2176 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2177 try {
2178 if (isRequest(nr)) unneeded = false;
2179 } catch (Exception e) {
2180 loge("Request " + nr + " not found in mNetworkRequests.");
2181 loge(" it came from request list of " + nai.name());
2182 }
2183 }
2184 } else {
2185 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2186 // If this Network is already the highest scoring Network for a request, or if
2187 // there is hope for it to become one if it validated, then it is needed.
2188 if (nri.isRequest && nai.satisfies(nri.request) &&
2189 (nai.networkRequests.get(nri.request.requestId) != null ||
2190 // Note that this catches two important cases:
2191 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2192 // is currently satisfying the request. This is desirable when
2193 // cellular ends up validating but WiFi does not.
2194 // 2. Unvalidated WiFi will not be reaped when validated cellular
2195 // is currently satsifying the request. This is desirable when
2196 // WiFi ends up validating and out scoring cellular.
2197 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2198 nai.getCurrentScoreAsValidated())) {
2199 unneeded = false;
2200 break;
2201 }
2202 }
2203 }
2204 return unneeded;
2205 }
2206
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002207 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2208 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002209 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002210 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002211 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2212 return;
2213 }
2214 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002215 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002216 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002217 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002218 // Find all networks that are satisfying this request and remove the request
2219 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002220 // TODO - it's my understanding that for a request there is only a single
2221 // network satisfying it, so this loop is wasteful
2222 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002223 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2224 if (nai.networkRequests.get(nri.request.requestId) != null) {
2225 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002226 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002227 log(" Removing from current network " + nai.name() +
2228 ", leaving " + nai.networkRequests.size() +
2229 " requests.");
2230 }
Paul Jensen99364842014-12-09 11:43:45 -05002231 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002232 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002233 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002234 } else {
2235 // suspect there should only be one pass through here
2236 // but if any were kept do the check below
2237 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002238 }
2239 }
2240 }
2241
Robert Greenwalt51481852015-01-08 14:43:31 -08002242 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2243 if (nai != null) {
2244 mNetworkForRequestId.remove(nri.request.requestId);
2245 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002246 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002247 // that a network connected to serve it, even though the network was already
2248 // connected. Now that this request has gone away, we might have to pretend
2249 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002250 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002251 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2252 boolean doRemove = true;
2253 if (wasKept) {
2254 // check if any of the remaining requests for this network are for the
2255 // same legacy type - if so, don't remove the nai
2256 for (int i = 0; i < nai.networkRequests.size(); i++) {
2257 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2258 if (otherRequest.legacyType == nri.request.legacyType &&
2259 isRequest(otherRequest)) {
2260 if (DBG) log(" still have other legacy request - leaving");
2261 doRemove = false;
2262 }
2263 }
2264 }
2265
2266 if (doRemove) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002267 mLegacyTypeTracker.remove(nri.request.legacyType, nai);
2268 }
2269 }
2270
Robert Greenwalta67be032014-05-16 15:49:14 -07002271 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002272 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2273 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002274 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002275 } else {
2276 // listens don't have a singular affectedNetwork. Check all networks to see
2277 // if this listen request applies and remove it.
2278 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2279 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002280 }
2281 }
2282 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2283 }
2284 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002285
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002286 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2287 enforceConnectivityInternalPermission();
2288 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2289 accept ? 1 : 0, always ? 1: 0, network));
2290 }
2291
2292 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2293 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2294 " accept=" + accept + " always=" + always);
2295
2296 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2297 if (nai == null) {
2298 // Nothing to do.
2299 return;
2300 }
2301
2302 if (nai.everValidated) {
2303 // The network validated while the dialog box was up. Don't make any changes. There's a
2304 // TODO in the dialog code to make it go away if the network validates; once that's
2305 // implemented, taking action here will be confusing.
2306 return;
2307 }
2308
2309 if (!nai.networkMisc.explicitlySelected) {
2310 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2311 }
2312
2313 if (accept != nai.networkMisc.acceptUnvalidated) {
2314 int oldScore = nai.getCurrentScore();
2315 nai.networkMisc.acceptUnvalidated = accept;
2316 rematchAllNetworksAndRequests(nai, oldScore);
2317 sendUpdatedScoreToFactories(nai);
2318 }
2319
2320 if (always) {
2321 nai.asyncChannel.sendMessage(
2322 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2323 }
2324
2325 // TODO: should we also disconnect from the network if accept is false?
2326 }
2327
2328 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2329 mHandler.sendMessageDelayed(
2330 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2331 PROMPT_UNVALIDATED_DELAY_MS);
2332 }
2333
2334 private void handlePromptUnvalidated(Network network) {
2335 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2336
2337 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2338 // we haven't already been told to switch to it regardless of whether it validated or not.
2339 if (nai == null || nai.everValidated ||
2340 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2341 return;
2342 }
2343
2344 // TODO: What should we do if we've already switched to this network because we had no
2345 // better option? There are two obvious alternatives.
2346 //
2347 // 1. Decide that there's no point prompting because this is our only usable network.
2348 // However, because we didn't prompt, if later on a validated network comes along, we'll
2349 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2350 // unvalidated network - or b) prompt the user at that later time - bad because the user
2351 // might not understand why they are now being prompted.
2352 //
2353 // 2. Always prompt the user, even if we have no other network to use. The user could then
2354 // try to find an alternative network to join (remember, if we got here, then the user
2355 // selected this network manually). This is bad because the prompt isn't really very
2356 // useful.
2357 //
2358 // For now we do #1, but we can revisit that later.
2359 if (isDefaultNetwork(nai)) {
2360 return;
2361 }
2362
2363 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2364 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2365 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2366 intent.setClassName("com.android.settings",
2367 "com.android.settings.wifi.WifiNoInternetDialog");
2368 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2369 }
2370
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002371 private class InternalHandler extends Handler {
2372 public InternalHandler(Looper looper) {
2373 super(looper);
2374 }
2375
2376 @Override
2377 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002378 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002379 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002380 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002381 String causedBy = null;
2382 synchronized (ConnectivityService.this) {
2383 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2384 mNetTransitionWakeLock.isHeld()) {
2385 mNetTransitionWakeLock.release();
2386 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002387 } else {
2388 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002389 }
2390 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002391 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2392 log("Failed to find a new network - expiring NetTransition Wakelock");
2393 } else {
2394 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2395 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002396 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002397 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002398 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002399 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002400 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002401 break;
2402 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002403 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002404 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002405 sendStickyBroadcast(intent);
2406 break;
2407 }
Jason Monkdecd2952013-10-10 14:02:51 -04002408 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002409 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002410 break;
2411 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002412 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002413 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2414 break;
2415 }
2416 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2417 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002418 break;
2419 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002420 case EVENT_REGISTER_NETWORK_AGENT: {
2421 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2422 break;
2423 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002424 case EVENT_REGISTER_NETWORK_REQUEST:
2425 case EVENT_REGISTER_NETWORK_LISTENER: {
2426 handleRegisterNetworkRequest(msg);
2427 break;
2428 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002429 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2430 handleRegisterNetworkRequestWithIntent(msg);
2431 break;
2432 }
2433 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2434 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2435 break;
2436 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002437 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002438 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002439 break;
2440 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002441 case EVENT_SET_ACCEPT_UNVALIDATED: {
2442 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2443 break;
2444 }
2445 case EVENT_PROMPT_UNVALIDATED: {
2446 handlePromptUnvalidated((Network) msg.obj);
2447 break;
2448 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002449 case EVENT_SYSTEM_READY: {
2450 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2451 nai.networkMonitor.systemReady = true;
2452 }
2453 break;
2454 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002455 }
2456 }
2457 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002458
2459 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002460 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002461 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002462 if (isTetheringSupported()) {
2463 return mTethering.tether(iface);
2464 } else {
2465 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2466 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002467 }
2468
2469 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002470 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002471 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002472
2473 if (isTetheringSupported()) {
2474 return mTethering.untether(iface);
2475 } else {
2476 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2477 }
2478 }
2479
2480 // javadoc from interface
2481 public int getLastTetherError(String iface) {
2482 enforceTetherAccessPermission();
2483
2484 if (isTetheringSupported()) {
2485 return mTethering.getLastTetherError(iface);
2486 } else {
2487 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2488 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002489 }
2490
2491 // TODO - proper iface API for selection by property, inspection, etc
2492 public String[] getTetherableUsbRegexs() {
2493 enforceTetherAccessPermission();
2494 if (isTetheringSupported()) {
2495 return mTethering.getTetherableUsbRegexs();
2496 } else {
2497 return new String[0];
2498 }
2499 }
2500
2501 public String[] getTetherableWifiRegexs() {
2502 enforceTetherAccessPermission();
2503 if (isTetheringSupported()) {
2504 return mTethering.getTetherableWifiRegexs();
2505 } else {
2506 return new String[0];
2507 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002508 }
2509
Danica Chang6fdd0c62010-08-11 14:54:43 -07002510 public String[] getTetherableBluetoothRegexs() {
2511 enforceTetherAccessPermission();
2512 if (isTetheringSupported()) {
2513 return mTethering.getTetherableBluetoothRegexs();
2514 } else {
2515 return new String[0];
2516 }
2517 }
2518
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002519 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002520 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002521 if (isTetheringSupported()) {
2522 return mTethering.setUsbTethering(enable);
2523 } else {
2524 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2525 }
2526 }
2527
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002528 // TODO - move iface listing, queries, etc to new module
2529 // javadoc from interface
2530 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002531 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002532 return mTethering.getTetherableIfaces();
2533 }
2534
2535 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002536 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002537 return mTethering.getTetheredIfaces();
2538 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002539
Robert Greenwalt5a735062010-03-02 17:25:02 -08002540 public String[] getTetheringErroredIfaces() {
2541 enforceTetherAccessPermission();
2542 return mTethering.getErroredIfaces();
2543 }
2544
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002545 public String[] getTetheredDhcpRanges() {
2546 enforceConnectivityInternalPermission();
2547 return mTethering.getTetheredDhcpRanges();
2548 }
2549
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002550 // if ro.tether.denied = true we default to no tethering
2551 // gservices could set the secure setting to 1 though to enable it on a build where it
2552 // had previously been turned off.
2553 public boolean isTetheringSupported() {
2554 enforceTetherAccessPermission();
2555 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002556 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002557 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2558 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002559 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2560 mTethering.getTetherableWifiRegexs().length != 0 ||
2561 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2562 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002563 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002564
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002565 // Called when we lose the default network and have no replacement yet.
2566 // This will automatically be cleared after X seconds or a new default network
2567 // becomes CONNECTED, whichever happens first. The timer is started by the
2568 // first caller and not restarted by subsequent callers.
2569 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002570 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002571 synchronized (this) {
2572 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002573 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002574 mNetTransitionWakeLock.acquire();
2575 mNetTransitionWakeLockCausedBy = forWhom;
2576 }
2577 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002578 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002579 mNetTransitionWakeLockTimeout);
2580 return;
2581 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002582
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002583 // 100 percent is full good, 0 is full bad.
2584 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002585 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002586 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002587 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002588 }
2589
Paul Jensenbfd17b72015-04-07 12:43:13 -04002590 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002591 enforceAccessPermission();
2592 enforceInternetPermission();
2593
Paul Jensenbfd17b72015-04-07 12:43:13 -04002594 NetworkAgentInfo nai;
2595 if (network == null) {
2596 nai = getDefaultNetwork();
2597 } else {
2598 nai = getNetworkAgentInfoForNetwork(network);
2599 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002600 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002601 // Revalidate if the app report does not match our current validated state.
2602 if (hasConnectivity == nai.lastValidated) return;
2603 final int uid = Binder.getCallingUid();
2604 if (DBG) {
2605 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2606 ") by " + uid);
2607 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002608 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002609 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2610 // which isn't meant to work on uncreated networks.
2611 if (!nai.created) return;
2612
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002613 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002614
2615 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2616 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002617 }
2618
Paul Jensen25a217c2015-02-27 22:55:47 -05002619 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2620 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2621 enforceConnectivityInternalPermission();
2622 }
2623 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2624 if (nai == null) return;
2625 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2626 actionToken);
2627 }
2628
Paul Jensencee9b512015-05-06 07:32:40 -04002629 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002630 // this information is already available as a world read/writable jvm property
2631 // so this API change wouldn't have a benifit. It also breaks the passing
2632 // of proxy info to all the JVMs.
2633 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002634 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002635 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002636 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2637 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002638 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002639 }
2640
Paul Jensencee9b512015-05-06 07:32:40 -04002641 public ProxyInfo getProxyForNetwork(Network network) {
2642 if (network == null) return getDefaultProxy();
2643 final ProxyInfo globalProxy = getGlobalProxy();
2644 if (globalProxy != null) return globalProxy;
2645 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2646 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2647 // caller may not have.
2648 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2649 if (nai == null) return null;
2650 synchronized (nai) {
2651 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2652 if (proxyInfo == null) return null;
2653 return new ProxyInfo(proxyInfo);
2654 }
2655 }
2656
Paul Jensene0bef712014-12-10 15:12:18 -05002657 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2658 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2659 // proxy is null then there is no proxy in place).
2660 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2661 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2662 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2663 proxy = null;
2664 }
2665 return proxy;
2666 }
2667
2668 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2669 // better for determining if a new proxy broadcast is necessary:
2670 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2671 // avoid unnecessary broadcasts.
2672 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2673 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2674 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2675 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2676 // all set.
2677 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2678 a = canonicalizeProxyInfo(a);
2679 b = canonicalizeProxyInfo(b);
2680 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2681 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2682 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2683 }
2684
Jason Monk207900c2014-04-25 15:00:09 -04002685 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002686 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002687
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002688 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002689 if (proxyProperties == mGlobalProxy) return;
2690 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2691 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2692
2693 String host = "";
2694 int port = 0;
2695 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002696 String pacFileUrl = "";
2697 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002698 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002699 if (!proxyProperties.isValid()) {
2700 if (DBG)
2701 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2702 return;
2703 }
Jason Monk207900c2014-04-25 15:00:09 -04002704 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002705 host = mGlobalProxy.getHost();
2706 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002707 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002708 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002709 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002710 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002711 } else {
2712 mGlobalProxy = null;
2713 }
2714 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002715 final long token = Binder.clearCallingIdentity();
2716 try {
2717 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2718 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2719 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2720 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002721 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002722 } finally {
2723 Binder.restoreCallingIdentity(token);
2724 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002725
Jason Monkcf0f97a2014-10-02 15:39:38 -04002726 if (mGlobalProxy == null) {
2727 proxyProperties = mDefaultProxy;
2728 }
2729 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002730 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002731 }
2732
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002733 private void loadGlobalProxy() {
2734 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002735 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2736 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2737 String exclList = Settings.Global.getString(res,
2738 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002739 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2740 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002741 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002742 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002743 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002744 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002745 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002746 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002747 if (!proxyProperties.isValid()) {
2748 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2749 return;
2750 }
2751
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002752 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002753 mGlobalProxy = proxyProperties;
2754 }
2755 }
2756 }
2757
Jason Monk207900c2014-04-25 15:00:09 -04002758 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002759 // this information is already available as a world read/writable jvm property
2760 // so this API change wouldn't have a benifit. It also breaks the passing
2761 // of proxy info to all the JVMs.
2762 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002763 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002764 return mGlobalProxy;
2765 }
2766 }
2767
Jason Monk207900c2014-04-25 15:00:09 -04002768 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002769 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002770 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002771 proxy = null;
2772 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002773 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002774 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002775 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002776 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002777 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2778 return;
2779 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002780
2781 // This call could be coming from the PacManager, containing the port of the local
2782 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2783 // global (to get the correct local port), and send a broadcast.
2784 // TODO: Switch PacManager to have its own message to send back rather than
2785 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002786 if ((mGlobalProxy != null) && (proxy != null)
2787 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002788 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2789 mGlobalProxy = proxy;
2790 sendProxyBroadcast(mGlobalProxy);
2791 return;
2792 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002793 mDefaultProxy = proxy;
2794
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002795 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002796 if (!mDefaultProxyDisabled) {
2797 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002798 }
2799 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002800 }
2801
Paul Jensene0bef712014-12-10 15:12:18 -05002802 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2803 // This method gets called when any network changes proxy, but the broadcast only ever contains
2804 // the default proxy (even if it hasn't changed).
2805 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2806 // world where an app might be bound to a non-default network.
2807 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2808 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2809 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2810
2811 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2812 sendProxyBroadcast(getDefaultProxy());
2813 }
2814 }
2815
Robert Greenwalt434203a2010-10-11 16:00:27 -07002816 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002817 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2818 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002819 if (!TextUtils.isEmpty(proxy)) {
2820 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002821 if (data.length == 0) {
2822 return;
2823 }
2824
Robert Greenwalt434203a2010-10-11 16:00:27 -07002825 String proxyHost = data[0];
2826 int proxyPort = 8080;
2827 if (data.length > 1) {
2828 try {
2829 proxyPort = Integer.parseInt(data[1]);
2830 } catch (NumberFormatException e) {
2831 return;
2832 }
2833 }
Jason Monk207900c2014-04-25 15:00:09 -04002834 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002835 setGlobalProxy(p);
2836 }
2837 }
2838
Jason Monk207900c2014-04-25 15:00:09 -04002839 private void sendProxyBroadcast(ProxyInfo proxy) {
2840 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002841 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002842 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002843 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002844 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2845 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002846 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002847 final long ident = Binder.clearCallingIdentity();
2848 try {
2849 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2850 } finally {
2851 Binder.restoreCallingIdentity(ident);
2852 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002853 }
2854
2855 private static class SettingsObserver extends ContentObserver {
2856 private int mWhat;
2857 private Handler mHandler;
2858 SettingsObserver(Handler handler, int what) {
2859 super(handler);
2860 mHandler = handler;
2861 mWhat = what;
2862 }
2863
2864 void observe(Context context) {
2865 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002866 resolver.registerContentObserver(Settings.Global.getUriFor(
2867 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002868 }
2869
2870 @Override
2871 public void onChange(boolean selfChange) {
2872 mHandler.obtainMessage(mWhat).sendToTarget();
2873 }
2874 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002875
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002876 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002877 Slog.d(TAG, s);
2878 }
2879
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002880 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002881 Slog.e(TAG, s);
2882 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002883
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002884 private static <T> T checkNotNull(T value, String message) {
2885 if (value == null) {
2886 throw new NullPointerException(message);
2887 }
2888 return value;
2889 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002890
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002891 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002892 * Prepare for a VPN application.
Jeff Davidson9a1da682014-11-11 13:52:58 -08002893 * Permissions are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002894 * @hide
2895 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002896 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002897 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002898 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002899 int user = UserHandle.getUserId(Binder.getCallingUid());
2900 synchronized(mVpns) {
2901 return mVpns.get(user).prepare(oldPackage, newPackage);
2902 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002903 }
2904
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002905 /**
Jeff Davidson05542602014-08-11 14:07:27 -07002906 * Set whether the current VPN package has the ability to launch VPNs without
Jeff Davidson9a1da682014-11-11 13:52:58 -08002907 * user intervention. This method is used by system-privileged apps.
2908 * Permissions are checked in Vpn class.
Jeff Davidson05542602014-08-11 14:07:27 -07002909 * @hide
2910 */
2911 @Override
2912 public void setVpnPackageAuthorization(boolean authorized) {
2913 int user = UserHandle.getUserId(Binder.getCallingUid());
2914 synchronized(mVpns) {
2915 mVpns.get(user).setPackageAuthorization(authorized);
2916 }
2917 }
2918
2919 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002920 * Configure a TUN interface and return its file descriptor. Parameters
2921 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002922 * and not available in ConnectivityManager. Permissions are checked in
2923 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002924 * @hide
2925 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002926 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002927 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002928 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002929 int user = UserHandle.getUserId(Binder.getCallingUid());
2930 synchronized(mVpns) {
2931 return mVpns.get(user).establish(config);
2932 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002933 }
2934
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002935 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07002936 * Start legacy VPN, controlling native daemons as needed. Creates a
2937 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002938 */
2939 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07002940 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002941 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07002942 final LinkProperties egress = getActiveLinkProperties();
2943 if (egress == null) {
2944 throw new IllegalStateException("Missing active network connection");
2945 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002946 int user = UserHandle.getUserId(Binder.getCallingUid());
2947 synchronized(mVpns) {
2948 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2949 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002950 }
2951
2952 /**
2953 * Return the information of the ongoing legacy VPN. This method is used
2954 * by VpnSettings and not available in ConnectivityManager. Permissions
2955 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002956 */
2957 @Override
2958 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002959 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002960 int user = UserHandle.getUserId(Binder.getCallingUid());
2961 synchronized(mVpns) {
2962 return mVpns.get(user).getLegacyVpnInfo();
2963 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002964 }
2965
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002966 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08002967 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
2968 * and not available in ConnectivityManager.
2969 */
2970 @Override
2971 public VpnInfo[] getAllVpnInfo() {
2972 enforceConnectivityInternalPermission();
2973 if (mLockdownEnabled) {
2974 return new VpnInfo[0];
2975 }
2976
2977 synchronized(mVpns) {
2978 List<VpnInfo> infoList = new ArrayList<>();
2979 for (int i = 0; i < mVpns.size(); i++) {
2980 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
2981 if (info != null) {
2982 infoList.add(info);
2983 }
2984 }
2985 return infoList.toArray(new VpnInfo[infoList.size()]);
2986 }
2987 }
2988
2989 /**
2990 * @return VPN information for accounting, or null if we can't retrieve all required
2991 * information, e.g primary underlying iface.
2992 */
2993 @Nullable
2994 private VpnInfo createVpnInfo(Vpn vpn) {
2995 VpnInfo info = vpn.getVpnInfo();
2996 if (info == null) {
2997 return null;
2998 }
2999 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3000 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3001 // the underlyingNetworks list.
3002 if (underlyingNetworks == null) {
3003 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3004 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3005 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3006 }
3007 } else if (underlyingNetworks.length > 0) {
3008 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3009 if (linkProperties != null) {
3010 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3011 }
3012 }
3013 return info.primaryUnderlyingIface == null ? null : info;
3014 }
3015
3016 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003017 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
3018 * not available in ConnectivityManager.
3019 * Permissions are checked in Vpn class.
3020 * @hide
3021 */
3022 @Override
3023 public VpnConfig getVpnConfig() {
3024 int user = UserHandle.getUserId(Binder.getCallingUid());
3025 synchronized(mVpns) {
3026 return mVpns.get(user).getVpnConfig();
3027 }
3028 }
3029
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003030 @Override
3031 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003032 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3033 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3034 return false;
3035 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003036
3037 // Tear down existing lockdown if profile was removed
3038 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3039 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003040 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003041 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3042 return false;
3043 }
3044
3045 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3046 final VpnProfile profile = VpnProfile.decode(
3047 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003048 int user = UserHandle.getUserId(Binder.getCallingUid());
3049 synchronized(mVpns) {
3050 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3051 profile));
3052 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003053 } else {
3054 setLockdownTracker(null);
3055 }
3056
3057 return true;
3058 }
3059
3060 /**
3061 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3062 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3063 */
3064 private void setLockdownTracker(LockdownVpnTracker tracker) {
3065 // Shutdown any existing tracker
3066 final LockdownVpnTracker existing = mLockdownTracker;
3067 mLockdownTracker = null;
3068 if (existing != null) {
3069 existing.shutdown();
3070 }
3071
3072 try {
3073 if (tracker != null) {
3074 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003075 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003076 mLockdownTracker = tracker;
3077 mLockdownTracker.init();
3078 } else {
3079 mNetd.setFirewallEnabled(false);
3080 }
3081 } catch (RemoteException e) {
3082 // ignored; NMS lives inside system_server
3083 }
3084 }
3085
3086 private void throwIfLockdownEnabled() {
3087 if (mLockdownEnabled) {
3088 throw new IllegalStateException("Unavailable in lockdown mode");
3089 }
3090 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003091
Wink Savilleab9321d2013-06-29 21:10:57 -07003092 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003093 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003094 // TODO: Remove? Any reason to trigger a provisioning check?
3095 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003096 }
3097
3098 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3099 private volatile boolean mIsNotificationVisible = false;
3100
Paul Jensen89e0f092014-09-15 15:59:36 -04003101 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003102 if (DBG) {
3103 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003104 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003105 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003106 Intent intent = new Intent(action);
3107 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003108 // Concatenate the range of types onto the range of NetIDs.
3109 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003110 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003111 }
3112
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003113 /**
3114 * Show or hide network provisioning notificaitons.
3115 *
3116 * @param id an identifier that uniquely identifies this notification. This must match
3117 * between show and hide calls. We use the NetID value but for legacy callers
3118 * we concatenate the range of types with the range of NetIDs.
3119 */
3120 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003121 String extraInfo, PendingIntent intent) {
3122 if (DBG) {
3123 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3124 networkType + " extraInfo=" + extraInfo);
3125 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003126
3127 Resources r = Resources.getSystem();
3128 NotificationManager notificationManager = (NotificationManager) mContext
3129 .getSystemService(Context.NOTIFICATION_SERVICE);
3130
3131 if (visible) {
3132 CharSequence title;
3133 CharSequence details;
3134 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003135 Notification notification = new Notification();
3136 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003137 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003138 title = r.getString(R.string.wifi_available_sign_in, 0);
3139 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003140 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003141 icon = R.drawable.stat_notify_wifi_in_range;
3142 break;
3143 case ConnectivityManager.TYPE_MOBILE:
3144 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003145 title = r.getString(R.string.network_available_sign_in, 0);
3146 // TODO: Change this to pull from NetworkInfo once a printable
3147 // name has been added to it
3148 details = mTelephonyManager.getNetworkOperatorName();
3149 icon = R.drawable.stat_notify_rssi_in_range;
3150 break;
3151 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003152 title = r.getString(R.string.network_available_sign_in, 0);
3153 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003154 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003155 icon = R.drawable.stat_notify_rssi_in_range;
3156 break;
3157 }
3158
Wink Savilleab9321d2013-06-29 21:10:57 -07003159 notification.when = 0;
3160 notification.icon = icon;
3161 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003162 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003163 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003164 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003165 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003166 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003167
Wink Saville948282b2013-08-29 08:55:16 -07003168 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003169 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003170 } catch (NullPointerException npe) {
3171 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3172 npe.printStackTrace();
3173 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003174 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003175 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003176 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003177 } catch (NullPointerException npe) {
3178 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3179 npe.printStackTrace();
3180 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003181 }
Wink Saville948282b2013-08-29 08:55:16 -07003182 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003183 }
3184
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003185 /** Location to an updatable file listing carrier provisioning urls.
3186 * An example:
3187 *
3188 * <?xml version="1.0" encoding="utf-8"?>
3189 * <provisioningUrls>
3190 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3191 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3192 * </provisioningUrls>
3193 */
3194 private static final String PROVISIONING_URL_PATH =
3195 "/data/misc/radio/provisioning_urls.xml";
3196 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003197
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003198 /** XML tag for root element. */
3199 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3200 /** XML tag for individual url */
3201 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3202 /** XML tag for redirected url */
3203 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3204 /** XML attribute for mcc */
3205 private static final String ATTR_MCC = "mcc";
3206 /** XML attribute for mnc */
3207 private static final String ATTR_MNC = "mnc";
3208
3209 private static final int REDIRECTED_PROVISIONING = 1;
3210 private static final int PROVISIONING = 2;
3211
3212 private String getProvisioningUrlBaseFromFile(int type) {
3213 FileReader fileReader = null;
3214 XmlPullParser parser = null;
3215 Configuration config = mContext.getResources().getConfiguration();
3216 String tagType;
3217
3218 switch (type) {
3219 case PROVISIONING:
3220 tagType = TAG_PROVISIONING_URL;
3221 break;
3222 case REDIRECTED_PROVISIONING:
3223 tagType = TAG_REDIRECTED_URL;
3224 break;
3225 default:
3226 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3227 type);
3228 }
3229
3230 try {
3231 fileReader = new FileReader(mProvisioningUrlFile);
3232 parser = Xml.newPullParser();
3233 parser.setInput(fileReader);
3234 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3235
3236 while (true) {
3237 XmlUtils.nextElement(parser);
3238
3239 String element = parser.getName();
3240 if (element == null) break;
3241
3242 if (element.equals(tagType)) {
3243 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3244 try {
3245 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3246 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3247 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3248 parser.next();
3249 if (parser.getEventType() == XmlPullParser.TEXT) {
3250 return parser.getText();
3251 }
3252 }
3253 }
3254 } catch (NumberFormatException e) {
3255 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3256 }
3257 }
3258 }
3259 return null;
3260 } catch (FileNotFoundException e) {
3261 loge("Carrier Provisioning Urls file not found");
3262 } catch (XmlPullParserException e) {
3263 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3264 } catch (IOException e) {
3265 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3266 } finally {
3267 if (fileReader != null) {
3268 try {
3269 fileReader.close();
3270 } catch (IOException e) {}
3271 }
3272 }
3273 return null;
3274 }
3275
Wink Saville42d4f082013-07-20 20:31:59 -07003276 @Override
3277 public String getMobileRedirectedProvisioningUrl() {
3278 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003279 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3280 if (TextUtils.isEmpty(url)) {
3281 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3282 }
3283 return url;
3284 }
3285
Wink Saville42d4f082013-07-20 20:31:59 -07003286 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003287 public String getMobileProvisioningUrl() {
3288 enforceConnectivityInternalPermission();
3289 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3290 if (TextUtils.isEmpty(url)) {
3291 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003292 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003293 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003294 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003295 }
Wink Saville8cf35602013-07-10 23:00:07 -07003296 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003297 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003298 String phoneNumber = mTelephonyManager.getLine1Number();
3299 if (TextUtils.isEmpty(phoneNumber)) {
3300 phoneNumber = "0000000000";
3301 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003302 url = String.format(url,
3303 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3304 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003305 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003306 }
3307
Wink Savilleab9321d2013-06-29 21:10:57 -07003308 return url;
3309 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003310
Wink Saville948282b2013-08-29 08:55:16 -07003311 @Override
3312 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003313 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003314 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003315 final long ident = Binder.clearCallingIdentity();
3316 try {
3317 setProvNotificationVisible(visible, networkType, action);
3318 } finally {
3319 Binder.restoreCallingIdentity(ident);
3320 }
Wink Saville948282b2013-08-29 08:55:16 -07003321 }
Wink Saville7788c612013-08-29 14:57:08 -07003322
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003323 @Override
3324 public void setAirplaneMode(boolean enable) {
3325 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003326 final long ident = Binder.clearCallingIdentity();
3327 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003328 final ContentResolver cr = mContext.getContentResolver();
3329 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3330 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3331 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003332 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003333 } finally {
3334 Binder.restoreCallingIdentity(ident);
3335 }
3336 }
3337
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003338 private void onUserStart(int userId) {
3339 synchronized(mVpns) {
3340 Vpn userVpn = mVpns.get(userId);
3341 if (userVpn != null) {
3342 loge("Starting user already has a VPN");
3343 return;
3344 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003345 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003346 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003347 }
3348 }
3349
3350 private void onUserStop(int userId) {
3351 synchronized(mVpns) {
3352 Vpn userVpn = mVpns.get(userId);
3353 if (userVpn == null) {
3354 loge("Stopping user has no VPN");
3355 return;
3356 }
3357 mVpns.delete(userId);
3358 }
3359 }
3360
3361 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3362 @Override
3363 public void onReceive(Context context, Intent intent) {
3364 final String action = intent.getAction();
3365 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3366 if (userId == UserHandle.USER_NULL) return;
3367
3368 if (Intent.ACTION_USER_STARTING.equals(action)) {
3369 onUserStart(userId);
3370 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3371 onUserStop(userId);
3372 }
3373 }
3374 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003375
Robert Greenwalta67be032014-05-16 15:49:14 -07003376 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3377 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003378 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3379 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003380
Robert Greenwalta67be032014-05-16 15:49:14 -07003381 private static class NetworkFactoryInfo {
3382 public final String name;
3383 public final Messenger messenger;
3384 public final AsyncChannel asyncChannel;
3385
3386 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3387 this.name = name;
3388 this.messenger = messenger;
3389 this.asyncChannel = asyncChannel;
3390 }
3391 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003392
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003393 /**
3394 * Tracks info about the requester.
3395 * Also used to notice when the calling process dies so we can self-expire
3396 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003397 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3398 static final boolean REQUEST = true;
3399 static final boolean LISTEN = false;
3400
3401 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003402 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003403 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003404 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003405 final int mPid;
3406 final int mUid;
3407 final Messenger messenger;
3408 final boolean isRequest;
3409
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003410 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3411 request = r;
3412 mPendingIntent = pi;
3413 messenger = null;
3414 mBinder = null;
3415 mPid = getCallingPid();
3416 mUid = getCallingUid();
3417 this.isRequest = isRequest;
3418 }
3419
Robert Greenwalt9258c642014-03-26 16:47:06 -07003420 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3421 super();
3422 messenger = m;
3423 request = r;
3424 mBinder = binder;
3425 mPid = getCallingPid();
3426 mUid = getCallingUid();
3427 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003428 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003429
3430 try {
3431 mBinder.linkToDeath(this, 0);
3432 } catch (RemoteException e) {
3433 binderDied();
3434 }
3435 }
3436
3437 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003438 if (mBinder != null) {
3439 mBinder.unlinkToDeath(this, 0);
3440 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003441 }
3442
3443 public void binderDied() {
3444 log("ConnectivityService NetworkRequestInfo binderDied(" +
3445 request + ", " + mBinder + ")");
3446 releaseNetworkRequest(request);
3447 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003448
3449 public String toString() {
3450 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003451 mPid + " for " + request +
3452 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003453 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003454 }
3455
3456 @Override
3457 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003458 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003459 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003460 enforceNetworkRequestPermissions(networkCapabilities);
3461 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003462
Robert Greenwalt6078b502014-06-11 16:05:07 -07003463 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003464 throw new IllegalArgumentException("Bad timeout specified");
3465 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003466
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003467 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3468 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003469 if (DBG) log("requestNetwork for " + networkRequest);
3470 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3471 NetworkRequestInfo.REQUEST);
3472
3473 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003474 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003475 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003476 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003477 }
3478 return networkRequest;
3479 }
3480
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003481 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3482 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3483 == false) {
3484 enforceConnectivityInternalPermission();
3485 } else {
3486 enforceChangePermission();
3487 }
3488 }
3489
fenglub15e72b2015-03-20 11:29:56 -07003490 @Override
fengludb571472015-04-21 17:12:05 -07003491 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003492 enforceAccessPermission();
3493 NetworkAgentInfo nai = null;
3494 if (network == null) {
3495 return false;
3496 }
3497 synchronized (mNetworkForNetId) {
3498 nai = mNetworkForNetId.get(network.netId);
3499 }
3500 if (nai != null) {
3501 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3502 return true;
3503 }
3504 return false;
3505 }
3506
3507
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003508 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3509 // if UID is restricted, don't allow them to bring up metered APNs
3510 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
3511 == false) {
3512 final int uidRules;
3513 final int uid = Binder.getCallingUid();
3514 synchronized(mRulesLock) {
3515 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3516 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003517 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003518 // we could silently fail or we can filter the available nets to only give
3519 // them those they have access to. Chose the more useful
3520 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3521 }
3522 }
3523 }
3524
Robert Greenwalt9258c642014-03-26 16:47:06 -07003525 @Override
3526 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3527 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003528 checkNotNull(operation, "PendingIntent cannot be null.");
3529 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3530 enforceNetworkRequestPermissions(networkCapabilities);
3531 enforceMeteredApnPolicy(networkCapabilities);
3532
3533 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3534 nextNetworkRequestId());
3535 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3536 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3537 NetworkRequestInfo.REQUEST);
3538 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3539 nri));
3540 return networkRequest;
3541 }
3542
Jeremy Joslin79294842014-12-03 17:15:28 -08003543 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3544 mHandler.sendMessageDelayed(
3545 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3546 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3547 }
3548
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003549 @Override
3550 public void releasePendingNetworkRequest(PendingIntent operation) {
3551 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3552 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003553 }
3554
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003555 // In order to implement the compatibility measure for pre-M apps that call
3556 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3557 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3558 // This ensures it has permission to do so.
3559 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3560 if (nc == null) {
3561 return false;
3562 }
3563 int[] transportTypes = nc.getTransportTypes();
3564 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3565 return false;
3566 }
3567 try {
3568 mContext.enforceCallingOrSelfPermission(
3569 android.Manifest.permission.ACCESS_WIFI_STATE,
3570 "ConnectivityService");
3571 } catch (SecurityException e) {
3572 return false;
3573 }
3574 return true;
3575 }
3576
Robert Greenwalt9258c642014-03-26 16:47:06 -07003577 @Override
3578 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3579 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003580 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3581 enforceAccessPermission();
3582 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003583
3584 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003585 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003586 if (DBG) log("listenForNetwork for " + networkRequest);
3587 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3588 NetworkRequestInfo.LISTEN);
3589
3590 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3591 return networkRequest;
3592 }
3593
3594 @Override
3595 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3596 PendingIntent operation) {
3597 }
3598
3599 @Override
3600 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003601 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3602 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003603 }
3604
3605 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003606 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003607 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003608 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3609 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003610 }
3611
Robert Greenwalta67be032014-05-16 15:49:14 -07003612 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003613 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003614 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3615 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3616 }
3617
3618 @Override
3619 public void unregisterNetworkFactory(Messenger messenger) {
3620 enforceConnectivityInternalPermission();
3621 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3622 }
3623
3624 private void handleUnregisterNetworkFactory(Messenger messenger) {
3625 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3626 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003627 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003628 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003629 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003630 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003631 }
3632
Robert Greenwalt7b816022014-04-18 15:25:25 -07003633 /**
3634 * NetworkAgentInfo supporting a request by requestId.
3635 * These have already been vetted (their Capabilities satisfy the request)
3636 * and the are the highest scored network available.
3637 * the are keyed off the Requests requestId.
3638 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003639 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003640 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3641 new SparseArray<NetworkAgentInfo>();
3642
Paul Jensen31a94f42015-02-13 14:18:39 -05003643 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3644 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003645 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3646 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003647 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3648 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3649 // there may not be a strict 1:1 correlation between the two.
3650 @GuardedBy("mNetworkForNetId")
3651 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003652
Robert Greenwalt7b816022014-04-18 15:25:25 -07003653 // NetworkAgentInfo keyed off its connecting messenger
3654 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003655 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003656 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3657 new HashMap<Messenger, NetworkAgentInfo>();
3658
Paul Jensen2c311d62014-11-17 12:34:51 -05003659 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003660 private final NetworkRequest mDefaultRequest;
3661
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003662 private NetworkAgentInfo getDefaultNetwork() {
3663 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3664 }
3665
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003666 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003667 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003668 }
3669
Paul Jensen31a94f42015-02-13 14:18:39 -05003670 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003671 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003672 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003673 enforceConnectivityInternalPermission();
3674
Paul Jensen2c311d62014-11-17 12:34:51 -05003675 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3676 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003677 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003678 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3679 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3680 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003681 synchronized (this) {
3682 nai.networkMonitor.systemReady = mSystemReady;
3683 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003684 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003685 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003686 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003687 }
3688
3689 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3690 if (VDBG) log("Got NetworkAgent Messenger");
3691 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003692 synchronized (mNetworkForNetId) {
3693 mNetworkForNetId.put(na.network.netId, na);
3694 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003695 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3696 NetworkInfo networkInfo = na.networkInfo;
3697 na.networkInfo = null;
3698 updateNetworkInfo(na, networkInfo);
3699 }
3700
3701 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3702 LinkProperties newLp = networkAgent.linkProperties;
3703 int netId = networkAgent.network.netId;
3704
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003705 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3706 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003707 if (networkAgent.clatd != null) {
3708 networkAgent.clatd.fixupLinkProperties(oldLp);
3709 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003710
Paul Jensen992f2522014-04-28 10:33:11 -04003711 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003712 updateMtu(newLp, oldLp);
3713 // TODO - figure out what to do for clat
3714// for (LinkProperties lp : newLp.getStackedLinks()) {
3715// updateMtu(lp, null);
3716// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003717 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003718
3719 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3720 // For now, use it only when the network has Internet access. http://b/18327075
3721 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3722 NetworkCapabilities.NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003723 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003724 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3725
Paul Jensen3b759822014-05-13 11:44:01 -04003726 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003727 if (isDefaultNetwork(networkAgent)) {
3728 handleApplyDefaultProxy(newLp.getHttpProxy());
3729 } else {
3730 updateProxy(newLp, oldLp, networkAgent);
3731 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003732 // TODO - move this check to cover the whole function
3733 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003734 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003735 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3736 }
Paul Jensen3b759822014-05-13 11:44:01 -04003737 }
3738
Lorenzo Colitti95439462014-10-09 13:44:48 +09003739 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3740 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3741 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003742
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003743 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003744 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3745 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003746 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003747 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003748 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003749 }
Paul Jensen992f2522014-04-28 10:33:11 -04003750
3751 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3752 CompareResult<String> interfaceDiff = new CompareResult<String>();
3753 if (oldLp != null) {
3754 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3755 } else if (newLp != null) {
3756 interfaceDiff.added = newLp.getAllInterfaceNames();
3757 }
3758 for (String iface : interfaceDiff.added) {
3759 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003760 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003761 mNetd.addInterfaceToNetwork(iface, netId);
3762 } catch (Exception e) {
3763 loge("Exception adding interface: " + e);
3764 }
3765 }
3766 for (String iface : interfaceDiff.removed) {
3767 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003768 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003769 mNetd.removeInterfaceFromNetwork(iface, netId);
3770 } catch (Exception e) {
3771 loge("Exception removing interface: " + e);
3772 }
3773 }
3774 }
3775
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003776 /**
3777 * Have netd update routes from oldLp to newLp.
3778 * @return true if routes changed between oldLp and newLp
3779 */
3780 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003781 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3782 if (oldLp != null) {
3783 routeDiff = oldLp.compareAllRoutes(newLp);
3784 } else if (newLp != null) {
3785 routeDiff.added = newLp.getAllRoutes();
3786 }
3787
3788 // add routes before removing old in case it helps with continuous connectivity
3789
3790 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3791 for (RouteInfo route : routeDiff.added) {
3792 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003793 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003794 try {
3795 mNetd.addRoute(netId, route);
3796 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003797 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3798 loge("Exception in addRoute for non-gateway: " + e);
3799 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003800 }
3801 }
3802 for (RouteInfo route : routeDiff.added) {
3803 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003804 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003805 try {
3806 mNetd.addRoute(netId, route);
3807 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003808 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3809 loge("Exception in addRoute for gateway: " + e);
3810 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003811 }
3812 }
3813
3814 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003815 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003816 try {
3817 mNetd.removeRoute(netId, route);
3818 } catch (Exception e) {
3819 loge("Exception in removeRoute: " + e);
3820 }
3821 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003822 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003823 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003824 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3825 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003826 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003827 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003828 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003829 dnses = new ArrayList();
3830 dnses.add(mDefaultDns);
3831 if (DBG) {
3832 loge("no dns provided for netId " + netId + ", so using defaults");
3833 }
3834 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003835 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003836 try {
3837 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3838 newLp.getDomains());
3839 } catch (Exception e) {
3840 loge("Exception in setDnsServersForNetwork: " + e);
3841 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003842 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3843 if (defaultNai != null && defaultNai.network.netId == netId) {
3844 setDefaultDnsSystemProperties(dnses);
3845 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003846 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003847 } else if (flush) {
3848 try {
3849 mNetd.flushNetworkDnsCache(netId);
3850 } catch (Exception e) {
3851 loge("Exception in flushNetworkDnsCache: " + e);
3852 }
3853 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003854 }
3855 }
3856
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003857 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3858 int last = 0;
3859 for (InetAddress dns : dnses) {
3860 ++last;
3861 String key = "net.dns" + last;
3862 String value = dns.getHostAddress();
3863 SystemProperties.set(key, value);
3864 }
3865 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3866 String key = "net.dns" + i;
3867 SystemProperties.set(key, "");
3868 }
3869 mNumDnsEntries = last;
3870 }
3871
Robert Greenwalt7b816022014-04-18 15:25:25 -07003872 private void updateCapabilities(NetworkAgentInfo networkAgent,
3873 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003874 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3875 synchronized (networkAgent) {
3876 networkAgent.networkCapabilities = networkCapabilities;
3877 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003878 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003879 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003880 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003881 }
3882
Paul Jensenc8b9a742014-09-30 15:37:41 -04003883 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3884 for (int i = 0; i < nai.networkRequests.size(); i++) {
3885 NetworkRequest nr = nai.networkRequests.valueAt(i);
3886 // Don't send listening requests to factories. b/17393458
3887 if (!isRequest(nr)) continue;
3888 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3889 }
3890 }
3891
Robert Greenwalt7b816022014-04-18 15:25:25 -07003892 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3893 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07003894 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07003895 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3896 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003897 }
3898 }
3899
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003900 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
3901 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08003902 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003903 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08003904 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
3905 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08003906 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003907 sendIntent(nri.mPendingIntent, intent);
3908 }
3909 // else not handled
3910 }
3911
3912 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
3913 mPendingIntentWakeLock.acquire();
3914 try {
3915 if (DBG) log("Sending " + pendingIntent);
3916 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
3917 } catch (PendingIntent.CanceledException e) {
3918 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
3919 mPendingIntentWakeLock.release();
3920 releasePendingNetworkRequest(pendingIntent);
3921 }
3922 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
3923 }
3924
3925 @Override
3926 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
3927 String resultData, Bundle resultExtras) {
3928 if (DBG) log("Finished sending " + pendingIntent);
3929 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08003930 // Release with a delay so the receiving client has an opportunity to put in its
3931 // own request.
3932 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003933 }
3934
Robert Greenwalt9258c642014-03-26 16:47:06 -07003935 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003936 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003937 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003938 Bundle bundle = new Bundle();
3939 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
3940 new NetworkRequest(nri.request));
3941 Message msg = Message.obtain();
3942 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
3943 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
3944 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
3945 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003946 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003947 case ConnectivityManager.CALLBACK_LOSING: {
3948 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
3949 break;
3950 }
3951 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
3952 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
3953 new NetworkCapabilities(networkAgent.networkCapabilities));
3954 break;
3955 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003956 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003957 bundle.putParcelable(LinkProperties.class.getSimpleName(),
3958 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003959 break;
3960 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003961 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003962 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003963 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003964 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003965 if (VDBG) {
3966 log("sending notification " + notifyTypeToName(notificationType) +
3967 " for " + nri.request);
3968 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003969 nri.messenger.send(msg);
3970 } catch (RemoteException e) {
3971 // may occur naturally in the race of binder death.
3972 loge("RemoteException caught trying to send a callback msg for " + nri.request);
3973 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003974 }
3975
Paul Jensenc8b9a742014-09-30 15:37:41 -04003976 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
3977 for (int i = 0; i < nai.networkRequests.size(); i++) {
3978 NetworkRequest nr = nai.networkRequests.valueAt(i);
3979 // Ignore listening requests.
3980 if (!isRequest(nr)) continue;
3981 loge("Dead network still had at least " + nr);
3982 break;
3983 }
3984 nai.asyncChannel.disconnect();
3985 }
3986
Robert Greenwalt7b816022014-04-18 15:25:25 -07003987 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
3988 if (oldNetwork == null) {
3989 loge("Unknown NetworkAgentInfo in handleLingerComplete");
3990 return;
3991 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04003992 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
3993 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003994 }
3995
Paul Jensen27b02b72014-07-14 12:03:33 -04003996 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003997 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04003998 setupDataActivityTracking(newNetwork);
3999 try {
4000 mNetd.setDefaultNetId(newNetwork.network.netId);
4001 } catch (Exception e) {
4002 loge("Exception setting default network :" + e);
4003 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004004 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004005 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004006 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004007 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004008 }
4009
Paul Jensen2161a8e2014-09-11 11:00:39 -04004010 // Handles a network appearing or improving its score.
4011 //
4012 // - Evaluates all current NetworkRequests that can be
4013 // satisfied by newNetwork, and reassigns to newNetwork
4014 // any such requests for which newNetwork is the best.
4015 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004016 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004017 // needed. A network is needed if it is the best network for
4018 // one or more NetworkRequests, or if it is a VPN.
4019 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004020 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004021 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4022 //
4023 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4024 // networks that have no chance (i.e. even if validated)
4025 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004026 //
4027 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4028 // it does not remove NetworkRequests that other Networks could better satisfy.
4029 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4030 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4031 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004032 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004033 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004034 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004035 // torn down if unneeded.
4036 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4037 // performed to tear down unvalidated networks that have no chance (i.e. even if
4038 // validated) of becoming the highest scoring network.
4039 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4040 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004041 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004042 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004043 loge("ERROR: nascent network not validated.");
4044 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004045 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004046 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004047 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004048 if (DBG) log("rematching " + newNetwork.name());
4049 // Find and migrate to this Network any NetworkRequests for
4050 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004051 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004052 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004053 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004054 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4055 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004056 if (DBG) {
4057 log("Network " + newNetwork.name() + " was already satisfying" +
4058 " request " + nri.request.requestId + ". No change.");
4059 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004060 keep = true;
4061 continue;
4062 }
4063
4064 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004065 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004066 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004067 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004068 // This is not a request, it's a callback listener.
4069 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004070 newNetwork.addRequest(nri.request);
4071 continue;
4072 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004073
Robert Greenwalt7b816022014-04-18 15:25:25 -07004074 // next check if it's better than any current network we're using for
4075 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004076 if (VDBG) {
4077 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004078 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4079 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004080 }
4081 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004082 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004083 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004084 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004085 currentNetwork.networkRequests.remove(nri.request.requestId);
4086 currentNetwork.networkLingered.add(nri.request);
4087 affectedNetworks.add(currentNetwork);
4088 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004089 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004090 }
Paul Jensen573a0352015-01-08 10:49:34 -05004091 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004092 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004093 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004094 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004095 // Tell NetworkFactories about the new score, so they can stop
4096 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004097 // TODO - this could get expensive if we have alot of requests for this
4098 // network. Think about if there is a way to reduce this. Push
4099 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004100 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004101 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004102 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004103 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004104 }
4105 }
4106 }
4107 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004108 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004109 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004110 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004111 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4112 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4113 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004114 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004115 }
4116 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004117 if (keep) {
4118 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004119 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004120 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004121 synchronized (ConnectivityService.this) {
4122 // have a new default network, release the transition wakelock in
4123 // a second if it's held. The second pause is to allow apps
4124 // to reconnect over the new network
4125 if (mNetTransitionWakeLock.isHeld()) {
4126 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4127 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4128 mNetTransitionWakeLockSerialNumber, 0),
4129 1000);
4130 }
4131 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004132 }
4133
4134 // do this after the default net is switched, but
4135 // before LegacyTypeTracker sends legacy broadcasts
4136 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4137
4138 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004139 // Maintain the illusion: since the legacy API only
4140 // understands one network at a time, we must pretend
4141 // that the current default network disconnected before
4142 // the new one connected.
4143 if (oldDefaultNetwork != null) {
4144 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4145 oldDefaultNetwork);
4146 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004147 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004148 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4149 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004150 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004151
4152 // Notify battery stats service about this network, both the normal
4153 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004154 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004155 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004156 final IBatteryStats bs = BatteryStatsService.getService();
4157 final int type = newNetwork.networkInfo.getType();
4158
4159 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4160 bs.noteNetworkInterfaceType(baseIface, type);
4161 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4162 final String stackedIface = stacked.getInterfaceName();
4163 bs.noteNetworkInterfaceType(stackedIface, type);
4164 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4165 }
4166 } catch (RemoteException ignored) {
4167 }
4168
Robert Greenwalt152ed372014-12-17 17:19:53 -08004169 // This has to happen after the notifyNetworkCallbacks as that tickles each
4170 // ConnectivityManager instance so that legacy requests correctly bind dns
4171 // requests to this network. The legacy users are listening for this bcast
4172 // and will generally do a dns request so they can ensureRouteToHost and if
4173 // they do that before the callbacks happen they'll use the default network.
4174 //
4175 // TODO: Is there still a race here? We send the broadcast
4176 // after sending the callback, but if the app can receive the
4177 // broadcast before the callback, it might still break.
4178 //
4179 // This *does* introduce a race where if the user uses the new api
4180 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4181 // they may get old info. Reverse this after the old startUsing api is removed.
4182 // This is on top of the multiple intent sequencing referenced in the todo above.
4183 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4184 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4185 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4186 // legacy type tracker filters out repeat adds
4187 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4188 }
4189 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004190
4191 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4192 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4193 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4194 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4195 if (newNetwork.isVPN()) {
4196 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4197 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004198 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004199 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004200 // validated (and get evaluated against peers, one losing here), or get reaped (see
4201 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4202 // network. Networks that have been up for a while and are validated should be torn
4203 // down via the lingering process so communication on that network is given time to
4204 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004205 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004206 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004207 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004208 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4209 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004210 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004211 if (DBG) log("Reaping " + nai.name());
4212 teardownUnneededNetwork(nai);
4213 }
4214 }
4215 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004216 }
4217
Paul Jensen2161a8e2014-09-11 11:00:39 -04004218 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4219 // being disconnected.
4220 // If only one Network's score or capabilities have been modified since the last time
4221 // this function was called, pass this Network in via the "changed" arugment, otherwise
4222 // pass null.
4223 // If only one Network has been changed but its NetworkCapabilities have not changed,
4224 // pass in the Network's score (from getCurrentScore()) prior to the change via
4225 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4226 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4227 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4228 // to avoid the slowness. It is not simply enough to process just "changed", for
4229 // example in the case where "changed"'s score decreases and another network should begin
4230 // satifying a NetworkRequest that "changed" currently satisfies.
4231
4232 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4233 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4234 // rematchNetworkAndRequests() handles.
4235 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004236 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4237 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004238 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004239 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4240 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4241 NascentState.NOT_JUST_VALIDATED,
4242 // Only reap the last time through the loop. Reaping before all rematching
4243 // is complete could incorrectly teardown a network that hasn't yet been
4244 // rematched.
4245 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4246 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004247 }
4248 }
4249 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004250
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004251 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004252 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004253 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004254 // For now only update icons for default connection.
4255 // TODO: Update WiFi and cellular icons separately. b/17237507
4256 if (!isDefaultNetwork(nai)) return;
4257
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004258 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004259 // Don't repeat publish.
4260 if (newInetCondition == mDefaultInetConditionPublished) return;
4261
4262 mDefaultInetConditionPublished = newInetCondition;
4263 sendInetConditionBroadcast(nai.networkInfo);
4264 }
4265
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004266 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4267 if (mLockdownTracker != null) {
4268 if (nai != null && nai.isVPN()) {
4269 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4270 } else {
4271 mLockdownTracker.onNetworkInfoChanged();
4272 }
4273 }
4274 }
4275
Robert Greenwalt7b816022014-04-18 15:25:25 -07004276 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4277 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004278 NetworkInfo oldInfo = null;
4279 synchronized (networkAgent) {
4280 oldInfo = networkAgent.networkInfo;
4281 networkAgent.networkInfo = newInfo;
4282 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004283 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004284
4285 if (oldInfo != null && oldInfo.getState() == state) {
4286 if (VDBG) log("ignoring duplicate network state non-change");
4287 return;
4288 }
4289 if (DBG) {
4290 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4291 (oldInfo == null ? "null" : oldInfo.getState()) +
4292 " to " + state);
4293 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004294
Paul Jenseneec75412014-08-04 12:21:19 -04004295 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004296 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004297 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004298 if (networkAgent.isVPN()) {
4299 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004300 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4301 (networkAgent.networkMisc == null ||
4302 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004303 } else {
4304 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4305 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004306 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004307 loge("Error creating network " + networkAgent.network.netId + ": "
4308 + e.getMessage());
4309 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004310 }
Paul Jenseneec75412014-08-04 12:21:19 -04004311 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004312 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004313 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004314
Paul Jensenca8f16a2014-05-09 12:47:55 -04004315 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004316 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004317
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004318 if (networkAgent.isVPN()) {
4319 // Temporarily disable the default proxy (not global).
4320 synchronized (mProxyLock) {
4321 if (!mDefaultProxyDisabled) {
4322 mDefaultProxyDisabled = true;
4323 if (mGlobalProxy == null && mDefaultProxy != null) {
4324 sendProxyBroadcast(null);
4325 }
4326 }
4327 }
4328 // TODO: support proxy per network.
4329 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004330
Paul Jensen2161a8e2014-09-11 11:00:39 -04004331 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004332 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4333 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004334
4335 // This has to happen after matching the requests, because callbacks are just requests.
4336 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 } else if (state == NetworkInfo.State.DISCONNECTED ||
4338 state == NetworkInfo.State.SUSPENDED) {
4339 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004340 if (networkAgent.isVPN()) {
4341 synchronized (mProxyLock) {
4342 if (mDefaultProxyDisabled) {
4343 mDefaultProxyDisabled = false;
4344 if (mGlobalProxy == null && mDefaultProxy != null) {
4345 sendProxyBroadcast(mDefaultProxy);
4346 }
4347 }
4348 }
4349 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004350 }
4351 }
4352
Robert Greenwaltac96c522014-06-03 16:43:57 -07004353 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4354 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004355 if (score < 0) {
4356 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4357 "). Bumping score to min of 0");
4358 score = 0;
4359 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004360
Paul Jensen2161a8e2014-09-11 11:00:39 -04004361 final int oldScore = nai.getCurrentScore();
4362 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004363
Paul Jensen57a767f2014-11-19 13:01:46 -05004364 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004365
Paul Jensenc8b9a742014-09-30 15:37:41 -04004366 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004367 }
4368
Robert Greenwalt9258c642014-03-26 16:47:06 -07004369 // notify only this one new request of the current state
4370 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4371 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4372 // TODO - read state from monitor to decide what to send.
4373// if (nai.networkMonitor.isLingering()) {
4374// notifyType = NetworkCallbacks.LOSING;
4375// } else if (nai.networkMonitor.isEvaluating()) {
4376// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4377// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004378 if (nri.mPendingIntent == null) {
4379 callCallbackForRequest(nri, nai, notifyType);
4380 } else {
4381 sendPendingIntentForRequest(nri, nai, notifyType);
4382 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004383 }
4384
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004385 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004386 // The NetworkInfo we actually send out has no bearing on the real
4387 // state of affairs. For example, if the default connection is mobile,
4388 // and a request for HIPRI has just gone away, we need to pretend that
4389 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4390 // the state to DISCONNECTED, even though the network is of type MOBILE
4391 // and is still connected.
4392 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4393 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004394 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004395 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004396 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004397 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004398 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004399 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4400 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4401 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4402 if (info.isFailover()) {
4403 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4404 nai.networkInfo.setFailover(false);
4405 }
4406 if (info.getReason() != null) {
4407 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4408 }
4409 if (info.getExtraInfo() != null) {
4410 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4411 }
4412 NetworkAgentInfo newDefaultAgent = null;
4413 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4414 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4415 if (newDefaultAgent != null) {
4416 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4417 newDefaultAgent.networkInfo);
4418 } else {
4419 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4420 }
4421 }
4422 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4423 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004424 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004425 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004426 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004427 }
4428 }
4429 }
4430
Robert Greenwalt7b816022014-04-18 15:25:25 -07004431 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004432 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004433 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004434 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4435 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4436 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004437 if (nri.mPendingIntent == null) {
4438 callCallbackForRequest(nri, networkAgent, notifyType);
4439 } else {
4440 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4441 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004442 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004443 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004444
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004445 private String notifyTypeToName(int notifyType) {
4446 switch (notifyType) {
4447 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4448 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4449 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4450 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4451 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4452 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4453 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4454 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4455 }
4456 return "UNKNOWN";
4457 }
4458
Jeff Sharkey69736342014-12-08 14:50:12 -08004459 /**
4460 * Notify other system services that set of active ifaces has changed.
4461 */
4462 private void notifyIfacesChanged() {
4463 try {
4464 mStatsService.forceUpdateIfaces();
4465 } catch (Exception ignored) {
4466 }
4467 }
4468
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004469 @Override
4470 public boolean addVpnAddress(String address, int prefixLength) {
4471 throwIfLockdownEnabled();
4472 int user = UserHandle.getUserId(Binder.getCallingUid());
4473 synchronized (mVpns) {
4474 return mVpns.get(user).addAddress(address, prefixLength);
4475 }
4476 }
4477
4478 @Override
4479 public boolean removeVpnAddress(String address, int prefixLength) {
4480 throwIfLockdownEnabled();
4481 int user = UserHandle.getUserId(Binder.getCallingUid());
4482 synchronized (mVpns) {
4483 return mVpns.get(user).removeAddress(address, prefixLength);
4484 }
4485 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004486
4487 @Override
4488 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4489 throwIfLockdownEnabled();
4490 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004491 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004492 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004493 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004494 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004495 if (success) {
4496 notifyIfacesChanged();
4497 }
4498 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004499 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004500
4501 @Override
4502 public void factoryReset() {
4503 enforceConnectivityInternalPermission();
4504 // Turn airplane mode off
4505 setAirplaneMode(false);
4506
4507 // Untether
4508 for (String tether : getTetheredIfaces()) {
4509 untether(tether);
4510 }
4511
4512 // Turn VPN off
4513 VpnConfig vpnConfig = getVpnConfig();
4514 if (vpnConfig != null) {
4515 if (vpnConfig.legacy) {
4516 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN);
4517 } else {
4518 // Prevent this app from initiating VPN connections in the future without
4519 // user intervention.
4520 setVpnPackageAuthorization(false);
4521
4522 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN);
4523 }
4524 }
4525 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004526}