blob: b785d3dc0ce4e9a76006c0c8c740096fe537403c [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;
21import static android.net.ConnectivityManager.CONNECTIVITY_ACTION_IMMEDIATE;
Paul Jensen31a94f42015-02-13 14:18:39 -050022import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070023import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070024import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070025import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070026import static android.net.ConnectivityManager.isNetworkTypeValid;
27import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070028import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070029
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
836 if (networkCostly && (uidRules & RULE_REJECT_METERED) != 0) {
837 return true;
838 }
839
840 // no restrictive rules; network is visible
841 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700842 }
843
844 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700845 * Return a filtered {@link NetworkInfo}, potentially marked
846 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800847 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700848 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800849 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
850 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400851 // network is blocked; clone and override state
852 info = new NetworkInfo(info);
853 info.setDetailedState(DetailedState.BLOCKED, null, null);
Erik Kline338317e2015-01-19 16:19:09 +0900854 if (DBG) {
855 log("returning Blocked NetworkInfo for ifname=" +
856 lp.getInterfaceName() + ", uid=" + uid);
857 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700858 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800859 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700860 info = mLockdownTracker.augmentNetworkInfo(info);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700861 if (DBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700862 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700863 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700864 }
865
866 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800867 * Return NetworkInfo for the active (i.e., connected) network interface.
868 * It is assumed that at most one network is active at a time. If more
869 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700870 * @return the info for the active network, or {@code null} if none is
871 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800872 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700873 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800874 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700875 enforceAccessPermission();
876 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800877 NetworkState state = getUnfilteredActiveNetworkState(uid);
878 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800879 }
880
Paul Jensen31a94f42015-02-13 14:18:39 -0500881 @Override
882 public Network getActiveNetwork() {
883 enforceAccessPermission();
884 final int uid = Binder.getCallingUid();
885 final int user = UserHandle.getUserId(uid);
886 int vpnNetId = NETID_UNSET;
887 synchronized (mVpns) {
888 final Vpn vpn = mVpns.get(user);
889 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
890 }
891 NetworkAgentInfo nai;
892 if (vpnNetId != NETID_UNSET) {
893 synchronized (mNetworkForNetId) {
894 nai = mNetworkForNetId.get(vpnNetId);
895 }
896 if (nai != null) return nai.network;
897 }
898 nai = getDefaultNetwork();
899 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
900 return nai != null ? nai.network : null;
901 }
902
Wink Saville948282b2013-08-29 08:55:16 -0700903 /**
904 * Find the first Provisioning network.
905 *
906 * @return NetworkInfo or null if none.
907 */
908 private NetworkInfo getProvisioningNetworkInfo() {
909 enforceAccessPermission();
910
911 // Find the first Provisioning Network
912 NetworkInfo provNi = null;
913 for (NetworkInfo ni : getAllNetworkInfo()) {
Wink Saville67c38212013-09-05 12:02:25 -0700914 if (ni.isConnectedToProvisioningNetwork()) {
Wink Saville948282b2013-08-29 08:55:16 -0700915 provNi = ni;
916 break;
917 }
918 }
919 if (DBG) log("getProvisioningNetworkInfo: X provNi=" + provNi);
920 return provNi;
921 }
922
923 /**
924 * Find the first Provisioning network or the ActiveDefaultNetwork
925 * if there is no Provisioning network
926 *
927 * @return NetworkInfo or null if none.
928 */
929 @Override
930 public NetworkInfo getProvisioningOrActiveNetworkInfo() {
931 enforceAccessPermission();
932
933 NetworkInfo provNi = getProvisioningNetworkInfo();
934 if (provNi == null) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935 provNi = getActiveNetworkInfo();
Wink Saville948282b2013-08-29 08:55:16 -0700936 }
937 if (DBG) log("getProvisioningOrActiveNetworkInfo: X provNi=" + provNi);
938 return provNi;
939 }
940
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700941 public NetworkInfo getActiveNetworkInfoUnfiltered() {
942 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800943 final int uid = Binder.getCallingUid();
944 NetworkState state = getUnfilteredActiveNetworkState(uid);
945 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700946 }
947
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700948 @Override
949 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
950 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800951 NetworkState state = getUnfilteredActiveNetworkState(uid);
952 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700953 }
954
955 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800956 public NetworkInfo getNetworkInfo(int networkType) {
957 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700958 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900959 if (getVpnUnderlyingNetworks(uid) != null) {
960 // A VPN is active, so we may need to return one of its underlying networks. This
961 // information is not available in LegacyTypeTracker, so we have to get it from
962 // getUnfilteredActiveNetworkState.
963 NetworkState state = getUnfilteredActiveNetworkState(uid);
964 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
965 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
966 }
967 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800968 NetworkState state = getFilteredNetworkState(networkType, uid);
969 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800970 }
971
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800972 @Override
973 public NetworkInfo getNetworkInfoForNetwork(Network network) {
974 enforceAccessPermission();
975 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700976 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800977 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
978 if (nai != null) {
979 synchronized (nai) {
980 info = new NetworkInfo(nai.networkInfo);
981 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700982 }
983 }
984 return info;
985 }
986
987 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800988 public NetworkInfo[] getAllNetworkInfo() {
989 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700990 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -0400991 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
992 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800993 NetworkInfo info = getNetworkInfo(networkType);
994 if (info != null) {
995 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700996 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800997 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700998 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800999 }
1000
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001001 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001002 public Network getNetworkForType(int networkType) {
1003 enforceAccessPermission();
1004 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001005 NetworkState state = getFilteredNetworkState(networkType, uid);
1006 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1007 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001008 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001009 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001010 }
1011
1012 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001013 public Network[] getAllNetworks() {
1014 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001015 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001016 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001017 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001018 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001019 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001020 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001021 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001022 }
1023
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001024 private NetworkCapabilities getNetworkCapabilitiesAndValidation(NetworkAgentInfo nai) {
1025 if (nai != null) {
1026 synchronized (nai) {
1027 if (nai.created) {
1028 NetworkCapabilities nc = new NetworkCapabilities(nai.networkCapabilities);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001029 if (nai.lastValidated) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001030 nc.addCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1031 } else {
1032 nc.removeCapability(NetworkCapabilities.NET_CAPABILITY_VALIDATED);
1033 }
1034 return nc;
1035 }
1036 }
1037 }
1038 return null;
1039 }
1040
1041 @Override
1042 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1043 // The basic principle is: if an app's traffic could possibly go over a
1044 // network, without the app doing anything multinetwork-specific,
1045 // (hence, by "default"), then include that network's capabilities in
1046 // the array.
1047 //
1048 // In the normal case, app traffic only goes over the system's default
1049 // network connection, so that's the only network returned.
1050 //
1051 // With a VPN in force, some app traffic may go into the VPN, and thus
1052 // over whatever underlying networks the VPN specifies, while other app
1053 // traffic may go over the system default network (e.g.: a split-tunnel
1054 // VPN, or an app disallowed by the VPN), so the set of networks
1055 // returned includes the VPN's underlying networks and the system
1056 // default.
1057 enforceAccessPermission();
1058
1059 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1060
1061 NetworkAgentInfo nai = getDefaultNetwork();
1062 NetworkCapabilities nc = getNetworkCapabilitiesAndValidation(getDefaultNetwork());
1063 if (nc != null) {
1064 result.put(nai.network, nc);
1065 }
1066
1067 if (!mLockdownEnabled) {
1068 synchronized (mVpns) {
1069 Vpn vpn = mVpns.get(userId);
1070 if (vpn != null) {
1071 Network[] networks = vpn.getUnderlyingNetworks();
1072 if (networks != null) {
1073 for (Network network : networks) {
1074 nai = getNetworkAgentInfoForNetwork(network);
1075 nc = getNetworkCapabilitiesAndValidation(nai);
1076 if (nc != null) {
1077 result.put(nai.network, nc);
1078 }
1079 }
1080 }
1081 }
1082 }
1083 }
1084
1085 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1086 out = result.values().toArray(out);
1087 return out;
1088 }
1089
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001090 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001091 public boolean isNetworkSupported(int networkType) {
1092 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001093 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001094 }
1095
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001096 /**
1097 * Return LinkProperties for the active (i.e., connected) default
1098 * network interface. It is assumed that at most one default network
1099 * is active at a time. If more than one is active, it is indeterminate
1100 * which will be returned.
1101 * @return the ip properties for the active network, or {@code null} if
1102 * none is active
1103 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001104 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001105 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001106 enforceAccessPermission();
1107 final int uid = Binder.getCallingUid();
1108 NetworkState state = getUnfilteredActiveNetworkState(uid);
1109 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001110 }
1111
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001112 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001113 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001114 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001115 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1116 if (nai != null) {
1117 synchronized (nai) {
1118 return new LinkProperties(nai.linkProperties);
1119 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001120 }
1121 return null;
1122 }
1123
Robert Greenwalt12e67352014-05-13 21:41:06 -07001124 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001125 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001126 public LinkProperties getLinkProperties(Network network) {
1127 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001128 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001129 if (nai != null) {
1130 synchronized (nai) {
1131 return new LinkProperties(nai.linkProperties);
1132 }
1133 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001134 return null;
1135 }
1136
1137 @Override
1138 public NetworkCapabilities getNetworkCapabilities(Network network) {
1139 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001140 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001141 if (nai != null) {
1142 synchronized (nai) {
1143 return new NetworkCapabilities(nai.networkCapabilities);
1144 }
1145 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001146 return null;
1147 }
1148
1149 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001150 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001151 // Require internal since we're handing out IMSI details
1152 enforceConnectivityInternalPermission();
1153
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001154 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001155 for (Network network : getAllNetworks()) {
1156 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1157 if (nai != null) {
1158 synchronized (nai) {
1159 final String subscriberId = (nai.networkMisc != null)
1160 ? nai.networkMisc.subscriberId : null;
1161 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1162 nai.networkCapabilities, network, subscriberId, null));
1163 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001164 }
1165 }
1166 return result.toArray(new NetworkState[result.size()]);
1167 }
1168
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001169 @Override
1170 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1171 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001172 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001173 final long token = Binder.clearCallingIdentity();
1174 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001175 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1176 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001177 try {
1178 return mPolicyManager.getNetworkQuotaInfo(state);
1179 } catch (RemoteException e) {
1180 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001181 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001182 return null;
1183 } finally {
1184 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001185 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001186 }
1187
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001188 @Override
1189 public boolean isActiveNetworkMetered() {
1190 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001191 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001192 final long token = Binder.clearCallingIdentity();
1193 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001194 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001195 } finally {
1196 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001197 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001198 }
1199
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001200 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1201 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1202 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001203 try {
1204 return mPolicyManager.isNetworkMetered(state);
1205 } catch (RemoteException e) {
1206 }
1207 }
1208 return false;
1209 }
1210
Jeff Sharkey216c1812012-08-05 14:29:23 -07001211 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1212 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001213 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001214 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001215 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001216 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001217 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001218
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001219 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001220 * Ensure that a network route exists to deliver traffic to the specified
1221 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001222 * @param networkType the type of the network over which traffic to the
1223 * specified host is to be routed
1224 * @param hostAddress the IP address of the host to which the route is
1225 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001226 * @return {@code true} on success, {@code false} on failure
1227 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001228 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001229 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001230 if (mProtectedNetworks.contains(networkType)) {
1231 enforceConnectivityInternalPermission();
1232 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001233
Chad Brubakerc0234532014-02-14 13:24:29 -08001234 InetAddress addr;
1235 try {
1236 addr = InetAddress.getByAddress(hostAddress);
1237 } catch (UnknownHostException e) {
1238 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1239 return false;
1240 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001241
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001242 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001243 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001244 return false;
1245 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001246
1247 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1248 if (nai == null) {
1249 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1250 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1251 } else {
1252 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1253 }
1254 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001255 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001256
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001257 DetailedState netState;
1258 synchronized (nai) {
1259 netState = nai.networkInfo.getDetailedState();
1260 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001261
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001262 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001263 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001264 log("requestRouteToHostAddress on down network "
1265 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001266 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001267 }
1268 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001269 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001270
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001271 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001272 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001273 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001274 LinkProperties lp;
1275 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001276 synchronized (nai) {
1277 lp = nai.linkProperties;
1278 netId = nai.network.netId;
1279 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001280 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001281 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1282 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001283 } finally {
1284 Binder.restoreCallingIdentity(token);
1285 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001286 }
1287
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001288 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001289 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001290 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001291 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001292 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001293 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001294 if (bestRoute.getGateway().equals(addr)) {
1295 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001296 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001297 } else {
1298 // if we will connect to this through another route, add a direct route
1299 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001300 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001301 }
1302 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001303 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001304 try {
1305 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1306 } catch (Exception e) {
1307 // never crash - catch them all
1308 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001309 return false;
1310 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001311 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001312 }
1313
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001314 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1315 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001316 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001317 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001318 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001319 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001320 }
1321
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001322 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001323 // skip update when we've already applied rules
1324 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1325 if (oldRules == uidRules) return;
1326
1327 mUidRules.put(uid, uidRules);
1328 }
1329
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001330 // TODO: notify UID when it has requested targeted updates
1331 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001332
1333 @Override
1334 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001335 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001336 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001337 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001338 }
1339
1340 synchronized (mRulesLock) {
1341 mMeteredIfaces.clear();
1342 for (String iface : meteredIfaces) {
1343 mMeteredIfaces.add(iface);
1344 }
1345 }
1346 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001347
1348 @Override
1349 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1350 // caller is NPMS, since we only register with them
1351 if (LOGD_RULES) {
1352 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1353 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001354 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001355 };
1356
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001357 private void enforceInternetPermission() {
1358 mContext.enforceCallingOrSelfPermission(
1359 android.Manifest.permission.INTERNET,
1360 "ConnectivityService");
1361 }
1362
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001363 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001364 mContext.enforceCallingOrSelfPermission(
1365 android.Manifest.permission.ACCESS_NETWORK_STATE,
1366 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001367 }
1368
1369 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001370 mContext.enforceCallingOrSelfPermission(
1371 android.Manifest.permission.CHANGE_NETWORK_STATE,
1372 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001373 }
1374
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001375 private void enforceTetherAccessPermission() {
1376 mContext.enforceCallingOrSelfPermission(
1377 android.Manifest.permission.ACCESS_NETWORK_STATE,
1378 "ConnectivityService");
1379 }
1380
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001381 private void enforceConnectivityInternalPermission() {
1382 mContext.enforceCallingOrSelfPermission(
1383 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1384 "ConnectivityService");
1385 }
1386
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001387 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001388 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001389 sendGeneralBroadcast(info, CONNECTIVITY_ACTION_IMMEDIATE);
1390 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001391 }
1392
1393 private void sendInetConditionBroadcast(NetworkInfo info) {
1394 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1395 }
1396
Wink Saville628b0852011-08-04 15:01:58 -07001397 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001398 if (mLockdownTracker != null) {
1399 info = mLockdownTracker.augmentNetworkInfo(info);
1400 }
1401
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001402 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001403 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001404 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001405 if (info.isFailover()) {
1406 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1407 info.setFailover(false);
1408 }
1409 if (info.getReason() != null) {
1410 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1411 }
1412 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001413 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1414 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001416 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001417 return intent;
1418 }
1419
1420 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1421 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1422 }
1423
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001424 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001425 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1426 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1427 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001428 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001429 final long ident = Binder.clearCallingIdentity();
1430 try {
1431 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1432 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1433 } finally {
1434 Binder.restoreCallingIdentity(ident);
1435 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001436 }
1437
Mike Lockwood0f79b542009-08-14 14:18:49 -04001438 private void sendStickyBroadcast(Intent intent) {
1439 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001440 if (!mSystemReady) {
1441 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001442 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001443 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001444 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001445 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001446 }
1447
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001448 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001449 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1450 final IBatteryStats bs = BatteryStatsService.getService();
1451 try {
1452 NetworkInfo ni = intent.getParcelableExtra(
1453 ConnectivityManager.EXTRA_NETWORK_INFO);
1454 bs.noteConnectivityChanged(intent.getIntExtra(
1455 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1456 ni != null ? ni.getState().toString() : "?");
1457 } catch (RemoteException e) {
1458 }
1459 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001460 try {
1461 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1462 } finally {
1463 Binder.restoreCallingIdentity(ident);
1464 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001465 }
1466 }
1467
1468 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001469 loadGlobalProxy();
1470
Mike Lockwood0f79b542009-08-14 14:18:49 -04001471 synchronized(this) {
1472 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001473 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001474 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001475 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001476 }
1477 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001478 // load the global proxy at startup
1479 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001480
1481 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1482 // for user to unlock device.
1483 if (!updateLockdownVpn()) {
1484 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1485 mContext.registerReceiver(mUserPresentReceiver, filter);
1486 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001487
1488 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001489
1490 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001491 }
1492
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001493 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1494 @Override
1495 public void onReceive(Context context, Intent intent) {
1496 // Try creating lockdown tracker, since user present usually means
1497 // unlocked keystore.
1498 if (updateLockdownVpn()) {
1499 mContext.unregisterReceiver(this);
1500 }
1501 }
1502 };
1503
Wink Savilled747cbc2013-08-07 16:22:47 -07001504 /** @hide */
1505 @Override
1506 public void captivePortalCheckCompleted(NetworkInfo info, boolean isCaptivePortal) {
1507 enforceConnectivityInternalPermission();
1508 if (DBG) log("captivePortalCheckCompleted: ni=" + info + " captive=" + isCaptivePortal);
Robert Greenwalt12e67352014-05-13 21:41:06 -07001509// mNetTrackers[info.getType()].captivePortalCheckCompleted(isCaptivePortal);
Wink Savilled747cbc2013-08-07 16:22:47 -07001510 }
1511
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001512 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001513 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001514 *
1515 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001516 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001517 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001518 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1519 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001520
1521 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001522 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001523
Robert Greenwalt7b816022014-04-18 15:25:25 -07001524 if (networkAgent.networkCapabilities.hasTransport(
1525 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001526 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1527 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001528 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001529 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001530 } else if (networkAgent.networkCapabilities.hasTransport(
1531 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001532 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1533 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001534 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001535 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001536 } else {
1537 // do not track any other networks
1538 timeout = 0;
1539 }
1540
Robert Greenwalt7b816022014-04-18 15:25:25 -07001541 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001542 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001543 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001544 } catch (Exception e) {
1545 // You shall not crash!
1546 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001547 }
1548 }
1549 }
1550
1551 /**
1552 * Remove data activity tracking when network disconnects.
1553 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001554 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1555 final String iface = networkAgent.linkProperties.getInterfaceName();
1556 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001557
Robert Greenwalt7b816022014-04-18 15:25:25 -07001558 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1559 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001560 try {
1561 // the call fails silently if no idletimer setup for this interface
1562 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001563 } catch (Exception e) {
1564 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001565 }
1566 }
1567 }
1568
1569 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001570 * Reads the network specific MTU size from reources.
1571 * and set it on it's iface.
1572 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001573 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1574 final String iface = newLp.getInterfaceName();
1575 final int mtu = newLp.getMtu();
1576 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1577 if (VDBG) log("identical MTU - not setting");
1578 return;
1579 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001580
Robert Greenwalt43074032014-08-15 17:53:05 -07001581 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001582 loge("Unexpected mtu value: " + mtu + ", " + iface);
1583 return;
1584 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001585
w1997615afd812014-08-05 15:18:11 -07001586 // Cannot set MTU without interface name
1587 if (TextUtils.isEmpty(iface)) {
1588 loge("Setting MTU size with null iface.");
1589 return;
1590 }
1591
Robert Greenwalt7b816022014-04-18 15:25:25 -07001592 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001593 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001594 mNetd.setMtu(iface, mtu);
1595 } catch (Exception e) {
1596 Slog.e(TAG, "exception in setMtu()" + e);
1597 }
1598 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001599
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001600 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Irfan Sheriffd649c122010-06-09 15:39:36 -07001601
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001602 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1603 if (isDefaultNetwork(nai) == false) {
1604 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001605 }
1606
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001607 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1608 String[] values = null;
1609 if (tcpBufferSizes != null) {
1610 values = tcpBufferSizes.split(",");
1611 }
1612
1613 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001614 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001615 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1616 values = tcpBufferSizes.split(",");
1617 }
1618
1619 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1620
1621 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001622 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001623
1624 final String prefix = "/sys/kernel/ipv4/tcp_";
1625 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1626 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1627 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1628 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1629 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1630 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1631 mCurrentTcpBufferSizes = tcpBufferSizes;
1632 } catch (IOException e) {
1633 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001634 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001635
1636 final String defaultRwndKey = "net.tcp.default_init_rwnd";
1637 int defaultRwndValue = SystemProperties.getInt(defaultRwndKey, 0);
1638 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
1639 Settings.Global.TCP_DEFAULT_INIT_RWND, defaultRwndValue);
1640 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1641 if (rwndValue != 0) {
1642 SystemProperties.set(sysctlKey, rwndValue.toString());
1643 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001644 }
1645
Mattias Falk8b47b362011-08-23 14:15:13 +02001646 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001647 /*
1648 * Tell the VMs to toss their DNS caches
1649 */
1650 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1651 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001652 /*
1653 * Connectivity events can happen before boot has completed ...
1654 */
1655 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001656 final long ident = Binder.clearCallingIdentity();
1657 try {
1658 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1659 } finally {
1660 Binder.restoreCallingIdentity(ident);
1661 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001662 }
1663
Robert Greenwalt562cc542014-05-15 18:07:26 -07001664 @Override
1665 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001666 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1667 NETWORK_RESTORE_DELAY_PROP_NAME);
1668 if(restoreDefaultNetworkDelayStr != null &&
1669 restoreDefaultNetworkDelayStr.length() != 0) {
1670 try {
1671 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1672 } catch (NumberFormatException e) {
1673 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001674 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001675 // if the system property isn't set, use the value for the apn type
1676 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1677
1678 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1679 (mNetConfigs[networkType] != null)) {
1680 ret = mNetConfigs[networkType].restoreTime;
1681 }
1682 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001683 }
1684
1685 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001686 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1687 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001688 if (mContext.checkCallingOrSelfPermission(
1689 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001690 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001691 pw.println("Permission Denial: can't dump ConnectivityService " +
1692 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1693 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001694 return;
1695 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001696
Robert Greenwalta67be032014-05-16 15:49:14 -07001697 pw.println("NetworkFactories for:");
1698 pw.increaseIndent();
1699 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
1700 pw.println(nfi.name);
1701 }
1702 pw.decreaseIndent();
1703 pw.println();
1704
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001705 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1706 pw.print("Active default network: ");
1707 if (defaultNai == null) {
1708 pw.println("none");
1709 } else {
1710 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001711 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001712 pw.println();
1713
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001714 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001715 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001716 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1717 pw.println(nai.toString());
1718 pw.increaseIndent();
1719 pw.println("Requests:");
1720 pw.increaseIndent();
1721 for (int i = 0; i < nai.networkRequests.size(); i++) {
1722 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001723 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001724 pw.decreaseIndent();
1725 pw.println("Lingered:");
1726 pw.increaseIndent();
1727 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1728 pw.decreaseIndent();
1729 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001730 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001731 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001732 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001733
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001734 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001735 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001736 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1737 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001738 }
1739 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001740 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001741
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001742 pw.println("mLegacyTypeTracker:");
1743 pw.increaseIndent();
1744 mLegacyTypeTracker.dump(pw);
1745 pw.decreaseIndent();
1746 pw.println();
1747
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001748 synchronized (this) {
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001749 pw.println("NetworkTransitionWakeLock is currently " +
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001750 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held.");
1751 pw.println("It was last requested for "+mNetTransitionWakeLockCausedBy);
1752 }
1753 pw.println();
1754
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001755 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001756
1757 if (mInetLog != null) {
1758 pw.println();
1759 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001760 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001761 for(int i = 0; i < mInetLog.size(); i++) {
1762 pw.println(mInetLog.get(i));
1763 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001764 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001765 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001766 }
1767
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001768 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001769 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001770 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001771 if (officialNai != null && officialNai.equals(nai)) return true;
1772 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001773 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001774 " - " + nai);
1775 }
1776 return false;
1777 }
1778
Paul Jensenc8b9a742014-09-30 15:37:41 -04001779 private boolean isRequest(NetworkRequest request) {
1780 return mNetworkRequests.get(request).isRequest;
1781 }
1782
Robert Greenwalt42acef32009-08-12 16:08:25 -07001783 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001784 private class NetworkStateTrackerHandler extends Handler {
1785 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001786 super(looper);
1787 }
1788
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001789 @Override
1790 public void handleMessage(Message msg) {
1791 NetworkInfo info;
1792 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001793 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001794 handleAsyncChannelHalfConnect(msg);
1795 break;
1796 }
1797 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1798 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1799 if (nai != null) nai.asyncChannel.disconnect();
1800 break;
1801 }
1802 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1803 handleAsyncChannelDisconnected(msg);
1804 break;
1805 }
1806 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1807 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1808 if (nai == null) {
1809 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1810 } else {
1811 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001812 }
1813 break;
1814 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001815 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1816 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1817 if (nai == null) {
1818 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1819 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001820 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001821 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001822 "; created=" + nai.created);
1823 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001824 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001825 synchronized (nai) {
1826 nai.linkProperties = (LinkProperties)msg.obj;
1827 }
Paul Jenseneec75412014-08-04 12:21:19 -04001828 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001829 }
1830 break;
1831 }
1832 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1833 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1834 if (nai == null) {
1835 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1836 break;
1837 }
1838 info = (NetworkInfo) msg.obj;
1839 updateNetworkInfo(nai, info);
1840 break;
1841 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001842 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1843 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1844 if (nai == null) {
1845 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1846 break;
1847 }
1848 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001849 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001850 break;
1851 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001852 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1853 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1854 if (nai == null) {
1855 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1856 break;
1857 }
1858 try {
1859 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001860 } catch (Exception e) {
1861 // Never crash!
1862 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001863 }
1864 break;
1865 }
1866 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1867 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1868 if (nai == null) {
1869 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1870 break;
1871 }
1872 try {
1873 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001874 } catch (Exception e) {
1875 // Never crash!
1876 loge("Exception in removeVpnUidRanges: " + e);
1877 }
1878 break;
1879 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001880 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1881 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1882 if (nai == null) {
1883 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1884 break;
1885 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001886 if (nai.created && !nai.networkMisc.explicitlySelected) {
1887 loge("ERROR: created network explicitly selected.");
1888 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001889 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001890 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001891 break;
1892 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001893 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001894 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001895 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_VALIDATED")) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001896 boolean valid = (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001897 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001898 if (valid) {
1899 if (DBG) log("Validated " + nai.name());
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001900 if (!nai.everValidated) {
1901 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001902 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1903 ReapUnvalidatedNetworks.REAP);
1904 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001905 sendUpdatedScoreToFactories(nai);
1906 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001907 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001908 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07001909 // Let the NetworkAgent know the state of its network
1910 nai.asyncChannel.sendMessage(
1911 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
1912 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
1913 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001914
1915 // TODO: trigger a NetworkCapabilities update so that the dialog can know
1916 // that the network is now validated and close itself.
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001917 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001918 break;
1919 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04001920 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001921 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001922 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
1923 handleLingerComplete(nai);
1924 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001925 break;
1926 }
Paul Jensen869868be2014-05-15 10:33:05 -04001927 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001928 if (msg.arg1 == 0) {
1929 setProvNotificationVisibleIntent(false, msg.arg2, 0, null, null);
1930 } else {
Paul Jensen5df4bec2014-08-25 22:45:39 -04001931 NetworkAgentInfo nai = null;
1932 synchronized (mNetworkForNetId) {
1933 nai = mNetworkForNetId.get(msg.arg2);
1934 }
1935 if (nai == null) {
1936 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
1937 break;
1938 }
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04001939 setProvNotificationVisibleIntent(true, msg.arg2, nai.networkInfo.getType(),
1940 nai.networkInfo.getExtraInfo(), (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04001941 }
Paul Jensen869868be2014-05-15 10:33:05 -04001942 break;
1943 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001944 }
1945 }
1946 }
1947
Paul Jensen0cc17322014-11-25 15:26:53 -05001948 // Cancel any lingering so the linger timeout doesn't teardown a network.
1949 // This should be called when a network begins satisfying a NetworkRequest.
1950 // Note: depending on what state the NetworkMonitor is in (e.g.,
1951 // if it's awaiting captive portal login, or if validation failed), this
1952 // may trigger a re-evaluation of the network.
1953 private void unlinger(NetworkAgentInfo nai) {
1954 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05001955 // If network has never been validated, it cannot have been lingered, so don't bother
1956 // needlessly triggering a re-evaluation.
1957 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05001958 nai.networkLingered.clear();
1959 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
1960 }
1961
Robert Greenwalt7b816022014-04-18 15:25:25 -07001962 private void handleAsyncChannelHalfConnect(Message msg) {
1963 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07001964 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001965 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1966 if (VDBG) log("NetworkFactory connected");
1967 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07001968 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07001969 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07001970 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07001971 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04001972 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001973 }
1974 } else {
1975 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07001976 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001977 }
1978 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
1979 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
1980 if (VDBG) log("NetworkAgent connected");
1981 // A network agent has requested a connection. Establish the connection.
1982 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
1983 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
1984 } else {
1985 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07001986 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07001987 if (nai != null) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001988 synchronized (mNetworkForNetId) {
1989 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05001990 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001991 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09001992 // Just in case.
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07001993 mLegacyTypeTracker.remove(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07001994 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001995 }
1996 }
1997 }
Paul Jensen0cc17322014-11-25 15:26:53 -05001998
Robert Greenwalt7b816022014-04-18 15:25:25 -07001999 private void handleAsyncChannelDisconnected(Message msg) {
2000 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2001 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002002 if (DBG) {
2003 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2004 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002005 // A network agent has disconnected.
Paul Jenseneec75412014-08-04 12:21:19 -04002006 if (nai.created) {
2007 // Tell netd to clean up the configuration for this network
2008 // (routing rules, DNS, etc).
2009 try {
2010 mNetd.removeNetwork(nai.network.netId);
2011 } catch (Exception e) {
2012 loge("Exception removing network: " + e);
2013 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002014 }
Robert Greenwalt562cc542014-05-15 18:07:26 -07002015 // TODO - if we move the logic to the network agent (have them disconnect
2016 // because they lost all their requests or because their score isn't good)
2017 // then they would disconnect organically, report their new state and then
2018 // disconnect the channel.
2019 if (nai.networkInfo.isConnected()) {
2020 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2021 null, null);
2022 }
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002023 if (isDefaultNetwork(nai)) {
2024 mDefaultInetConditionPublished = 0;
2025 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002026 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002027 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002028 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002029 mNetworkAgentInfos.remove(msg.replyTo);
2030 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07002031 mLegacyTypeTracker.remove(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002032 synchronized (mNetworkForNetId) {
2033 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002034 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002035 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002036 // Since we've lost the network, go through all the requests that
2037 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002038 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002039 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002040 for (int i = 0; i < nai.networkRequests.size(); i++) {
2041 NetworkRequest request = nai.networkRequests.valueAt(i);
2042 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2043 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002044 if (DBG) {
2045 log("Checking for replacement network to handle request " + request );
2046 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002047 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002048 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002049 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002050 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2051 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002052 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002053 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002054 alternative = existing;
2055 }
2056 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002057 if (alternative != null) {
2058 if (DBG) log(" found replacement in " + alternative.name());
2059 if (!toActivate.contains(alternative)) {
2060 toActivate.add(alternative);
2061 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002062 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002063 }
2064 }
2065 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2066 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002067 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002068 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002069 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002070 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002071 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002072 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2073 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002074 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002075 }
Maunik Shah4b647f42015-03-30 11:36:42 +05302076 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2077 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002078 }
2079
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002080 // If this method proves to be too slow then we can maintain a separate
2081 // pendingIntent => NetworkRequestInfo map.
2082 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2083 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2084 Intent intent = pendingIntent.getIntent();
2085 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2086 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2087 if (existingPendingIntent != null &&
2088 existingPendingIntent.getIntent().filterEquals(intent)) {
2089 return entry.getValue();
2090 }
2091 }
2092 return null;
2093 }
2094
2095 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2096 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2097
2098 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2099 if (existingRequest != null) { // remove the existing request.
2100 if (DBG) log("Replacing " + existingRequest.request + " with "
2101 + nri.request + " because their intents matched.");
2102 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2103 }
2104 handleRegisterNetworkRequest(msg);
2105 }
2106
Robert Greenwalt9258c642014-03-26 16:47:06 -07002107 private void handleRegisterNetworkRequest(Message msg) {
2108 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002109
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002110 mNetworkRequests.put(nri.request, nri);
2111
Paul Jensen0cc17322014-11-25 15:26:53 -05002112 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2113
Robert Greenwalt9258c642014-03-26 16:47:06 -07002114 // Check for the best currently alive network that satisfies this request
2115 NetworkAgentInfo bestNetwork = null;
2116 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002117 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002118 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002119 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002120 if (!nri.isRequest) {
2121 // Not setting bestNetwork here as a listening NetworkRequest may be
2122 // satisfied by multiple Networks. Instead the request is added to
2123 // each satisfying Network and notified about each.
2124 network.addRequest(nri.request);
2125 notifyNetworkCallback(network, nri);
2126 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002127 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002128 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002129 }
2130 }
2131 }
2132 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002133 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002134 unlinger(bestNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07002135 bestNetwork.addRequest(nri.request);
Robert Greenwalt2d370702014-06-03 17:22:11 -07002136 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002137 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002138 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002139 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2140 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002141 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002142
Lorenzo Colittia793a672014-07-31 23:20:17 +09002143 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002144 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002145 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002146 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002147 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002148 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002149 }
2150 }
2151 }
2152
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002153 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2154 int callingUid) {
2155 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2156 if (nri != null) {
2157 handleReleaseNetworkRequest(nri.request, callingUid);
2158 }
2159 }
2160
Paul Jensen99364842014-12-09 11:43:45 -05002161 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2162 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2163 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2164 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2165 private boolean unneeded(NetworkAgentInfo nai) {
2166 if (!nai.created || nai.isVPN()) return false;
2167 boolean unneeded = true;
2168 if (nai.everValidated) {
2169 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2170 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2171 try {
2172 if (isRequest(nr)) unneeded = false;
2173 } catch (Exception e) {
2174 loge("Request " + nr + " not found in mNetworkRequests.");
2175 loge(" it came from request list of " + nai.name());
2176 }
2177 }
2178 } else {
2179 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2180 // If this Network is already the highest scoring Network for a request, or if
2181 // there is hope for it to become one if it validated, then it is needed.
2182 if (nri.isRequest && nai.satisfies(nri.request) &&
2183 (nai.networkRequests.get(nri.request.requestId) != null ||
2184 // Note that this catches two important cases:
2185 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2186 // is currently satisfying the request. This is desirable when
2187 // cellular ends up validating but WiFi does not.
2188 // 2. Unvalidated WiFi will not be reaped when validated cellular
2189 // is currently satsifying the request. This is desirable when
2190 // WiFi ends up validating and out scoring cellular.
2191 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2192 nai.getCurrentScoreAsValidated())) {
2193 unneeded = false;
2194 break;
2195 }
2196 }
2197 }
2198 return unneeded;
2199 }
2200
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002201 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2202 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002203 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002204 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002205 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2206 return;
2207 }
2208 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002209 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002210 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002211 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002212 // Find all networks that are satisfying this request and remove the request
2213 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002214 // TODO - it's my understanding that for a request there is only a single
2215 // network satisfying it, so this loop is wasteful
2216 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002217 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2218 if (nai.networkRequests.get(nri.request.requestId) != null) {
2219 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002220 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002221 log(" Removing from current network " + nai.name() +
2222 ", leaving " + nai.networkRequests.size() +
2223 " requests.");
2224 }
Paul Jensen99364842014-12-09 11:43:45 -05002225 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002226 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002227 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002228 } else {
2229 // suspect there should only be one pass through here
2230 // but if any were kept do the check below
2231 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002232 }
2233 }
2234 }
2235
Robert Greenwalt51481852015-01-08 14:43:31 -08002236 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2237 if (nai != null) {
2238 mNetworkForRequestId.remove(nri.request.requestId);
2239 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002240 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002241 // that a network connected to serve it, even though the network was already
2242 // connected. Now that this request has gone away, we might have to pretend
2243 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002244 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002245 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2246 boolean doRemove = true;
2247 if (wasKept) {
2248 // check if any of the remaining requests for this network are for the
2249 // same legacy type - if so, don't remove the nai
2250 for (int i = 0; i < nai.networkRequests.size(); i++) {
2251 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2252 if (otherRequest.legacyType == nri.request.legacyType &&
2253 isRequest(otherRequest)) {
2254 if (DBG) log(" still have other legacy request - leaving");
2255 doRemove = false;
2256 }
2257 }
2258 }
2259
2260 if (doRemove) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002261 mLegacyTypeTracker.remove(nri.request.legacyType, nai);
2262 }
2263 }
2264
Robert Greenwalta67be032014-05-16 15:49:14 -07002265 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002266 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2267 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002268 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002269 } else {
2270 // listens don't have a singular affectedNetwork. Check all networks to see
2271 // if this listen request applies and remove it.
2272 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2273 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002274 }
2275 }
2276 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2277 }
2278 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002279
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002280 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2281 enforceConnectivityInternalPermission();
2282 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2283 accept ? 1 : 0, always ? 1: 0, network));
2284 }
2285
2286 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2287 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2288 " accept=" + accept + " always=" + always);
2289
2290 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2291 if (nai == null) {
2292 // Nothing to do.
2293 return;
2294 }
2295
2296 if (nai.everValidated) {
2297 // The network validated while the dialog box was up. Don't make any changes. There's a
2298 // TODO in the dialog code to make it go away if the network validates; once that's
2299 // implemented, taking action here will be confusing.
2300 return;
2301 }
2302
2303 if (!nai.networkMisc.explicitlySelected) {
2304 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2305 }
2306
2307 if (accept != nai.networkMisc.acceptUnvalidated) {
2308 int oldScore = nai.getCurrentScore();
2309 nai.networkMisc.acceptUnvalidated = accept;
2310 rematchAllNetworksAndRequests(nai, oldScore);
2311 sendUpdatedScoreToFactories(nai);
2312 }
2313
2314 if (always) {
2315 nai.asyncChannel.sendMessage(
2316 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2317 }
2318
2319 // TODO: should we also disconnect from the network if accept is false?
2320 }
2321
2322 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
2323 mHandler.sendMessageDelayed(
2324 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2325 PROMPT_UNVALIDATED_DELAY_MS);
2326 }
2327
2328 private void handlePromptUnvalidated(Network network) {
2329 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2330
2331 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2332 // we haven't already been told to switch to it regardless of whether it validated or not.
2333 if (nai == null || nai.everValidated ||
2334 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2335 return;
2336 }
2337
2338 // TODO: What should we do if we've already switched to this network because we had no
2339 // better option? There are two obvious alternatives.
2340 //
2341 // 1. Decide that there's no point prompting because this is our only usable network.
2342 // However, because we didn't prompt, if later on a validated network comes along, we'll
2343 // either a) silently switch to it - bad if the user wanted to connect to stay on this
2344 // unvalidated network - or b) prompt the user at that later time - bad because the user
2345 // might not understand why they are now being prompted.
2346 //
2347 // 2. Always prompt the user, even if we have no other network to use. The user could then
2348 // try to find an alternative network to join (remember, if we got here, then the user
2349 // selected this network manually). This is bad because the prompt isn't really very
2350 // useful.
2351 //
2352 // For now we do #1, but we can revisit that later.
2353 if (isDefaultNetwork(nai)) {
2354 return;
2355 }
2356
2357 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
2358 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, network);
2359 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2360 intent.setClassName("com.android.settings",
2361 "com.android.settings.wifi.WifiNoInternetDialog");
2362 mContext.startActivityAsUser(intent, UserHandle.CURRENT);
2363 }
2364
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002365 private class InternalHandler extends Handler {
2366 public InternalHandler(Looper looper) {
2367 super(looper);
2368 }
2369
2370 @Override
2371 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002372 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002373 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002374 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002375 String causedBy = null;
2376 synchronized (ConnectivityService.this) {
2377 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2378 mNetTransitionWakeLock.isHeld()) {
2379 mNetTransitionWakeLock.release();
2380 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002381 } else {
2382 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002383 }
2384 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002385 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2386 log("Failed to find a new network - expiring NetTransition Wakelock");
2387 } else {
2388 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2389 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002390 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002391 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002392 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002393 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002394 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002395 break;
2396 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002397 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002398 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002399 sendStickyBroadcast(intent);
2400 break;
2401 }
Jason Monkdecd2952013-10-10 14:02:51 -04002402 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002403 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002404 break;
2405 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002406 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002407 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2408 break;
2409 }
2410 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2411 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002412 break;
2413 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002414 case EVENT_REGISTER_NETWORK_AGENT: {
2415 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2416 break;
2417 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002418 case EVENT_REGISTER_NETWORK_REQUEST:
2419 case EVENT_REGISTER_NETWORK_LISTENER: {
2420 handleRegisterNetworkRequest(msg);
2421 break;
2422 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002423 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT: {
2424 handleRegisterNetworkRequestWithIntent(msg);
2425 break;
2426 }
2427 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2428 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2429 break;
2430 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002431 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002432 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002433 break;
2434 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002435 case EVENT_SET_ACCEPT_UNVALIDATED: {
2436 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2437 break;
2438 }
2439 case EVENT_PROMPT_UNVALIDATED: {
2440 handlePromptUnvalidated((Network) msg.obj);
2441 break;
2442 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002443 case EVENT_SYSTEM_READY: {
2444 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2445 nai.networkMonitor.systemReady = true;
2446 }
2447 break;
2448 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002449 }
2450 }
2451 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002452
2453 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002454 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002455 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002456 if (isTetheringSupported()) {
2457 return mTethering.tether(iface);
2458 } else {
2459 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2460 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002461 }
2462
2463 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002464 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002465 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002466
2467 if (isTetheringSupported()) {
2468 return mTethering.untether(iface);
2469 } else {
2470 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2471 }
2472 }
2473
2474 // javadoc from interface
2475 public int getLastTetherError(String iface) {
2476 enforceTetherAccessPermission();
2477
2478 if (isTetheringSupported()) {
2479 return mTethering.getLastTetherError(iface);
2480 } else {
2481 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2482 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002483 }
2484
2485 // TODO - proper iface API for selection by property, inspection, etc
2486 public String[] getTetherableUsbRegexs() {
2487 enforceTetherAccessPermission();
2488 if (isTetheringSupported()) {
2489 return mTethering.getTetherableUsbRegexs();
2490 } else {
2491 return new String[0];
2492 }
2493 }
2494
2495 public String[] getTetherableWifiRegexs() {
2496 enforceTetherAccessPermission();
2497 if (isTetheringSupported()) {
2498 return mTethering.getTetherableWifiRegexs();
2499 } else {
2500 return new String[0];
2501 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002502 }
2503
Danica Chang6fdd0c62010-08-11 14:54:43 -07002504 public String[] getTetherableBluetoothRegexs() {
2505 enforceTetherAccessPermission();
2506 if (isTetheringSupported()) {
2507 return mTethering.getTetherableBluetoothRegexs();
2508 } else {
2509 return new String[0];
2510 }
2511 }
2512
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002513 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002514 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002515 if (isTetheringSupported()) {
2516 return mTethering.setUsbTethering(enable);
2517 } else {
2518 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2519 }
2520 }
2521
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002522 // TODO - move iface listing, queries, etc to new module
2523 // javadoc from interface
2524 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002525 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002526 return mTethering.getTetherableIfaces();
2527 }
2528
2529 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002530 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002531 return mTethering.getTetheredIfaces();
2532 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002533
Robert Greenwalt5a735062010-03-02 17:25:02 -08002534 public String[] getTetheringErroredIfaces() {
2535 enforceTetherAccessPermission();
2536 return mTethering.getErroredIfaces();
2537 }
2538
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002539 public String[] getTetheredDhcpRanges() {
2540 enforceConnectivityInternalPermission();
2541 return mTethering.getTetheredDhcpRanges();
2542 }
2543
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002544 // if ro.tether.denied = true we default to no tethering
2545 // gservices could set the secure setting to 1 though to enable it on a build where it
2546 // had previously been turned off.
2547 public boolean isTetheringSupported() {
2548 enforceTetherAccessPermission();
2549 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002550 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002551 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2552 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002553 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2554 mTethering.getTetherableWifiRegexs().length != 0 ||
2555 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2556 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002557 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002558
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002559 // Called when we lose the default network and have no replacement yet.
2560 // This will automatically be cleared after X seconds or a new default network
2561 // becomes CONNECTED, whichever happens first. The timer is started by the
2562 // first caller and not restarted by subsequent callers.
2563 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002564 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002565 synchronized (this) {
2566 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002567 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002568 mNetTransitionWakeLock.acquire();
2569 mNetTransitionWakeLockCausedBy = forWhom;
2570 }
2571 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002572 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002573 mNetTransitionWakeLockTimeout);
2574 return;
2575 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002576
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002577 // 100 percent is full good, 0 is full bad.
2578 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002579 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002580 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002581 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002582 }
2583
Paul Jensenbfd17b72015-04-07 12:43:13 -04002584 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002585 enforceAccessPermission();
2586 enforceInternetPermission();
2587
Paul Jensenbfd17b72015-04-07 12:43:13 -04002588 NetworkAgentInfo nai;
2589 if (network == null) {
2590 nai = getDefaultNetwork();
2591 } else {
2592 nai = getNetworkAgentInfoForNetwork(network);
2593 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002594 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002595 // Revalidate if the app report does not match our current validated state.
2596 if (hasConnectivity == nai.lastValidated) return;
2597 final int uid = Binder.getCallingUid();
2598 if (DBG) {
2599 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2600 ") by " + uid);
2601 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002602 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002603 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2604 // which isn't meant to work on uncreated networks.
2605 if (!nai.created) return;
2606
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002607 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002608
2609 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2610 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002611 }
2612
Paul Jensene0bef712014-12-10 15:12:18 -05002613 public ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002614 // this information is already available as a world read/writable jvm property
2615 // so this API change wouldn't have a benifit. It also breaks the passing
2616 // of proxy info to all the JVMs.
2617 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002618 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002619 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002620 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2621 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002622 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002623 }
2624
Paul Jensene0bef712014-12-10 15:12:18 -05002625 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2626 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2627 // proxy is null then there is no proxy in place).
2628 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2629 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2630 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2631 proxy = null;
2632 }
2633 return proxy;
2634 }
2635
2636 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2637 // better for determining if a new proxy broadcast is necessary:
2638 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2639 // avoid unnecessary broadcasts.
2640 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2641 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2642 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2643 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2644 // all set.
2645 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2646 a = canonicalizeProxyInfo(a);
2647 b = canonicalizeProxyInfo(b);
2648 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2649 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2650 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2651 }
2652
Jason Monk207900c2014-04-25 15:00:09 -04002653 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002654 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002655
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002656 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002657 if (proxyProperties == mGlobalProxy) return;
2658 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2659 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2660
2661 String host = "";
2662 int port = 0;
2663 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002664 String pacFileUrl = "";
2665 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002666 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002667 if (!proxyProperties.isValid()) {
2668 if (DBG)
2669 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2670 return;
2671 }
Jason Monk207900c2014-04-25 15:00:09 -04002672 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002673 host = mGlobalProxy.getHost();
2674 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002675 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002676 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002677 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002678 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002679 } else {
2680 mGlobalProxy = null;
2681 }
2682 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002683 final long token = Binder.clearCallingIdentity();
2684 try {
2685 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2686 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2687 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2688 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002689 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002690 } finally {
2691 Binder.restoreCallingIdentity(token);
2692 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002693
Jason Monkcf0f97a2014-10-02 15:39:38 -04002694 if (mGlobalProxy == null) {
2695 proxyProperties = mDefaultProxy;
2696 }
2697 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002698 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002699 }
2700
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002701 private void loadGlobalProxy() {
2702 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002703 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2704 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2705 String exclList = Settings.Global.getString(res,
2706 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002707 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2708 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002709 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002710 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002711 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002712 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002713 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002714 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002715 if (!proxyProperties.isValid()) {
2716 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2717 return;
2718 }
2719
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002720 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002721 mGlobalProxy = proxyProperties;
2722 }
2723 }
2724 }
2725
Jason Monk207900c2014-04-25 15:00:09 -04002726 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002727 // this information is already available as a world read/writable jvm property
2728 // so this API change wouldn't have a benifit. It also breaks the passing
2729 // of proxy info to all the JVMs.
2730 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002731 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002732 return mGlobalProxy;
2733 }
2734 }
2735
Jason Monk207900c2014-04-25 15:00:09 -04002736 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002737 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002738 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002739 proxy = null;
2740 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002741 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002742 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002743 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002744 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002745 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2746 return;
2747 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002748
2749 // This call could be coming from the PacManager, containing the port of the local
2750 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2751 // global (to get the correct local port), and send a broadcast.
2752 // TODO: Switch PacManager to have its own message to send back rather than
2753 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002754 if ((mGlobalProxy != null) && (proxy != null)
2755 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002756 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2757 mGlobalProxy = proxy;
2758 sendProxyBroadcast(mGlobalProxy);
2759 return;
2760 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002761 mDefaultProxy = proxy;
2762
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002763 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002764 if (!mDefaultProxyDisabled) {
2765 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002766 }
2767 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002768 }
2769
Paul Jensene0bef712014-12-10 15:12:18 -05002770 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2771 // This method gets called when any network changes proxy, but the broadcast only ever contains
2772 // the default proxy (even if it hasn't changed).
2773 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2774 // world where an app might be bound to a non-default network.
2775 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2776 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2777 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2778
2779 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2780 sendProxyBroadcast(getDefaultProxy());
2781 }
2782 }
2783
Robert Greenwalt434203a2010-10-11 16:00:27 -07002784 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002785 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2786 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002787 if (!TextUtils.isEmpty(proxy)) {
2788 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002789 if (data.length == 0) {
2790 return;
2791 }
2792
Robert Greenwalt434203a2010-10-11 16:00:27 -07002793 String proxyHost = data[0];
2794 int proxyPort = 8080;
2795 if (data.length > 1) {
2796 try {
2797 proxyPort = Integer.parseInt(data[1]);
2798 } catch (NumberFormatException e) {
2799 return;
2800 }
2801 }
Jason Monk207900c2014-04-25 15:00:09 -04002802 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002803 setGlobalProxy(p);
2804 }
2805 }
2806
Jason Monk207900c2014-04-25 15:00:09 -04002807 private void sendProxyBroadcast(ProxyInfo proxy) {
2808 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002809 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002810 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002811 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002812 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2813 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002814 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002815 final long ident = Binder.clearCallingIdentity();
2816 try {
2817 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2818 } finally {
2819 Binder.restoreCallingIdentity(ident);
2820 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002821 }
2822
2823 private static class SettingsObserver extends ContentObserver {
2824 private int mWhat;
2825 private Handler mHandler;
2826 SettingsObserver(Handler handler, int what) {
2827 super(handler);
2828 mHandler = handler;
2829 mWhat = what;
2830 }
2831
2832 void observe(Context context) {
2833 ContentResolver resolver = context.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002834 resolver.registerContentObserver(Settings.Global.getUriFor(
2835 Settings.Global.HTTP_PROXY), false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002836 }
2837
2838 @Override
2839 public void onChange(boolean selfChange) {
2840 mHandler.obtainMessage(mWhat).sendToTarget();
2841 }
2842 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002843
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002844 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002845 Slog.d(TAG, s);
2846 }
2847
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002848 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002849 Slog.e(TAG, s);
2850 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002851
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07002852 private static <T> T checkNotNull(T value, String message) {
2853 if (value == null) {
2854 throw new NullPointerException(message);
2855 }
2856 return value;
2857 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002858
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002859 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08002860 * Prepare for a VPN application.
Jeff Davidson9a1da682014-11-11 13:52:58 -08002861 * Permissions are checked in Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002862 * @hide
2863 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002864 @Override
Chia-chi Yeh100155a2011-07-03 16:52:38 -07002865 public boolean prepareVpn(String oldPackage, String newPackage) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002866 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002867 int user = UserHandle.getUserId(Binder.getCallingUid());
2868 synchronized(mVpns) {
2869 return mVpns.get(user).prepare(oldPackage, newPackage);
2870 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002871 }
2872
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002873 /**
Jeff Davidson05542602014-08-11 14:07:27 -07002874 * Set whether the current VPN package has the ability to launch VPNs without
Jeff Davidson9a1da682014-11-11 13:52:58 -08002875 * user intervention. This method is used by system-privileged apps.
2876 * Permissions are checked in Vpn class.
Jeff Davidson05542602014-08-11 14:07:27 -07002877 * @hide
2878 */
2879 @Override
2880 public void setVpnPackageAuthorization(boolean authorized) {
2881 int user = UserHandle.getUserId(Binder.getCallingUid());
2882 synchronized(mVpns) {
2883 mVpns.get(user).setPackageAuthorization(authorized);
2884 }
2885 }
2886
2887 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002888 * Configure a TUN interface and return its file descriptor. Parameters
2889 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002890 * and not available in ConnectivityManager. Permissions are checked in
2891 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002892 * @hide
2893 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002894 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07002895 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002896 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002897 int user = UserHandle.getUserId(Binder.getCallingUid());
2898 synchronized(mVpns) {
2899 return mVpns.get(user).establish(config);
2900 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002901 }
2902
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002903 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07002904 * Start legacy VPN, controlling native daemons as needed. Creates a
2905 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002906 */
2907 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07002908 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002909 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07002910 final LinkProperties egress = getActiveLinkProperties();
2911 if (egress == null) {
2912 throw new IllegalStateException("Missing active network connection");
2913 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002914 int user = UserHandle.getUserId(Binder.getCallingUid());
2915 synchronized(mVpns) {
2916 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
2917 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002918 }
2919
2920 /**
2921 * Return the information of the ongoing legacy VPN. This method is used
2922 * by VpnSettings and not available in ConnectivityManager. Permissions
2923 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07002924 */
2925 @Override
2926 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002927 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07002928 int user = UserHandle.getUserId(Binder.getCallingUid());
2929 synchronized(mVpns) {
2930 return mVpns.get(user).getLegacyVpnInfo();
2931 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07002932 }
2933
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07002934 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08002935 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
2936 * and not available in ConnectivityManager.
2937 */
2938 @Override
2939 public VpnInfo[] getAllVpnInfo() {
2940 enforceConnectivityInternalPermission();
2941 if (mLockdownEnabled) {
2942 return new VpnInfo[0];
2943 }
2944
2945 synchronized(mVpns) {
2946 List<VpnInfo> infoList = new ArrayList<>();
2947 for (int i = 0; i < mVpns.size(); i++) {
2948 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
2949 if (info != null) {
2950 infoList.add(info);
2951 }
2952 }
2953 return infoList.toArray(new VpnInfo[infoList.size()]);
2954 }
2955 }
2956
2957 /**
2958 * @return VPN information for accounting, or null if we can't retrieve all required
2959 * information, e.g primary underlying iface.
2960 */
2961 @Nullable
2962 private VpnInfo createVpnInfo(Vpn vpn) {
2963 VpnInfo info = vpn.getVpnInfo();
2964 if (info == null) {
2965 return null;
2966 }
2967 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
2968 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
2969 // the underlyingNetworks list.
2970 if (underlyingNetworks == null) {
2971 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
2972 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
2973 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
2974 }
2975 } else if (underlyingNetworks.length > 0) {
2976 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
2977 if (linkProperties != null) {
2978 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
2979 }
2980 }
2981 return info.primaryUnderlyingIface == null ? null : info;
2982 }
2983
2984 /**
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07002985 * Returns the information of the ongoing VPN. This method is used by VpnDialogs and
2986 * not available in ConnectivityManager.
2987 * Permissions are checked in Vpn class.
2988 * @hide
2989 */
2990 @Override
2991 public VpnConfig getVpnConfig() {
2992 int user = UserHandle.getUserId(Binder.getCallingUid());
2993 synchronized(mVpns) {
2994 return mVpns.get(user).getVpnConfig();
2995 }
2996 }
2997
Jeff Sharkey69ddab42012-08-25 00:05:46 -07002998 @Override
2999 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003000 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3001 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3002 return false;
3003 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003004
3005 // Tear down existing lockdown if profile was removed
3006 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3007 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003008 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003009 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3010 return false;
3011 }
3012
3013 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3014 final VpnProfile profile = VpnProfile.decode(
3015 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003016 int user = UserHandle.getUserId(Binder.getCallingUid());
3017 synchronized(mVpns) {
3018 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3019 profile));
3020 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003021 } else {
3022 setLockdownTracker(null);
3023 }
3024
3025 return true;
3026 }
3027
3028 /**
3029 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3030 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3031 */
3032 private void setLockdownTracker(LockdownVpnTracker tracker) {
3033 // Shutdown any existing tracker
3034 final LockdownVpnTracker existing = mLockdownTracker;
3035 mLockdownTracker = null;
3036 if (existing != null) {
3037 existing.shutdown();
3038 }
3039
3040 try {
3041 if (tracker != null) {
3042 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003043 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003044 mLockdownTracker = tracker;
3045 mLockdownTracker.init();
3046 } else {
3047 mNetd.setFirewallEnabled(false);
3048 }
3049 } catch (RemoteException e) {
3050 // ignored; NMS lives inside system_server
3051 }
3052 }
3053
3054 private void throwIfLockdownEnabled() {
3055 if (mLockdownEnabled) {
3056 throw new IllegalStateException("Unavailable in lockdown mode");
3057 }
3058 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003059
Wink Savilleab9321d2013-06-29 21:10:57 -07003060 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003061 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003062 // TODO: Remove? Any reason to trigger a provisioning check?
3063 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003064 }
3065
3066 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
3067 private volatile boolean mIsNotificationVisible = false;
3068
Paul Jensen89e0f092014-09-15 15:59:36 -04003069 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003070 if (DBG) {
3071 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003072 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003073 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003074 Intent intent = new Intent(action);
3075 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003076 // Concatenate the range of types onto the range of NetIDs.
3077 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Paul Jensen89e0f092014-09-15 15:59:36 -04003078 setProvNotificationVisibleIntent(visible, id, networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003079 }
3080
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003081 /**
3082 * Show or hide network provisioning notificaitons.
3083 *
3084 * @param id an identifier that uniquely identifies this notification. This must match
3085 * between show and hide calls. We use the NetID value but for legacy callers
3086 * we concatenate the range of types with the range of NetIDs.
3087 */
3088 private void setProvNotificationVisibleIntent(boolean visible, int id, int networkType,
Paul Jensen869868be2014-05-15 10:33:05 -04003089 String extraInfo, PendingIntent intent) {
3090 if (DBG) {
3091 log("setProvNotificationVisibleIntent: E visible=" + visible + " networkType=" +
3092 networkType + " extraInfo=" + extraInfo);
3093 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003094
3095 Resources r = Resources.getSystem();
3096 NotificationManager notificationManager = (NotificationManager) mContext
3097 .getSystemService(Context.NOTIFICATION_SERVICE);
3098
3099 if (visible) {
3100 CharSequence title;
3101 CharSequence details;
3102 int icon;
Wink Saville948282b2013-08-29 08:55:16 -07003103 Notification notification = new Notification();
3104 switch (networkType) {
Wink Savilleab9321d2013-06-29 21:10:57 -07003105 case ConnectivityManager.TYPE_WIFI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003106 title = r.getString(R.string.wifi_available_sign_in, 0);
3107 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003108 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003109 icon = R.drawable.stat_notify_wifi_in_range;
3110 break;
3111 case ConnectivityManager.TYPE_MOBILE:
3112 case ConnectivityManager.TYPE_MOBILE_HIPRI:
Wink Savilleab9321d2013-06-29 21:10:57 -07003113 title = r.getString(R.string.network_available_sign_in, 0);
3114 // TODO: Change this to pull from NetworkInfo once a printable
3115 // name has been added to it
3116 details = mTelephonyManager.getNetworkOperatorName();
3117 icon = R.drawable.stat_notify_rssi_in_range;
3118 break;
3119 default:
Wink Savilleab9321d2013-06-29 21:10:57 -07003120 title = r.getString(R.string.network_available_sign_in, 0);
3121 details = r.getString(R.string.network_available_sign_in_detailed,
Wink Saville948282b2013-08-29 08:55:16 -07003122 extraInfo);
Wink Savilleab9321d2013-06-29 21:10:57 -07003123 icon = R.drawable.stat_notify_rssi_in_range;
3124 break;
3125 }
3126
Wink Savilleab9321d2013-06-29 21:10:57 -07003127 notification.when = 0;
3128 notification.icon = icon;
3129 notification.flags = Notification.FLAG_AUTO_CANCEL;
Wink Savilleab9321d2013-06-29 21:10:57 -07003130 notification.tickerText = title;
Alan Viverette4a357cd2015-03-18 18:37:18 -07003131 notification.color = mContext.getColor(
Selim Cinek255dd042014-08-19 22:29:02 +02003132 com.android.internal.R.color.system_notification_accent_color);
Wink Savilleab9321d2013-06-29 21:10:57 -07003133 notification.setLatestEventInfo(mContext, title, details, notification.contentIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003134 notification.contentIntent = intent;
Wink Savilleab9321d2013-06-29 21:10:57 -07003135
Wink Saville948282b2013-08-29 08:55:16 -07003136 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003137 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003138 } catch (NullPointerException npe) {
3139 loge("setNotificaitionVisible: visible notificationManager npe=" + npe);
3140 npe.printStackTrace();
3141 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003142 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003143 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003144 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003145 } catch (NullPointerException npe) {
3146 loge("setNotificaitionVisible: cancel notificationManager npe=" + npe);
3147 npe.printStackTrace();
3148 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003149 }
Wink Saville948282b2013-08-29 08:55:16 -07003150 mIsNotificationVisible = visible;
Wink Savilleab9321d2013-06-29 21:10:57 -07003151 }
3152
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003153 /** Location to an updatable file listing carrier provisioning urls.
3154 * An example:
3155 *
3156 * <?xml version="1.0" encoding="utf-8"?>
3157 * <provisioningUrls>
3158 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
3159 * <redirectedUrl mcc="310" mnc="4">http://www.google.com</redirectedUrl>
3160 * </provisioningUrls>
3161 */
3162 private static final String PROVISIONING_URL_PATH =
3163 "/data/misc/radio/provisioning_urls.xml";
3164 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003165
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003166 /** XML tag for root element. */
3167 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3168 /** XML tag for individual url */
3169 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
3170 /** XML tag for redirected url */
3171 private static final String TAG_REDIRECTED_URL = "redirectedUrl";
3172 /** XML attribute for mcc */
3173 private static final String ATTR_MCC = "mcc";
3174 /** XML attribute for mnc */
3175 private static final String ATTR_MNC = "mnc";
3176
3177 private static final int REDIRECTED_PROVISIONING = 1;
3178 private static final int PROVISIONING = 2;
3179
3180 private String getProvisioningUrlBaseFromFile(int type) {
3181 FileReader fileReader = null;
3182 XmlPullParser parser = null;
3183 Configuration config = mContext.getResources().getConfiguration();
3184 String tagType;
3185
3186 switch (type) {
3187 case PROVISIONING:
3188 tagType = TAG_PROVISIONING_URL;
3189 break;
3190 case REDIRECTED_PROVISIONING:
3191 tagType = TAG_REDIRECTED_URL;
3192 break;
3193 default:
3194 throw new RuntimeException("getProvisioningUrlBaseFromFile: Unexpected parameter " +
3195 type);
3196 }
3197
3198 try {
3199 fileReader = new FileReader(mProvisioningUrlFile);
3200 parser = Xml.newPullParser();
3201 parser.setInput(fileReader);
3202 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3203
3204 while (true) {
3205 XmlUtils.nextElement(parser);
3206
3207 String element = parser.getName();
3208 if (element == null) break;
3209
3210 if (element.equals(tagType)) {
3211 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3212 try {
3213 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3214 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3215 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3216 parser.next();
3217 if (parser.getEventType() == XmlPullParser.TEXT) {
3218 return parser.getText();
3219 }
3220 }
3221 }
3222 } catch (NumberFormatException e) {
3223 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3224 }
3225 }
3226 }
3227 return null;
3228 } catch (FileNotFoundException e) {
3229 loge("Carrier Provisioning Urls file not found");
3230 } catch (XmlPullParserException e) {
3231 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3232 } catch (IOException e) {
3233 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3234 } finally {
3235 if (fileReader != null) {
3236 try {
3237 fileReader.close();
3238 } catch (IOException e) {}
3239 }
3240 }
3241 return null;
3242 }
3243
Wink Saville42d4f082013-07-20 20:31:59 -07003244 @Override
3245 public String getMobileRedirectedProvisioningUrl() {
3246 enforceConnectivityInternalPermission();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003247 String url = getProvisioningUrlBaseFromFile(REDIRECTED_PROVISIONING);
3248 if (TextUtils.isEmpty(url)) {
3249 url = mContext.getResources().getString(R.string.mobile_redirected_provisioning_url);
3250 }
3251 return url;
3252 }
3253
Wink Saville42d4f082013-07-20 20:31:59 -07003254 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003255 public String getMobileProvisioningUrl() {
3256 enforceConnectivityInternalPermission();
3257 String url = getProvisioningUrlBaseFromFile(PROVISIONING);
3258 if (TextUtils.isEmpty(url)) {
3259 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003260 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003261 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003262 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003263 }
Wink Saville8cf35602013-07-10 23:00:07 -07003264 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003265 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003266 String phoneNumber = mTelephonyManager.getLine1Number();
3267 if (TextUtils.isEmpty(phoneNumber)) {
3268 phoneNumber = "0000000000";
3269 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003270 url = String.format(url,
3271 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3272 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003273 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003274 }
3275
Wink Savilleab9321d2013-06-29 21:10:57 -07003276 return url;
3277 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003278
Wink Saville948282b2013-08-29 08:55:16 -07003279 @Override
3280 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003281 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003282 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003283 final long ident = Binder.clearCallingIdentity();
3284 try {
3285 setProvNotificationVisible(visible, networkType, action);
3286 } finally {
3287 Binder.restoreCallingIdentity(ident);
3288 }
Wink Saville948282b2013-08-29 08:55:16 -07003289 }
Wink Saville7788c612013-08-29 14:57:08 -07003290
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003291 @Override
3292 public void setAirplaneMode(boolean enable) {
3293 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003294 final long ident = Binder.clearCallingIdentity();
3295 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003296 final ContentResolver cr = mContext.getContentResolver();
3297 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3298 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3299 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003300 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003301 } finally {
3302 Binder.restoreCallingIdentity(ident);
3303 }
3304 }
3305
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003306 private void onUserStart(int userId) {
3307 synchronized(mVpns) {
3308 Vpn userVpn = mVpns.get(userId);
3309 if (userVpn != null) {
3310 loge("Starting user already has a VPN");
3311 return;
3312 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003313 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003314 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003315 }
3316 }
3317
3318 private void onUserStop(int userId) {
3319 synchronized(mVpns) {
3320 Vpn userVpn = mVpns.get(userId);
3321 if (userVpn == null) {
3322 loge("Stopping user has no VPN");
3323 return;
3324 }
3325 mVpns.delete(userId);
3326 }
3327 }
3328
3329 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3330 @Override
3331 public void onReceive(Context context, Intent intent) {
3332 final String action = intent.getAction();
3333 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3334 if (userId == UserHandle.USER_NULL) return;
3335
3336 if (Intent.ACTION_USER_STARTING.equals(action)) {
3337 onUserStart(userId);
3338 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3339 onUserStop(userId);
3340 }
3341 }
3342 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003343
Robert Greenwalta67be032014-05-16 15:49:14 -07003344 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3345 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003346 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3347 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003348
Robert Greenwalta67be032014-05-16 15:49:14 -07003349 private static class NetworkFactoryInfo {
3350 public final String name;
3351 public final Messenger messenger;
3352 public final AsyncChannel asyncChannel;
3353
3354 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3355 this.name = name;
3356 this.messenger = messenger;
3357 this.asyncChannel = asyncChannel;
3358 }
3359 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003360
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003361 /**
3362 * Tracks info about the requester.
3363 * Also used to notice when the calling process dies so we can self-expire
3364 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003365 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3366 static final boolean REQUEST = true;
3367 static final boolean LISTEN = false;
3368
3369 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003370 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003371 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003372 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003373 final int mPid;
3374 final int mUid;
3375 final Messenger messenger;
3376 final boolean isRequest;
3377
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003378 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3379 request = r;
3380 mPendingIntent = pi;
3381 messenger = null;
3382 mBinder = null;
3383 mPid = getCallingPid();
3384 mUid = getCallingUid();
3385 this.isRequest = isRequest;
3386 }
3387
Robert Greenwalt9258c642014-03-26 16:47:06 -07003388 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3389 super();
3390 messenger = m;
3391 request = r;
3392 mBinder = binder;
3393 mPid = getCallingPid();
3394 mUid = getCallingUid();
3395 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003396 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003397
3398 try {
3399 mBinder.linkToDeath(this, 0);
3400 } catch (RemoteException e) {
3401 binderDied();
3402 }
3403 }
3404
3405 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003406 if (mBinder != null) {
3407 mBinder.unlinkToDeath(this, 0);
3408 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003409 }
3410
3411 public void binderDied() {
3412 log("ConnectivityService NetworkRequestInfo binderDied(" +
3413 request + ", " + mBinder + ")");
3414 releaseNetworkRequest(request);
3415 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003416
3417 public String toString() {
3418 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003419 mPid + " for " + request +
3420 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003421 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003422 }
3423
3424 @Override
3425 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003426 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003427 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003428 enforceNetworkRequestPermissions(networkCapabilities);
3429 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003430
Robert Greenwalt6078b502014-06-11 16:05:07 -07003431 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003432 throw new IllegalArgumentException("Bad timeout specified");
3433 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003434
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003435 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3436 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003437 if (DBG) log("requestNetwork for " + networkRequest);
3438 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3439 NetworkRequestInfo.REQUEST);
3440
3441 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003442 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003443 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003444 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003445 }
3446 return networkRequest;
3447 }
3448
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003449 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
3450 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED)
3451 == false) {
3452 enforceConnectivityInternalPermission();
3453 } else {
3454 enforceChangePermission();
3455 }
3456 }
3457
fenglub15e72b2015-03-20 11:29:56 -07003458 @Override
Robert Greenwalt2c22a912015-04-21 23:59:14 +00003459 public boolean requestBwUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003460 enforceAccessPermission();
3461 NetworkAgentInfo nai = null;
3462 if (network == null) {
3463 return false;
3464 }
3465 synchronized (mNetworkForNetId) {
3466 nai = mNetworkForNetId.get(network.netId);
3467 }
3468 if (nai != null) {
3469 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3470 return true;
3471 }
3472 return false;
3473 }
3474
3475
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003476 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3477 // if UID is restricted, don't allow them to bring up metered APNs
3478 if (networkCapabilities.hasCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED)
3479 == false) {
3480 final int uidRules;
3481 final int uid = Binder.getCallingUid();
3482 synchronized(mRulesLock) {
3483 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3484 }
3485 if ((uidRules & RULE_REJECT_METERED) != 0) {
3486 // we could silently fail or we can filter the available nets to only give
3487 // them those they have access to. Chose the more useful
3488 networkCapabilities.addCapability(NetworkCapabilities.NET_CAPABILITY_NOT_METERED);
3489 }
3490 }
3491 }
3492
Robert Greenwalt9258c642014-03-26 16:47:06 -07003493 @Override
3494 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3495 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003496 checkNotNull(operation, "PendingIntent cannot be null.");
3497 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3498 enforceNetworkRequestPermissions(networkCapabilities);
3499 enforceMeteredApnPolicy(networkCapabilities);
3500
3501 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3502 nextNetworkRequestId());
3503 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3504 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3505 NetworkRequestInfo.REQUEST);
3506 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3507 nri));
3508 return networkRequest;
3509 }
3510
Jeremy Joslin79294842014-12-03 17:15:28 -08003511 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3512 mHandler.sendMessageDelayed(
3513 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3514 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3515 }
3516
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003517 @Override
3518 public void releasePendingNetworkRequest(PendingIntent operation) {
3519 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3520 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003521 }
3522
3523 @Override
3524 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3525 Messenger messenger, IBinder binder) {
3526 enforceAccessPermission();
3527
3528 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003529 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003530 if (DBG) log("listenForNetwork for " + networkRequest);
3531 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3532 NetworkRequestInfo.LISTEN);
3533
3534 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3535 return networkRequest;
3536 }
3537
3538 @Override
3539 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3540 PendingIntent operation) {
3541 }
3542
3543 @Override
3544 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003545 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3546 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003547 }
3548
3549 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003550 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003551 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003552 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3553 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003554 }
3555
Robert Greenwalta67be032014-05-16 15:49:14 -07003556 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003557 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003558 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3559 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3560 }
3561
3562 @Override
3563 public void unregisterNetworkFactory(Messenger messenger) {
3564 enforceConnectivityInternalPermission();
3565 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3566 }
3567
3568 private void handleUnregisterNetworkFactory(Messenger messenger) {
3569 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3570 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003571 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003572 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003573 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003574 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003575 }
3576
Robert Greenwalt7b816022014-04-18 15:25:25 -07003577 /**
3578 * NetworkAgentInfo supporting a request by requestId.
3579 * These have already been vetted (their Capabilities satisfy the request)
3580 * and the are the highest scored network available.
3581 * the are keyed off the Requests requestId.
3582 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003583 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003584 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3585 new SparseArray<NetworkAgentInfo>();
3586
Paul Jensen31a94f42015-02-13 14:18:39 -05003587 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3588 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003589 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3590 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003591 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3592 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3593 // there may not be a strict 1:1 correlation between the two.
3594 @GuardedBy("mNetworkForNetId")
3595 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003596
Robert Greenwalt7b816022014-04-18 15:25:25 -07003597 // NetworkAgentInfo keyed off its connecting messenger
3598 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003599 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003600 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3601 new HashMap<Messenger, NetworkAgentInfo>();
3602
Paul Jensen2c311d62014-11-17 12:34:51 -05003603 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003604 private final NetworkRequest mDefaultRequest;
3605
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003606 private NetworkAgentInfo getDefaultNetwork() {
3607 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3608 }
3609
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003610 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003611 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003612 }
3613
Paul Jensen31a94f42015-02-13 14:18:39 -05003614 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003615 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003616 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003617 enforceConnectivityInternalPermission();
3618
Paul Jensen2c311d62014-11-17 12:34:51 -05003619 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3620 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003621 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003622 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3623 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3624 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003625 synchronized (this) {
3626 nai.networkMonitor.systemReady = mSystemReady;
3627 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003628 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003629 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003630 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003631 }
3632
3633 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3634 if (VDBG) log("Got NetworkAgent Messenger");
3635 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003636 synchronized (mNetworkForNetId) {
3637 mNetworkForNetId.put(na.network.netId, na);
3638 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003639 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3640 NetworkInfo networkInfo = na.networkInfo;
3641 na.networkInfo = null;
3642 updateNetworkInfo(na, networkInfo);
3643 }
3644
3645 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3646 LinkProperties newLp = networkAgent.linkProperties;
3647 int netId = networkAgent.network.netId;
3648
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003649 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3650 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003651 if (networkAgent.clatd != null) {
3652 networkAgent.clatd.fixupLinkProperties(oldLp);
3653 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003654
Paul Jensen992f2522014-04-28 10:33:11 -04003655 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003656 updateMtu(newLp, oldLp);
3657 // TODO - figure out what to do for clat
3658// for (LinkProperties lp : newLp.getStackedLinks()) {
3659// updateMtu(lp, null);
3660// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003661 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003662
3663 // TODO: deprecate and remove mDefaultDns when we can do so safely.
3664 // For now, use it only when the network has Internet access. http://b/18327075
3665 final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3666 NetworkCapabilities.NET_CAPABILITY_INTERNET);
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003667 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003668 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3669
Paul Jensen3b759822014-05-13 11:44:01 -04003670 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003671 if (isDefaultNetwork(networkAgent)) {
3672 handleApplyDefaultProxy(newLp.getHttpProxy());
3673 } else {
3674 updateProxy(newLp, oldLp, networkAgent);
3675 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003676 // TODO - move this check to cover the whole function
3677 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003678 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003679 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3680 }
Paul Jensen3b759822014-05-13 11:44:01 -04003681 }
3682
Lorenzo Colitti95439462014-10-09 13:44:48 +09003683 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3684 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3685 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003686
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003687 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003688 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3689 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003690 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003691 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003692 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003693 }
Paul Jensen992f2522014-04-28 10:33:11 -04003694
3695 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3696 CompareResult<String> interfaceDiff = new CompareResult<String>();
3697 if (oldLp != null) {
3698 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3699 } else if (newLp != null) {
3700 interfaceDiff.added = newLp.getAllInterfaceNames();
3701 }
3702 for (String iface : interfaceDiff.added) {
3703 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003704 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003705 mNetd.addInterfaceToNetwork(iface, netId);
3706 } catch (Exception e) {
3707 loge("Exception adding interface: " + e);
3708 }
3709 }
3710 for (String iface : interfaceDiff.removed) {
3711 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003712 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003713 mNetd.removeInterfaceFromNetwork(iface, netId);
3714 } catch (Exception e) {
3715 loge("Exception removing interface: " + e);
3716 }
3717 }
3718 }
3719
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003720 /**
3721 * Have netd update routes from oldLp to newLp.
3722 * @return true if routes changed between oldLp and newLp
3723 */
3724 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003725 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3726 if (oldLp != null) {
3727 routeDiff = oldLp.compareAllRoutes(newLp);
3728 } else if (newLp != null) {
3729 routeDiff.added = newLp.getAllRoutes();
3730 }
3731
3732 // add routes before removing old in case it helps with continuous connectivity
3733
3734 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3735 for (RouteInfo route : routeDiff.added) {
3736 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003737 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003738 try {
3739 mNetd.addRoute(netId, route);
3740 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003741 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3742 loge("Exception in addRoute for non-gateway: " + e);
3743 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003744 }
3745 }
3746 for (RouteInfo route : routeDiff.added) {
3747 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003748 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003749 try {
3750 mNetd.addRoute(netId, route);
3751 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003752 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3753 loge("Exception in addRoute for gateway: " + e);
3754 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003755 }
3756 }
3757
3758 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003759 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003760 try {
3761 mNetd.removeRoute(netId, route);
3762 } catch (Exception e) {
3763 loge("Exception in removeRoute: " + e);
3764 }
3765 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003766 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003767 }
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003768 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
3769 boolean flush, boolean useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003770 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Robert Greenwaltdf2b8782014-06-06 10:30:11 -07003771 Collection<InetAddress> dnses = newLp.getDnsServers();
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003772 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003773 dnses = new ArrayList();
3774 dnses.add(mDefaultDns);
3775 if (DBG) {
3776 loge("no dns provided for netId " + netId + ", so using defaults");
3777 }
3778 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003779 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003780 try {
3781 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
3782 newLp.getDomains());
3783 } catch (Exception e) {
3784 loge("Exception in setDnsServersForNetwork: " + e);
3785 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003786 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
3787 if (defaultNai != null && defaultNai.network.netId == netId) {
3788 setDefaultDnsSystemProperties(dnses);
3789 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07003790 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003791 } else if (flush) {
3792 try {
3793 mNetd.flushNetworkDnsCache(netId);
3794 } catch (Exception e) {
3795 loge("Exception in flushNetworkDnsCache: " + e);
3796 }
3797 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003798 }
3799 }
3800
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07003801 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
3802 int last = 0;
3803 for (InetAddress dns : dnses) {
3804 ++last;
3805 String key = "net.dns" + last;
3806 String value = dns.getHostAddress();
3807 SystemProperties.set(key, value);
3808 }
3809 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
3810 String key = "net.dns" + i;
3811 SystemProperties.set(key, "");
3812 }
3813 mNumDnsEntries = last;
3814 }
3815
Robert Greenwalt7b816022014-04-18 15:25:25 -07003816 private void updateCapabilities(NetworkAgentInfo networkAgent,
3817 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003818 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
3819 synchronized (networkAgent) {
3820 networkAgent.networkCapabilities = networkCapabilities;
3821 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08003822 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003823 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07003824 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003825 }
3826
Paul Jensenc8b9a742014-09-30 15:37:41 -04003827 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
3828 for (int i = 0; i < nai.networkRequests.size(); i++) {
3829 NetworkRequest nr = nai.networkRequests.valueAt(i);
3830 // Don't send listening requests to factories. b/17393458
3831 if (!isRequest(nr)) continue;
3832 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
3833 }
3834 }
3835
Robert Greenwalt7b816022014-04-18 15:25:25 -07003836 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
3837 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07003838 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07003839 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
3840 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003841 }
3842 }
3843
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003844 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
3845 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08003846 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003847 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08003848 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
3849 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08003850 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003851 sendIntent(nri.mPendingIntent, intent);
3852 }
3853 // else not handled
3854 }
3855
3856 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
3857 mPendingIntentWakeLock.acquire();
3858 try {
3859 if (DBG) log("Sending " + pendingIntent);
3860 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
3861 } catch (PendingIntent.CanceledException e) {
3862 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
3863 mPendingIntentWakeLock.release();
3864 releasePendingNetworkRequest(pendingIntent);
3865 }
3866 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
3867 }
3868
3869 @Override
3870 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
3871 String resultData, Bundle resultExtras) {
3872 if (DBG) log("Finished sending " + pendingIntent);
3873 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08003874 // Release with a delay so the receiving client has an opportunity to put in its
3875 // own request.
3876 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003877 }
3878
Robert Greenwalt9258c642014-03-26 16:47:06 -07003879 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003880 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003881 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003882 Bundle bundle = new Bundle();
3883 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
3884 new NetworkRequest(nri.request));
3885 Message msg = Message.obtain();
3886 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
3887 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
3888 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
3889 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003890 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003891 case ConnectivityManager.CALLBACK_LOSING: {
3892 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
3893 break;
3894 }
3895 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
3896 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
3897 new NetworkCapabilities(networkAgent.networkCapabilities));
3898 break;
3899 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003900 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003901 bundle.putParcelable(LinkProperties.class.getSimpleName(),
3902 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003903 break;
3904 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003905 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003906 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003907 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003908 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003909 if (VDBG) {
3910 log("sending notification " + notifyTypeToName(notificationType) +
3911 " for " + nri.request);
3912 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003913 nri.messenger.send(msg);
3914 } catch (RemoteException e) {
3915 // may occur naturally in the race of binder death.
3916 loge("RemoteException caught trying to send a callback msg for " + nri.request);
3917 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003918 }
3919
Paul Jensenc8b9a742014-09-30 15:37:41 -04003920 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
3921 for (int i = 0; i < nai.networkRequests.size(); i++) {
3922 NetworkRequest nr = nai.networkRequests.valueAt(i);
3923 // Ignore listening requests.
3924 if (!isRequest(nr)) continue;
3925 loge("Dead network still had at least " + nr);
3926 break;
3927 }
3928 nai.asyncChannel.disconnect();
3929 }
3930
Robert Greenwalt7b816022014-04-18 15:25:25 -07003931 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
3932 if (oldNetwork == null) {
3933 loge("Unknown NetworkAgentInfo in handleLingerComplete");
3934 return;
3935 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04003936 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
3937 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003938 }
3939
Paul Jensen27b02b72014-07-14 12:03:33 -04003940 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003941 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04003942 setupDataActivityTracking(newNetwork);
3943 try {
3944 mNetd.setDefaultNetId(newNetwork.network.netId);
3945 } catch (Exception e) {
3946 loge("Exception setting default network :" + e);
3947 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09003948 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04003949 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07003950 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05003951 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04003952 }
3953
Paul Jensen2161a8e2014-09-11 11:00:39 -04003954 // Handles a network appearing or improving its score.
3955 //
3956 // - Evaluates all current NetworkRequests that can be
3957 // satisfied by newNetwork, and reassigns to newNetwork
3958 // any such requests for which newNetwork is the best.
3959 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05003960 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04003961 // needed. A network is needed if it is the best network for
3962 // one or more NetworkRequests, or if it is a VPN.
3963 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003964 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05003965 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
3966 //
3967 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
3968 // networks that have no chance (i.e. even if validated)
3969 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04003970 //
3971 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
3972 // it does not remove NetworkRequests that other Networks could better satisfy.
3973 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
3974 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
3975 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003976 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05003977 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04003978 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05003979 // torn down if unneeded.
3980 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
3981 // performed to tear down unvalidated networks that have no chance (i.e. even if
3982 // validated) of becoming the highest scoring network.
3983 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
3984 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05003985 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09003986 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05003987 loge("ERROR: nascent network not validated.");
3988 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04003989 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003990 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05003991 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04003992 if (DBG) log("rematching " + newNetwork.name());
3993 // Find and migrate to this Network any NetworkRequests for
3994 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07003995 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04003996 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003997 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09003998 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
3999 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004000 if (DBG) {
4001 log("Network " + newNetwork.name() + " was already satisfying" +
4002 " request " + nri.request.requestId + ". No change.");
4003 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004004 keep = true;
4005 continue;
4006 }
4007
4008 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004009 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004010 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004011 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004012 // This is not a request, it's a callback listener.
4013 // Add it to newNetwork regardless of score.
Paul Jensen0311b2b2014-08-19 10:31:40 -04004014 newNetwork.addRequest(nri.request);
4015 continue;
4016 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004017
Robert Greenwalt7b816022014-04-18 15:25:25 -07004018 // next check if it's better than any current network we're using for
4019 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004020 if (VDBG) {
4021 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004022 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4023 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004024 }
4025 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004026 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004027 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004028 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004029 currentNetwork.networkRequests.remove(nri.request.requestId);
4030 currentNetwork.networkLingered.add(nri.request);
4031 affectedNetworks.add(currentNetwork);
4032 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004033 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004034 }
Paul Jensen573a0352015-01-08 10:49:34 -05004035 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004036 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Robert Greenwalt562cc542014-05-15 18:07:26 -07004037 newNetwork.addRequest(nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004038 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004039 // Tell NetworkFactories about the new score, so they can stop
4040 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004041 // TODO - this could get expensive if we have alot of requests for this
4042 // network. Think about if there is a way to reduce this. Push
4043 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004044 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004045 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004046 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004047 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004048 }
4049 }
4050 }
4051 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004052 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004053 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004054 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004055 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4056 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4057 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004058 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004059 }
4060 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004061 if (keep) {
4062 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004063 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004064 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004065 synchronized (ConnectivityService.this) {
4066 // have a new default network, release the transition wakelock in
4067 // a second if it's held. The second pause is to allow apps
4068 // to reconnect over the new network
4069 if (mNetTransitionWakeLock.isHeld()) {
4070 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4071 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4072 mNetTransitionWakeLockSerialNumber, 0),
4073 1000);
4074 }
4075 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004076 }
4077
4078 // do this after the default net is switched, but
4079 // before LegacyTypeTracker sends legacy broadcasts
4080 notifyNetworkCallbacks(newNetwork, ConnectivityManager.CALLBACK_AVAILABLE);
4081
4082 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004083 // Maintain the illusion: since the legacy API only
4084 // understands one network at a time, we must pretend
4085 // that the current default network disconnected before
4086 // the new one connected.
4087 if (oldDefaultNetwork != null) {
4088 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
4089 oldDefaultNetwork);
4090 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004091 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004092 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4093 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004094 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004095
4096 // Notify battery stats service about this network, both the normal
4097 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004098 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004099 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004100 final IBatteryStats bs = BatteryStatsService.getService();
4101 final int type = newNetwork.networkInfo.getType();
4102
4103 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4104 bs.noteNetworkInterfaceType(baseIface, type);
4105 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4106 final String stackedIface = stacked.getInterfaceName();
4107 bs.noteNetworkInterfaceType(stackedIface, type);
4108 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4109 }
4110 } catch (RemoteException ignored) {
4111 }
4112
Robert Greenwalt152ed372014-12-17 17:19:53 -08004113 // This has to happen after the notifyNetworkCallbacks as that tickles each
4114 // ConnectivityManager instance so that legacy requests correctly bind dns
4115 // requests to this network. The legacy users are listening for this bcast
4116 // and will generally do a dns request so they can ensureRouteToHost and if
4117 // they do that before the callbacks happen they'll use the default network.
4118 //
4119 // TODO: Is there still a race here? We send the broadcast
4120 // after sending the callback, but if the app can receive the
4121 // broadcast before the callback, it might still break.
4122 //
4123 // This *does* introduce a race where if the user uses the new api
4124 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4125 // they may get old info. Reverse this after the old startUsing api is removed.
4126 // This is on top of the multiple intent sequencing referenced in the todo above.
4127 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4128 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4129 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4130 // legacy type tracker filters out repeat adds
4131 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4132 }
4133 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004134
4135 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4136 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4137 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4138 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4139 if (newNetwork.isVPN()) {
4140 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4141 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004142 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004143 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004144 // validated (and get evaluated against peers, one losing here), or get reaped (see
4145 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4146 // network. Networks that have been up for a while and are validated should be torn
4147 // down via the lingering process so communication on that network is given time to
4148 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004149 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004150 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004151 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004152 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4153 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004154 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004155 if (DBG) log("Reaping " + nai.name());
4156 teardownUnneededNetwork(nai);
4157 }
4158 }
4159 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004160 }
4161
Paul Jensen2161a8e2014-09-11 11:00:39 -04004162 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4163 // being disconnected.
4164 // If only one Network's score or capabilities have been modified since the last time
4165 // this function was called, pass this Network in via the "changed" arugment, otherwise
4166 // pass null.
4167 // If only one Network has been changed but its NetworkCapabilities have not changed,
4168 // pass in the Network's score (from getCurrentScore()) prior to the change via
4169 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4170 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4171 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4172 // to avoid the slowness. It is not simply enough to process just "changed", for
4173 // example in the case where "changed"'s score decreases and another network should begin
4174 // satifying a NetworkRequest that "changed" currently satisfies.
4175
4176 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4177 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4178 // rematchNetworkAndRequests() handles.
4179 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004180 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4181 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004182 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004183 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4184 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4185 NascentState.NOT_JUST_VALIDATED,
4186 // Only reap the last time through the loop. Reaping before all rematching
4187 // is complete could incorrectly teardown a network that hasn't yet been
4188 // rematched.
4189 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4190 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004191 }
4192 }
4193 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004194
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004195 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004196 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004197 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004198 // For now only update icons for default connection.
4199 // TODO: Update WiFi and cellular icons separately. b/17237507
4200 if (!isDefaultNetwork(nai)) return;
4201
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004202 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004203 // Don't repeat publish.
4204 if (newInetCondition == mDefaultInetConditionPublished) return;
4205
4206 mDefaultInetConditionPublished = newInetCondition;
4207 sendInetConditionBroadcast(nai.networkInfo);
4208 }
4209
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004210 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4211 if (mLockdownTracker != null) {
4212 if (nai != null && nai.isVPN()) {
4213 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4214 } else {
4215 mLockdownTracker.onNetworkInfoChanged();
4216 }
4217 }
4218 }
4219
Robert Greenwalt7b816022014-04-18 15:25:25 -07004220 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4221 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004222 NetworkInfo oldInfo = null;
4223 synchronized (networkAgent) {
4224 oldInfo = networkAgent.networkInfo;
4225 networkAgent.networkInfo = newInfo;
4226 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004227 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004228
4229 if (oldInfo != null && oldInfo.getState() == state) {
4230 if (VDBG) log("ignoring duplicate network state non-change");
4231 return;
4232 }
4233 if (DBG) {
4234 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4235 (oldInfo == null ? "null" : oldInfo.getState()) +
4236 " to " + state);
4237 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004238
Paul Jenseneec75412014-08-04 12:21:19 -04004239 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004240 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004241 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004242 if (networkAgent.isVPN()) {
4243 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004244 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4245 (networkAgent.networkMisc == null ||
4246 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004247 } else {
4248 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4249 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004250 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004251 loge("Error creating network " + networkAgent.network.netId + ": "
4252 + e.getMessage());
4253 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004254 }
Paul Jenseneec75412014-08-04 12:21:19 -04004255 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004256 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004257 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004258
Paul Jensenca8f16a2014-05-09 12:47:55 -04004259 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004260 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004261
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004262 if (networkAgent.isVPN()) {
4263 // Temporarily disable the default proxy (not global).
4264 synchronized (mProxyLock) {
4265 if (!mDefaultProxyDisabled) {
4266 mDefaultProxyDisabled = true;
4267 if (mGlobalProxy == null && mDefaultProxy != null) {
4268 sendProxyBroadcast(null);
4269 }
4270 }
4271 }
4272 // TODO: support proxy per network.
4273 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004274
Paul Jensen2161a8e2014-09-11 11:00:39 -04004275 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004276 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4277 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004278
4279 // This has to happen after matching the requests, because callbacks are just requests.
4280 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004281 } else if (state == NetworkInfo.State.DISCONNECTED ||
4282 state == NetworkInfo.State.SUSPENDED) {
4283 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004284 if (networkAgent.isVPN()) {
4285 synchronized (mProxyLock) {
4286 if (mDefaultProxyDisabled) {
4287 mDefaultProxyDisabled = false;
4288 if (mGlobalProxy == null && mDefaultProxy != null) {
4289 sendProxyBroadcast(mDefaultProxy);
4290 }
4291 }
4292 }
4293 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004294 }
4295 }
4296
Robert Greenwaltac96c522014-06-03 16:43:57 -07004297 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4298 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004299 if (score < 0) {
4300 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4301 "). Bumping score to min of 0");
4302 score = 0;
4303 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004304
Paul Jensen2161a8e2014-09-11 11:00:39 -04004305 final int oldScore = nai.getCurrentScore();
4306 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004307
Paul Jensen57a767f2014-11-19 13:01:46 -05004308 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004309
Paul Jensenc8b9a742014-09-30 15:37:41 -04004310 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004311 }
4312
Robert Greenwalt9258c642014-03-26 16:47:06 -07004313 // notify only this one new request of the current state
4314 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4315 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4316 // TODO - read state from monitor to decide what to send.
4317// if (nai.networkMonitor.isLingering()) {
4318// notifyType = NetworkCallbacks.LOSING;
4319// } else if (nai.networkMonitor.isEvaluating()) {
4320// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4321// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004322 if (nri.mPendingIntent == null) {
4323 callCallbackForRequest(nri, nai, notifyType);
4324 } else {
4325 sendPendingIntentForRequest(nri, nai, notifyType);
4326 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004327 }
4328
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004329 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004330 // The NetworkInfo we actually send out has no bearing on the real
4331 // state of affairs. For example, if the default connection is mobile,
4332 // and a request for HIPRI has just gone away, we need to pretend that
4333 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4334 // the state to DISCONNECTED, even though the network is of type MOBILE
4335 // and is still connected.
4336 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4337 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004338 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004339 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004340 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004341 } else {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004342 info.setDetailedState(DetailedState.DISCONNECTED, null, info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004343 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4344 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4345 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4346 if (info.isFailover()) {
4347 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4348 nai.networkInfo.setFailover(false);
4349 }
4350 if (info.getReason() != null) {
4351 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4352 }
4353 if (info.getExtraInfo() != null) {
4354 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4355 }
4356 NetworkAgentInfo newDefaultAgent = null;
4357 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4358 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4359 if (newDefaultAgent != null) {
4360 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4361 newDefaultAgent.networkInfo);
4362 } else {
4363 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4364 }
4365 }
4366 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4367 mDefaultInetConditionPublished);
4368 final Intent immediateIntent = new Intent(intent);
4369 immediateIntent.setAction(CONNECTIVITY_ACTION_IMMEDIATE);
4370 sendStickyBroadcast(immediateIntent);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004371 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004372 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004373 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004374 }
4375 }
4376 }
4377
Robert Greenwalt7b816022014-04-18 15:25:25 -07004378 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004379 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004380 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004381 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4382 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4383 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004384 if (nri.mPendingIntent == null) {
4385 callCallbackForRequest(nri, networkAgent, notifyType);
4386 } else {
4387 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4388 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004389 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004390 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004391
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004392 private String notifyTypeToName(int notifyType) {
4393 switch (notifyType) {
4394 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4395 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4396 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4397 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4398 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4399 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4400 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4401 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4402 }
4403 return "UNKNOWN";
4404 }
4405
Jeff Sharkey69736342014-12-08 14:50:12 -08004406 /**
4407 * Notify other system services that set of active ifaces has changed.
4408 */
4409 private void notifyIfacesChanged() {
4410 try {
4411 mStatsService.forceUpdateIfaces();
4412 } catch (Exception ignored) {
4413 }
4414 }
4415
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004416 @Override
4417 public boolean addVpnAddress(String address, int prefixLength) {
4418 throwIfLockdownEnabled();
4419 int user = UserHandle.getUserId(Binder.getCallingUid());
4420 synchronized (mVpns) {
4421 return mVpns.get(user).addAddress(address, prefixLength);
4422 }
4423 }
4424
4425 @Override
4426 public boolean removeVpnAddress(String address, int prefixLength) {
4427 throwIfLockdownEnabled();
4428 int user = UserHandle.getUserId(Binder.getCallingUid());
4429 synchronized (mVpns) {
4430 return mVpns.get(user).removeAddress(address, prefixLength);
4431 }
4432 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004433
4434 @Override
4435 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4436 throwIfLockdownEnabled();
4437 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004438 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004439 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004440 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004441 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004442 if (success) {
4443 notifyIfacesChanged();
4444 }
4445 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004446 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004447}