blob: 84bcf66267e6c404ba5f4b5359221cb71e281b05 [file] [log] [blame]
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001/*
2 * Copyright (C) 2008 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17package com.android.server;
18
Haoyu Baidb3c8672012-06-20 14:29:57 -070019import static android.Manifest.permission.RECEIVE_DATA_ACTIVITY_CHANGE;
Jeff Sharkey961e3042011-08-29 16:02:57 -070020import static android.net.ConnectivityManager.CONNECTIVITY_ACTION;
Paul Jensen31a94f42015-02-13 14:18:39 -050021import static android.net.ConnectivityManager.NETID_UNSET;
Robert Greenwalt12e67352014-05-13 21:41:06 -070022import static android.net.ConnectivityManager.TYPE_NONE;
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -070023import static android.net.ConnectivityManager.TYPE_VPN;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -070024import static android.net.ConnectivityManager.getNetworkTypeName;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070025import static android.net.ConnectivityManager.isNetworkTypeValid;
Lorenzo Colitti8deb3412015-05-14 17:07:20 +090026import static android.net.NetworkCapabilities.NET_CAPABILITY_INTERNET;
27import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_METERED;
28import static android.net.NetworkCapabilities.NET_CAPABILITY_NOT_RESTRICTED;
29import static android.net.NetworkCapabilities.NET_CAPABILITY_VALIDATED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070030import static android.net.NetworkPolicyManager.RULE_ALLOW_ALL;
Amith Yamasani15e472352015-04-24 19:06:07 -070031import static android.net.NetworkPolicyManager.RULE_REJECT_ALL;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -070032import static android.net.NetworkPolicyManager.RULE_REJECT_METERED;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070033
Wenchao Tongf5ea3402015-03-04 13:26:38 -080034import android.annotation.Nullable;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -070035import android.app.AlarmManager;
Wink Savilleab9321d2013-06-29 21:10:57 -070036import android.app.Notification;
37import android.app.NotificationManager;
38import android.app.PendingIntent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070039import android.content.BroadcastReceiver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080040import android.content.ContentResolver;
41import android.content.Context;
42import android.content.Intent;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070043import android.content.IntentFilter;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080044import android.content.pm.PackageManager;
Robert Greenwalte182bfe2013-07-16 12:06:09 -070045import android.content.res.Configuration;
tk.mun148c7d02011-10-13 22:51:57 +090046import android.content.res.Resources;
Robert Greenwalt434203a2010-10-11 16:00:27 -070047import android.database.ContentObserver;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080048import android.net.ConnectivityManager;
49import android.net.IConnectivityManager;
Haoyu Baidb3c8672012-06-20 14:29:57 -070050import android.net.INetworkManagementEventObserver;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070051import android.net.INetworkPolicyListener;
52import android.net.INetworkPolicyManager;
Jeff Sharkey367d15a2011-09-22 14:59:51 -070053import android.net.INetworkStatsService;
Jaikumar Ganesh15c74392010-12-21 22:31:44 -080054import android.net.LinkProperties;
Robert Greenwalt0a46db52011-07-14 14:28:05 -070055import android.net.LinkProperties.CompareResult;
Robert Greenwalt9ba9c582014-03-19 17:56:12 -070056import android.net.Network;
Robert Greenwalt7b816022014-04-18 15:25:25 -070057import android.net.NetworkAgent;
Robert Greenwalte049c232014-04-11 15:53:27 -070058import android.net.NetworkCapabilities;
Robert Greenwaltd55a6b42011-03-25 13:09:25 -070059import android.net.NetworkConfig;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080060import android.net.NetworkInfo;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -070061import android.net.NetworkInfo.DetailedState;
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -070062import android.net.NetworkMisc;
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -070063import android.net.NetworkQuotaInfo;
Robert Greenwalte049c232014-04-11 15:53:27 -070064import android.net.NetworkRequest;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -070065import android.net.NetworkState;
Robert Greenwalt585ac0f2010-08-27 09:24:29 -070066import android.net.NetworkUtils;
Robert Greenwalt434203a2010-10-11 16:00:27 -070067import android.net.Proxy;
Jason Monk207900c2014-04-25 15:00:09 -040068import android.net.ProxyInfo;
Robert Greenwaltaa70f102011-04-28 14:28:50 -070069import android.net.RouteInfo;
Paul Jensen6bc2c2c2014-05-07 15:27:40 -040070import android.net.UidRange;
Jason Monk602b2322013-07-03 17:04:33 -040071import android.net.Uri;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080072import android.os.Binder;
Robert Greenwalta848c1c2014-09-30 16:50:07 -070073import android.os.Bundle;
Mike Lockwoodda8bb742011-05-28 13:24:04 -040074import android.os.FileUtils;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080075import android.os.Handler;
Wink Savillebb08caf2010-09-02 19:23:52 -070076import android.os.HandlerThread;
Robert Greenwalt42acef32009-08-12 16:08:25 -070077import android.os.IBinder;
Chia-chi Yehc9338302011-05-11 16:35:13 -070078import android.os.INetworkManagementService;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080079import android.os.Looper;
80import android.os.Message;
Robert Greenwalt665e1ae2012-08-21 19:27:00 -070081import android.os.Messenger;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -070082import android.os.ParcelFileDescriptor;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -070083import android.os.PowerManager;
Jeff Sharkeyf56e2432012-09-06 17:54:29 -070084import android.os.Process;
Robert Greenwalt42acef32009-08-12 16:08:25 -070085import android.os.RemoteException;
Robert Greenwalt5a0c3202012-05-22 16:07:46 -070086import android.os.SystemClock;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080087import android.os.SystemProperties;
Dianne Hackborn5ac72a22012-08-29 18:32:08 -070088import android.os.UserHandle;
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -040089import android.os.UserManager;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -080090import android.provider.Settings;
Jeff Sharkey69ddab42012-08-25 00:05:46 -070091import android.security.Credentials;
Jeff Sharkey82f85212012-08-24 11:17:25 -070092import android.security.KeyStore;
Wink Savilleab9321d2013-06-29 21:10:57 -070093import android.telephony.TelephonyManager;
Robert Greenwalt42acef32009-08-12 16:08:25 -070094import android.text.TextUtils;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -070095import android.util.LocalLog;
96import android.util.LocalLog.ReadOnlyLocalLog;
97import android.util.Pair;
Joe Onorato8a9b2202010-02-26 18:56:32 -080098import android.util.Slog;
Chad Brubaker4ca19e82013-06-14 11:16:51 -070099import android.util.SparseArray;
Paul Jensen31a94f42015-02-13 14:18:39 -0500100import android.util.SparseBooleanArray;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700101import android.util.SparseIntArray;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700102import android.util.Xml;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800103
Wink Savilleab9321d2013-06-29 21:10:57 -0700104import com.android.internal.R;
Jason Monk602b2322013-07-03 17:04:33 -0400105import com.android.internal.annotations.GuardedBy;
Paul Jensen67b0b072015-06-10 11:22:17 -0400106import com.android.internal.annotations.VisibleForTesting;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700107import com.android.internal.app.IBatteryStats;
Chia-chi Yeh2e467642011-07-04 03:23:12 -0700108import com.android.internal.net.LegacyVpnInfo;
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -0700109import com.android.internal.net.NetworkStatsFactory;
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -0700110import com.android.internal.net.VpnConfig;
Wenchao Tongf5ea3402015-03-04 13:26:38 -0800111import com.android.internal.net.VpnInfo;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700112import com.android.internal.net.VpnProfile;
Wink Savilleab9321d2013-06-29 21:10:57 -0700113import com.android.internal.telephony.DctConstants;
Robert Greenwalte049c232014-04-11 15:53:27 -0700114import com.android.internal.util.AsyncChannel;
Jeff Sharkeye6e61972012-09-14 13:47:51 -0700115import com.android.internal.util.IndentingPrintWriter;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700116import com.android.internal.util.XmlUtils;
Jeff Sharkey1059c3c2011-10-04 16:54:49 -0700117import com.android.server.am.BatteryStatsService;
John Spurlockbf991a82013-06-24 14:20:23 -0400118import com.android.server.connectivity.DataConnectionStats;
Erik Kline379747a2015-06-05 17:47:34 +0900119import com.android.server.connectivity.NetworkDiagnostics;
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900120import com.android.server.connectivity.Nat464Xlat;
Robert Greenwalt7b816022014-04-18 15:25:25 -0700121import com.android.server.connectivity.NetworkAgentInfo;
Paul Jensenca8f16a2014-05-09 12:47:55 -0400122import com.android.server.connectivity.NetworkMonitor;
Jason Monk602b2322013-07-03 17:04:33 -0400123import com.android.server.connectivity.PacManager;
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700124import com.android.server.connectivity.PermissionMonitor;
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800125import com.android.server.connectivity.Tethering;
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700126import com.android.server.connectivity.Vpn;
Jeff Sharkey216c1812012-08-05 14:29:23 -0700127import com.android.server.net.BaseNetworkObserver;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700128import com.android.server.net.LockdownVpnTracker;
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700129import com.google.android.collect.Lists;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700130import com.google.android.collect.Sets;
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700131
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700132import org.xmlpull.v1.XmlPullParser;
133import org.xmlpull.v1.XmlPullParserException;
134
135import java.io.File;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800136import java.io.FileDescriptor;
Robert Greenwalte182bfe2013-07-16 12:06:09 -0700137import java.io.FileNotFoundException;
138import java.io.FileReader;
Irfan Sheriffd649c122010-06-09 15:39:36 -0700139import java.io.IOException;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800140import java.io.PrintWriter;
Wink Savillec9822c52011-07-14 12:23:28 -0700141import java.net.Inet4Address;
Erik Kline41368502015-06-17 13:19:54 +0900142import java.net.Inet6Address;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700143import java.net.InetAddress;
144import java.net.UnknownHostException;
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700145import java.util.ArrayDeque;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700146import java.util.ArrayList;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700147import java.util.Arrays;
Robert Greenwalt47f69fe2010-06-15 15:43:39 -0700148import java.util.Collection;
Erik Kline41368502015-06-17 13:19:54 +0900149import java.util.Collections;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700150import java.util.HashMap;
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700151import java.util.HashSet;
Paul Jensenb10e37f2014-11-25 12:33:08 -0500152import java.util.Iterator;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700153import java.util.List;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700154import java.util.Map;
Robert Greenwalta848c1c2014-09-30 16:50:07 -0700155import java.util.Objects;
Wink Savilleab9321d2013-06-29 21:10:57 -0700156import java.util.concurrent.atomic.AtomicInteger;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800157
158/**
159 * @hide
160 */
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800161public class ConnectivityService extends IConnectivityManager.Stub
162 implements PendingIntent.OnFinished {
Jeff Sharkey899223b2012-08-04 15:24:58 -0700163 private static final String TAG = "ConnectivityService";
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800164
Robert Greenwalta7d31bf2014-07-23 12:42:47 -0700165 private static final boolean DBG = true;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -0700166 private static final boolean VDBG = false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800167
Jake Hamby786e71a2014-02-06 14:43:50 -0800168 private static final boolean LOGD_RULES = false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700169
Jeff Sharkey899223b2012-08-04 15:24:58 -0700170 // TODO: create better separation between radio types and network types
171
Robert Greenwalt42acef32009-08-12 16:08:25 -0700172 // how long to wait before switching back to a radio's default network
173 private static final int RESTORE_DEFAULT_NETWORK_DELAY = 1 * 60 * 1000;
174 // system property that can override the above value
175 private static final String NETWORK_RESTORE_DELAY_PROP_NAME =
176 "android.telephony.apn-restore";
177
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900178 // How long to wait before putting up a "This network doesn't have an Internet connection,
179 // connect anyway?" dialog after the user selects a network that doesn't validate.
180 private static final int PROMPT_UNVALIDATED_DELAY_MS = 8 * 1000;
181
Jeremy Joslin79294842014-12-03 17:15:28 -0800182 // How long to delay to removal of a pending intent based request.
183 // See Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS
184 private final int mReleasePendingIntentDelayMs;
185
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -0800186 private Tethering mTethering;
187
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700188 private final PermissionMonitor mPermissionMonitor;
189
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700190 private KeyStore mKeyStore;
Jeff Sharkey82f85212012-08-24 11:17:25 -0700191
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700192 @GuardedBy("mVpns")
193 private final SparseArray<Vpn> mVpns = new SparseArray<Vpn>();
Chia-chi Yehff3bdca2011-05-23 17:26:46 -0700194
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700195 private boolean mLockdownEnabled;
196 private LockdownVpnTracker mLockdownTracker;
197
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700198 /** Lock around {@link #mUidRules} and {@link #mMeteredIfaces}. */
199 private Object mRulesLock = new Object();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700200 /** Currently active network rules by UID. */
201 private SparseIntArray mUidRules = new SparseIntArray();
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700202 /** Set of ifaces that are costly. */
203 private HashSet<String> mMeteredIfaces = Sets.newHashSet();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700204
Erik Klineda4bfa82015-04-30 12:58:40 +0900205 final private Context mContext;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800206 private int mNetworkPreference;
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700207 // 0 is full bad, 100 is full good
Robert Greenwaltd7085fc2010-09-08 15:24:47 -0700208 private int mDefaultInetConditionPublished = 0;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800209
Robert Greenwalt0dd19a82013-02-11 15:25:10 -0800210 private int mNumDnsEntries;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800211
212 private boolean mTestMode;
Joe Onorato00092872010-09-01 21:18:22 -0700213 private static ConnectivityService sServiceInstance;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800214
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700215 private INetworkManagementService mNetd;
Jeff Sharkey69736342014-12-08 14:50:12 -0800216 private INetworkStatsService mStatsService;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700217 private INetworkPolicyManager mPolicyManager;
Robert Greenwalt59b1a4e2011-05-10 15:05:02 -0700218
Robert Greenwalt3f05bf42014-08-06 12:00:25 -0700219 private String mCurrentTcpBufferSizes;
220
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700221 private static final int ENABLED = 1;
222 private static final int DISABLED = 0;
223
Paul Jensenb10e37f2014-11-25 12:33:08 -0500224 // Arguments to rematchNetworkAndRequests()
225 private enum NascentState {
226 // Indicates a network was just validated for the first time. If the network is found to
227 // be unwanted (i.e. not satisfy any NetworkRequests) it is torn down.
228 JUST_VALIDATED,
229 // Indicates a network was not validated for the first time immediately prior to this call.
230 NOT_JUST_VALIDATED
231 };
232 private enum ReapUnvalidatedNetworks {
233 // Tear down unvalidated networks that have no chance (i.e. even if validated) of becoming
234 // the highest scoring network satisfying a NetworkRequest. This should be passed when it's
235 // known that there may be unvalidated networks that could potentially be reaped, and when
236 // all networks have been rematched against all NetworkRequests.
237 REAP,
238 // Don't reap unvalidated networks. This should be passed when it's known that there are
239 // no unvalidated networks that could potentially be reaped, and when some networks have
240 // not yet been rematched against all NetworkRequests.
241 DONT_REAP
242 };
243
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700244 /**
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700245 * used internally to change our mobile data enabled flag
246 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700247 private static final int EVENT_CHANGE_MOBILE_DATA_ENABLED = 2;
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -0700248
249 /**
Robert Greenwaltf3331232010-09-24 14:32:21 -0700250 * used internally to clear a wakelock when transitioning
Robert Greenwalt27711812014-06-25 16:45:57 -0700251 * from one net to another. Clear happens when we get a new
252 * network - EVENT_EXPIRE_NET_TRANSITION_WAKELOCK happens
253 * after a timeout if no network is found (typically 1 min).
Robert Greenwaltf3331232010-09-24 14:32:21 -0700254 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700255 private static final int EVENT_CLEAR_NET_TRANSITION_WAKELOCK = 8;
Robert Greenwaltf3331232010-09-24 14:32:21 -0700256
Robert Greenwalt434203a2010-10-11 16:00:27 -0700257 /**
258 * used internally to reload global proxy settings
259 */
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700260 private static final int EVENT_APPLY_GLOBAL_HTTP_PROXY = 9;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700261
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700262 /**
Wink Saville628b0852011-08-04 15:01:58 -0700263 * used internally to send a sticky broadcast delayed.
264 */
Chad Brubakerb98703e2013-07-23 17:44:41 -0700265 private static final int EVENT_SEND_STICKY_BROADCAST_INTENT = 11;
Wink Saville628b0852011-08-04 15:01:58 -0700266
Jeff Sharkey8e28b7d2011-08-19 02:24:24 -0700267 /**
Jason Monkdecd2952013-10-10 14:02:51 -0400268 * PAC manager has received new port.
269 */
270 private static final int EVENT_PROXY_HAS_CHANGED = 16;
271
Robert Greenwalte049c232014-04-11 15:53:27 -0700272 /**
273 * used internally when registering NetworkFactories
Robert Greenwalta67be032014-05-16 15:49:14 -0700274 * obj = NetworkFactoryInfo
Robert Greenwalte049c232014-04-11 15:53:27 -0700275 */
276 private static final int EVENT_REGISTER_NETWORK_FACTORY = 17;
277
Robert Greenwalt7b816022014-04-18 15:25:25 -0700278 /**
279 * used internally when registering NetworkAgents
280 * obj = Messenger
281 */
282 private static final int EVENT_REGISTER_NETWORK_AGENT = 18;
283
Robert Greenwalt9258c642014-03-26 16:47:06 -0700284 /**
285 * used to add a network request
286 * includes a NetworkRequestInfo
287 */
288 private static final int EVENT_REGISTER_NETWORK_REQUEST = 19;
289
290 /**
291 * indicates a timeout period is over - check if we had a network yet or not
292 * and if not, call the timeout calback (but leave the request live until they
293 * cancel it.
294 * includes a NetworkRequestInfo
295 */
296 private static final int EVENT_TIMEOUT_NETWORK_REQUEST = 20;
297
298 /**
299 * used to add a network listener - no request
300 * includes a NetworkRequestInfo
301 */
302 private static final int EVENT_REGISTER_NETWORK_LISTENER = 21;
303
304 /**
305 * used to remove a network request, either a listener or a real request
Paul Jensen7ecb42f2014-05-16 14:31:12 -0400306 * arg1 = UID of caller
307 * obj = NetworkRequest
Robert Greenwalt9258c642014-03-26 16:47:06 -0700308 */
309 private static final int EVENT_RELEASE_NETWORK_REQUEST = 22;
310
Robert Greenwalta67be032014-05-16 15:49:14 -0700311 /**
312 * used internally when registering NetworkFactories
313 * obj = Messenger
314 */
315 private static final int EVENT_UNREGISTER_NETWORK_FACTORY = 23;
316
Robert Greenwalt27711812014-06-25 16:45:57 -0700317 /**
318 * used internally to expire a wakelock when transitioning
319 * from one net to another. Expire happens when we fail to find
320 * a new network (typically after 1 minute) -
321 * EVENT_CLEAR_NET_TRANSITION_WAKELOCK happens if we had found
322 * a replacement network.
323 */
324 private static final int EVENT_EXPIRE_NET_TRANSITION_WAKELOCK = 24;
325
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -0700326 /**
327 * Used internally to indicate the system is ready.
328 */
329 private static final int EVENT_SYSTEM_READY = 25;
330
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800331 /**
332 * used to add a network request with a pending intent
Paul Jensen694f2b82015-06-17 14:15:39 -0400333 * obj = NetworkRequestInfo
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800334 */
335 private static final int EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT = 26;
336
337 /**
338 * used to remove a pending intent and its associated network request.
339 * arg1 = UID of caller
340 * obj = PendingIntent
341 */
342 private static final int EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT = 27;
343
Lorenzo Colittie03c3c72015-04-03 16:38:52 +0900344 /**
345 * used to specify whether a network should be used even if unvalidated.
346 * arg1 = whether to accept the network if it's unvalidated (1 or 0)
347 * arg2 = whether to remember this choice in the future (1 or 0)
348 * obj = network
349 */
350 private static final int EVENT_SET_ACCEPT_UNVALIDATED = 28;
351
352 /**
353 * used to ask the user to confirm a connection to an unvalidated network.
354 * obj = network
355 */
356 private static final int EVENT_PROMPT_UNVALIDATED = 29;
Robert Greenwalta67be032014-05-16 15:49:14 -0700357
Erik Klineda4bfa82015-04-30 12:58:40 +0900358 /**
359 * used internally to (re)configure mobile data always-on settings.
360 */
361 private static final int EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON = 30;
362
Paul Jensen694f2b82015-06-17 14:15:39 -0400363 /**
364 * used to add a network listener with a pending intent
365 * obj = NetworkRequestInfo
366 */
367 private static final int EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT = 31;
368
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700369 /** Handler used for internal events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700370 final private InternalHandler mHandler;
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700371 /** Handler used for incoming {@link NetworkStateTracker} events. */
Robert Greenwalt7b816022014-04-18 15:25:25 -0700372 final private NetworkStateTrackerHandler mTrackerHandler;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700373
Mike Lockwood0f79b542009-08-14 14:18:49 -0400374 private boolean mSystemReady;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -0800375 private Intent mInitialBroadcast;
Mike Lockwood0f79b542009-08-14 14:18:49 -0400376
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700377 private PowerManager.WakeLock mNetTransitionWakeLock;
378 private String mNetTransitionWakeLockCausedBy = "";
379 private int mNetTransitionWakeLockSerialNumber;
380 private int mNetTransitionWakeLockTimeout;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800381 private final PowerManager.WakeLock mPendingIntentWakeLock;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700382
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700383 private InetAddress mDefaultDns;
384
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700385 // used in DBG mode to track inet condition reports
386 private static final int INET_CONDITION_LOG_MAX_SIZE = 15;
387 private ArrayList mInetLog;
388
Robert Greenwalt434203a2010-10-11 16:00:27 -0700389 // track the current default http proxy - tell the world if we get a new one (real change)
Jason Monkcf0f97a2014-10-02 15:39:38 -0400390 private volatile ProxyInfo mDefaultProxy = null;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -0700391 private Object mProxyLock = new Object();
Chia-chi Yeh4c12a472011-10-03 15:34:04 -0700392 private boolean mDefaultProxyDisabled = false;
393
Robert Greenwalt434203a2010-10-11 16:00:27 -0700394 // track the global proxy.
Jason Monk207900c2014-04-25 15:00:09 -0400395 private ProxyInfo mGlobalProxy = null;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700396
Jason Monk602b2322013-07-03 17:04:33 -0400397 private PacManager mPacManager = null;
398
Erik Klineda4bfa82015-04-30 12:58:40 +0900399 final private SettingsObserver mSettingsObserver;
Robert Greenwalt434203a2010-10-11 16:00:27 -0700400
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400401 private UserManager mUserManager;
402
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700403 NetworkConfig[] mNetConfigs;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700404 int mNetworksDefined;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700405
Robert Greenwalt50393202011-06-21 17:26:14 -0700406 // the set of network types that can only be enabled by system/sig apps
407 List mProtectedNetworks;
408
John Spurlockbf991a82013-06-24 14:20:23 -0400409 private DataConnectionStats mDataConnectionStats;
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -0700410
Wink Savilleab9321d2013-06-29 21:10:57 -0700411 TelephonyManager mTelephonyManager;
John Spurlockbf991a82013-06-24 14:20:23 -0400412
Sreeram Ramachandran8f4d42c2014-09-05 16:06:34 -0700413 // sequence number for Networks; keep in sync with system/netd/NetworkController.cpp
414 private final static int MIN_NET_ID = 100; // some reserved marks
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700415 private final static int MAX_NET_ID = 65535;
416 private int mNextNetId = MIN_NET_ID;
417
Robert Greenwalt34524f02014-05-18 16:22:10 -0700418 // sequence number of NetworkRequests
419 private int mNextNetworkRequestId = 1;
420
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -0700421 // Array of <Network,ReadOnlyLocalLogs> tracking network validation and results
422 private static final int MAX_VALIDATION_LOGS = 10;
423 private final ArrayDeque<Pair<Network,ReadOnlyLocalLog>> mValidationLogs =
424 new ArrayDeque<Pair<Network,ReadOnlyLocalLog>>(MAX_VALIDATION_LOGS);
425
426 private void addValidationLogs(ReadOnlyLocalLog log, Network network) {
427 synchronized(mValidationLogs) {
428 while (mValidationLogs.size() >= MAX_VALIDATION_LOGS) {
429 mValidationLogs.removeLast();
430 }
431 mValidationLogs.addFirst(new Pair(network, log));
432 }
433 }
434
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700435 /**
436 * Implements support for the legacy "one network per network type" model.
437 *
438 * We used to have a static array of NetworkStateTrackers, one for each
439 * network type, but that doesn't work any more now that we can have,
440 * for example, more that one wifi network. This class stores all the
441 * NetworkAgentInfo objects that support a given type, but the legacy
442 * API will only see the first one.
443 *
444 * It serves two main purposes:
445 *
446 * 1. Provide information about "the network for a given type" (since this
447 * API only supports one).
448 * 2. Send legacy connectivity change broadcasts. Broadcasts are sent if
449 * the first network for a given type changes, or if the default network
450 * changes.
451 */
452 private class LegacyTypeTracker {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900453
454 private static final boolean DBG = true;
455 private static final boolean VDBG = false;
456 private static final String TAG = "CSLegacyTypeTracker";
457
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700458 /**
459 * Array of lists, one per legacy network type (e.g., TYPE_MOBILE_MMS).
460 * Each list holds references to all NetworkAgentInfos that are used to
461 * satisfy requests for that network type.
462 *
463 * This array is built out at startup such that an unsupported network
464 * doesn't get an ArrayList instance, making this a tristate:
465 * unsupported, supported but not active and active.
466 *
467 * The actual lists are populated when we scan the network types that
468 * are supported on this device.
469 */
470 private ArrayList<NetworkAgentInfo> mTypeLists[];
471
472 public LegacyTypeTracker() {
473 mTypeLists = (ArrayList<NetworkAgentInfo>[])
474 new ArrayList[ConnectivityManager.MAX_NETWORK_TYPE + 1];
475 }
476
477 public void addSupportedType(int type) {
478 if (mTypeLists[type] != null) {
479 throw new IllegalStateException(
480 "legacy list for type " + type + "already initialized");
481 }
482 mTypeLists[type] = new ArrayList<NetworkAgentInfo>();
483 }
484
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700485 public boolean isTypeSupported(int type) {
486 return isNetworkTypeValid(type) && mTypeLists[type] != null;
487 }
488
489 public NetworkAgentInfo getNetworkForType(int type) {
490 if (isTypeSupported(type) && !mTypeLists[type].isEmpty()) {
491 return mTypeLists[type].get(0);
492 } else {
493 return null;
494 }
495 }
496
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900497 private void maybeLogBroadcast(NetworkAgentInfo nai, boolean connected, int type,
498 boolean isDefaultNetwork) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900499 if (DBG) {
500 log("Sending " + (connected ? "connected" : "disconnected") +
501 " broadcast for type " + type + " " + nai.name() +
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900502 " isDefaultNetwork=" + isDefaultNetwork);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900503 }
504 }
505
506 /** Adds the given network to the specified legacy type list. */
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700507 public void add(int type, NetworkAgentInfo nai) {
508 if (!isTypeSupported(type)) {
509 return; // Invalid network type.
510 }
511 if (VDBG) log("Adding agent " + nai + " for legacy network type " + type);
512
513 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
514 if (list.contains(nai)) {
515 loge("Attempting to register duplicate agent for type " + type + ": " + nai);
516 return;
517 }
518
Lorenzo Colitti061f4152014-09-28 16:08:06 +0900519 list.add(nai);
520
521 // Send a broadcast if this is the first network of its type or if it's the default.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900522 final boolean isDefaultNetwork = isDefaultNetwork(nai);
523 if (list.size() == 1 || isDefaultNetwork) {
524 maybeLogBroadcast(nai, true, type, isDefaultNetwork);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700525 sendLegacyNetworkBroadcast(nai, true, type);
526 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700527 }
528
Lorenzo Colittia793a672014-07-31 23:20:17 +0900529 /** Removes the given network from the specified legacy type list. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900530 public void remove(int type, NetworkAgentInfo nai, boolean wasDefault) {
Lorenzo Colittia793a672014-07-31 23:20:17 +0900531 ArrayList<NetworkAgentInfo> list = mTypeLists[type];
532 if (list == null || list.isEmpty()) {
533 return;
534 }
535
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900536 final boolean wasFirstNetwork = list.get(0).equals(nai);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900537
538 if (!list.remove(nai)) {
539 return;
540 }
541
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900542 if (wasFirstNetwork || wasDefault) {
543 maybeLogBroadcast(nai, false, type, wasDefault);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900544 sendLegacyNetworkBroadcast(nai, false, type);
545 }
546
547 if (!list.isEmpty() && wasFirstNetwork) {
548 if (DBG) log("Other network available for type " + type +
549 ", sending connected broadcast");
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900550 final NetworkAgentInfo replacement = list.get(0);
551 maybeLogBroadcast(replacement, false, type, isDefaultNetwork(replacement));
552 sendLegacyNetworkBroadcast(replacement, false, type);
Lorenzo Colittia793a672014-07-31 23:20:17 +0900553 }
554 }
555
556 /** Removes the given network from all legacy type lists. */
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900557 public void remove(NetworkAgentInfo nai, boolean wasDefault) {
558 if (VDBG) log("Removing agent " + nai + " wasDefault=" + wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700559 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +0900560 remove(type, nai, wasDefault);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700561 }
562 }
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700563
Lorenzo Colittia793a672014-07-31 23:20:17 +0900564 private String naiToString(NetworkAgentInfo nai) {
565 String name = (nai != null) ? nai.name() : "null";
566 String state = (nai.networkInfo != null) ?
567 nai.networkInfo.getState() + "/" + nai.networkInfo.getDetailedState() :
568 "???/???";
569 return name + " " + state;
570 }
571
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700572 public void dump(IndentingPrintWriter pw) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900573 pw.println("mLegacyTypeTracker:");
574 pw.increaseIndent();
575 pw.print("Supported types:");
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700576 for (int type = 0; type < mTypeLists.length; type++) {
Lorenzo Colittie3805462015-06-03 11:18:24 +0900577 if (mTypeLists[type] != null) pw.print(" " + type);
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700578 }
Lorenzo Colittie3805462015-06-03 11:18:24 +0900579 pw.println();
580 pw.println("Current state:");
581 pw.increaseIndent();
582 for (int type = 0; type < mTypeLists.length; type++) {
583 if (mTypeLists[type] == null|| mTypeLists[type].size() == 0) continue;
584 for (NetworkAgentInfo nai : mTypeLists[type]) {
585 pw.println(type + " " + naiToString(nai));
586 }
587 }
588 pw.decreaseIndent();
589 pw.decreaseIndent();
590 pw.println();
Robert Greenwaltd49ac332014-07-30 16:31:24 -0700591 }
Lorenzo Colittia793a672014-07-31 23:20:17 +0900592
593 // This class needs its own log method because it has a different TAG.
594 private void log(String s) {
595 Slog.d(TAG, s);
596 }
597
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700598 }
599 private LegacyTypeTracker mLegacyTypeTracker = new LegacyTypeTracker();
600
Jeff Sharkey899223b2012-08-04 15:24:58 -0700601 public ConnectivityService(Context context, INetworkManagementService netManager,
Robert Greenwalt6831f1d2014-07-27 12:06:40 -0700602 INetworkStatsService statsService, INetworkPolicyManager policyManager) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800603 if (DBG) log("ConnectivityService starting up");
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800604
Erik Klineda4bfa82015-04-30 12:58:40 +0900605 mDefaultRequest = createInternetRequestForTransport(-1);
606 mNetworkRequests.put(mDefaultRequest, new NetworkRequestInfo(
607 null, mDefaultRequest, new Binder(), NetworkRequestInfo.REQUEST));
608
609 mDefaultMobileDataRequest = createInternetRequestForTransport(
610 NetworkCapabilities.TRANSPORT_CELLULAR);
Robert Greenwalte049c232014-04-11 15:53:27 -0700611
Wink Savillebb08caf2010-09-02 19:23:52 -0700612 HandlerThread handlerThread = new HandlerThread("ConnectivityServiceThread");
613 handlerThread.start();
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700614 mHandler = new InternalHandler(handlerThread.getLooper());
615 mTrackerHandler = new NetworkStateTrackerHandler(handlerThread.getLooper());
Wink Savillebb08caf2010-09-02 19:23:52 -0700616
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800617 // setup our unique device name
Robert Greenwalt733c6292010-12-06 09:30:17 -0800618 if (TextUtils.isEmpty(SystemProperties.get("net.hostname"))) {
619 String id = Settings.Secure.getString(context.getContentResolver(),
620 Settings.Secure.ANDROID_ID);
621 if (id != null && id.length() > 0) {
Irfan Sheriffa10a3ad2011-09-20 15:17:07 -0700622 String name = new String("android-").concat(id);
Robert Greenwalt733c6292010-12-06 09:30:17 -0800623 SystemProperties.set("net.hostname", name);
624 }
Robert Greenwaltde8383c2010-01-14 17:47:58 -0800625 }
626
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700627 // read our default dns server ip
Jeff Sharkey625239a2012-09-26 22:03:49 -0700628 String dns = Settings.Global.getString(context.getContentResolver(),
629 Settings.Global.DEFAULT_DNS_SERVER);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700630 if (dns == null || dns.length() == 0) {
631 dns = context.getResources().getString(
632 com.android.internal.R.string.config_default_dns_server);
633 }
634 try {
Robert Greenwalte5903732011-02-22 16:00:42 -0800635 mDefaultDns = NetworkUtils.numericToInetAddress(dns);
636 } catch (IllegalArgumentException e) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800637 loge("Error setting defaultDns using " + dns);
Robert Greenwalte90aa5e2010-09-01 11:34:05 -0700638 }
639
Jeremy Joslin79294842014-12-03 17:15:28 -0800640 mReleasePendingIntentDelayMs = Settings.Secure.getInt(context.getContentResolver(),
641 Settings.Secure.CONNECTIVITY_RELEASE_PENDING_INTENT_DELAY_MS, 5_000);
642
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700643 mContext = checkNotNull(context, "missing Context");
Jeff Sharkey899223b2012-08-04 15:24:58 -0700644 mNetd = checkNotNull(netManager, "missing INetworkManagementService");
Jeff Sharkey69736342014-12-08 14:50:12 -0800645 mStatsService = checkNotNull(statsService, "missing INetworkStatsService");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700646 mPolicyManager = checkNotNull(policyManager, "missing INetworkPolicyManager");
Jeff Sharkey82f85212012-08-24 11:17:25 -0700647 mKeyStore = KeyStore.getInstance();
Wink Savilleab9321d2013-06-29 21:10:57 -0700648 mTelephonyManager = (TelephonyManager) mContext.getSystemService(Context.TELEPHONY_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700649
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700650 try {
651 mPolicyManager.registerListener(mPolicyListener);
652 } catch (RemoteException e) {
653 // ouch, no rules updates means some processes may never get network
Robert Greenwalt58d4c592011-08-02 17:18:41 -0700654 loge("unable to register INetworkPolicyListener" + e.toString());
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700655 }
656
657 final PowerManager powerManager = (PowerManager) context.getSystemService(
658 Context.POWER_SERVICE);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700659 mNetTransitionWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
660 mNetTransitionWakeLockTimeout = mContext.getResources().getInteger(
661 com.android.internal.R.integer.config_networkTransitionTimeout);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -0800662 mPendingIntentWakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, TAG);
Robert Greenwalt14f2ef42010-06-15 12:19:37 -0700663
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700664 mNetConfigs = new NetworkConfig[ConnectivityManager.MAX_NETWORK_TYPE+1];
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700665
Wink Saville51f456f2013-04-23 14:26:51 -0700666 // TODO: What is the "correct" way to do determine if this is a wifi only device?
667 boolean wifiOnly = SystemProperties.getBoolean("ro.radio.noril", false);
668 log("wifiOnly=" + wifiOnly);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700669 String[] naStrings = context.getResources().getStringArray(
670 com.android.internal.R.array.networkAttributes);
671 for (String naString : naStrings) {
672 try {
Robert Greenwaltd55a6b42011-03-25 13:09:25 -0700673 NetworkConfig n = new NetworkConfig(naString);
Wink Saville5e56bc52013-07-29 15:00:57 -0700674 if (VDBG) log("naString=" + naString + " config=" + n);
Wink Saville975c8482011-04-07 14:23:45 -0700675 if (n.type > ConnectivityManager.MAX_NETWORK_TYPE) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800676 loge("Error in networkAttributes - ignoring attempt to define type " +
Wink Saville975c8482011-04-07 14:23:45 -0700677 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700678 continue;
Robert Greenwalt42acef32009-08-12 16:08:25 -0700679 }
Wink Saville51f456f2013-04-23 14:26:51 -0700680 if (wifiOnly && ConnectivityManager.isNetworkTypeMobile(n.type)) {
681 log("networkAttributes - ignoring mobile as this dev is wifiOnly " +
682 n.type);
683 continue;
684 }
Wink Saville975c8482011-04-07 14:23:45 -0700685 if (mNetConfigs[n.type] != null) {
Wink Savilleed9c02b2010-12-03 12:01:38 -0800686 loge("Error in networkAttributes - ignoring attempt to redefine type " +
Wink Saville975c8482011-04-07 14:23:45 -0700687 n.type);
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700688 continue;
689 }
Robert Greenwalt32aa65a2014-06-02 15:32:02 -0700690 mLegacyTypeTracker.addSupportedType(n.type);
Robert Greenwalt12e67352014-05-13 21:41:06 -0700691
Wink Saville975c8482011-04-07 14:23:45 -0700692 mNetConfigs[n.type] = n;
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700693 mNetworksDefined++;
694 } catch(Exception e) {
695 // ignore it - leave the entry null
Robert Greenwalt42acef32009-08-12 16:08:25 -0700696 }
697 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -0700698
699 // Forcibly add TYPE_VPN as a supported type, if it has not already been added via config.
700 if (mNetConfigs[TYPE_VPN] == null) {
701 // mNetConfigs is used only for "restore time", which isn't applicable to VPNs, so we
702 // don't need to add TYPE_VPN to mNetConfigs.
703 mLegacyTypeTracker.addSupportedType(TYPE_VPN);
704 mNetworksDefined++; // used only in the log() statement below.
705 }
706
Wink Saville5e56bc52013-07-29 15:00:57 -0700707 if (VDBG) log("mNetworksDefined=" + mNetworksDefined);
Robert Greenwalt42acef32009-08-12 16:08:25 -0700708
Robert Greenwalt50393202011-06-21 17:26:14 -0700709 mProtectedNetworks = new ArrayList<Integer>();
710 int[] protectedNetworks = context.getResources().getIntArray(
711 com.android.internal.R.array.config_protectedNetworks);
712 for (int p : protectedNetworks) {
713 if ((mNetConfigs[p] != null) && (mProtectedNetworks.contains(p) == false)) {
714 mProtectedNetworks.add(p);
715 } else {
716 if (DBG) loge("Ignoring protectedNetwork " + p);
717 }
718 }
719
Robert Greenwalt5154ae762009-10-30 14:17:42 -0700720 mTestMode = SystemProperties.get("cm.test.mode").equals("true")
721 && SystemProperties.get("ro.build.type").equals("eng");
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700722
Robert Greenwaltfab501672014-07-23 11:44:01 -0700723 mTethering = new Tethering(mContext, mNetd, statsService, mHandler.getLooper());
Robert Greenwaltc9d5fb72010-02-25 12:29:30 -0800724
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -0700725 mPermissionMonitor = new PermissionMonitor(mContext, mNetd);
726
Robert Greenwaltbfc76342013-07-19 14:30:49 -0700727 //set up the listener for user state for creating user VPNs
Chad Brubaker4ca19e82013-06-14 11:16:51 -0700728 IntentFilter intentFilter = new IntentFilter();
729 intentFilter.addAction(Intent.ACTION_USER_STARTING);
730 intentFilter.addAction(Intent.ACTION_USER_STOPPING);
731 mContext.registerReceiverAsUser(
732 mUserIntentReceiver, UserHandle.ALL, intentFilter, null, null);
Lorenzo Colitti13c9fde2013-03-15 04:22:37 +0900733
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700734 try {
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700735 mNetd.registerObserver(mTethering);
Jeff Sharkeyfb878b62012-07-26 18:32:30 -0700736 mNetd.registerObserver(mDataActivityObserver);
Chia-chi Yeh008ff392011-05-23 15:08:29 -0700737 } catch (RemoteException e) {
738 loge("Error registering observer :" + e);
739 }
740
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -0700741 if (DBG) {
742 mInetLog = new ArrayList();
743 }
Robert Greenwalt434203a2010-10-11 16:00:27 -0700744
Erik Klineda4bfa82015-04-30 12:58:40 +0900745 mSettingsObserver = new SettingsObserver(mContext, mHandler);
746 registerSettingsCallbacks();
Robert Greenwaltb7090d62010-12-02 11:31:00 -0800747
John Spurlockbf991a82013-06-24 14:20:23 -0400748 mDataConnectionStats = new DataConnectionStats(mContext);
749 mDataConnectionStats.startMonitoring();
Jason Monk602b2322013-07-03 17:04:33 -0400750
Jason Monkdecd2952013-10-10 14:02:51 -0400751 mPacManager = new PacManager(mContext, mHandler, EVENT_PROXY_HAS_CHANGED);
Wink Saville7788c612013-08-29 14:57:08 -0700752
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -0400753 mUserManager = (UserManager) context.getSystemService(Context.USER_SERVICE);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800754 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -0700755
Erik Klineda4bfa82015-04-30 12:58:40 +0900756 private NetworkRequest createInternetRequestForTransport(int transportType) {
757 NetworkCapabilities netCap = new NetworkCapabilities();
Lorenzo Colitti8deb3412015-05-14 17:07:20 +0900758 netCap.addCapability(NET_CAPABILITY_INTERNET);
759 netCap.addCapability(NET_CAPABILITY_NOT_RESTRICTED);
Erik Klineda4bfa82015-04-30 12:58:40 +0900760 if (transportType > -1) {
761 netCap.addTransportType(transportType);
762 }
763 return new NetworkRequest(netCap, TYPE_NONE, nextNetworkRequestId());
764 }
765
766 private void handleMobileDataAlwaysOn() {
767 final boolean enable = (Settings.Global.getInt(
768 mContext.getContentResolver(), Settings.Global.MOBILE_DATA_ALWAYS_ON, 0) == 1);
769 final boolean isEnabled = (mNetworkRequests.get(mDefaultMobileDataRequest) != null);
770 if (enable == isEnabled) {
771 return; // Nothing to do.
772 }
773
774 if (enable) {
775 handleRegisterNetworkRequest(new NetworkRequestInfo(
776 null, mDefaultMobileDataRequest, new Binder(), NetworkRequestInfo.REQUEST));
777 } else {
778 handleReleaseNetworkRequest(mDefaultMobileDataRequest, Process.SYSTEM_UID);
779 }
780 }
781
782 private void registerSettingsCallbacks() {
783 // Watch for global HTTP proxy changes.
784 mSettingsObserver.observe(
785 Settings.Global.getUriFor(Settings.Global.HTTP_PROXY),
786 EVENT_APPLY_GLOBAL_HTTP_PROXY);
787
788 // Watch for whether or not to keep mobile data always on.
789 mSettingsObserver.observe(
790 Settings.Global.getUriFor(Settings.Global.MOBILE_DATA_ALWAYS_ON),
791 EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON);
792 }
793
Robert Greenwalt34524f02014-05-18 16:22:10 -0700794 private synchronized int nextNetworkRequestId() {
795 return mNextNetworkRequestId++;
796 }
797
Paul Jensen67b0b072015-06-10 11:22:17 -0400798 @VisibleForTesting
799 protected int reserveNetId() {
Paul Jensen60061a62014-08-05 14:13:48 -0400800 synchronized (mNetworkForNetId) {
801 for (int i = MIN_NET_ID; i <= MAX_NET_ID; i++) {
802 int netId = mNextNetId;
803 if (++mNextNetId > MAX_NET_ID) mNextNetId = MIN_NET_ID;
804 // Make sure NetID unused. http://b/16815182
Paul Jensen31a94f42015-02-13 14:18:39 -0500805 if (!mNetIdInUse.get(netId)) {
806 mNetIdInUse.put(netId, true);
807 return netId;
Paul Jensen60061a62014-08-05 14:13:48 -0400808 }
809 }
810 }
811 throw new IllegalStateException("No free netIds");
Robert Greenwalt9ba9c582014-03-19 17:56:12 -0700812 }
813
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800814 private NetworkState getFilteredNetworkState(int networkType, int uid) {
815 NetworkInfo info = null;
816 LinkProperties lp = null;
817 NetworkCapabilities nc = null;
818 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800819 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800820
821 if (mLegacyTypeTracker.isTypeSupported(networkType)) {
822 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
823 if (nai != null) {
824 synchronized (nai) {
825 info = new NetworkInfo(nai.networkInfo);
826 lp = new LinkProperties(nai.linkProperties);
827 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400828 // Network objects are outwardly immutable so there is no point to duplicating.
829 // Duplicating also precludes sharing socket factories and connection pools.
830 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800831 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800832 }
833 info.setType(networkType);
834 } else {
835 info = new NetworkInfo(networkType, 0, getNetworkTypeName(networkType), "");
836 info.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED, null, null);
837 info.setIsAvailable(true);
838 lp = new LinkProperties();
839 nc = new NetworkCapabilities();
840 network = null;
841 }
842 info = getFilteredNetworkInfo(info, lp, uid);
843 }
844
Jeff Sharkey32566012014-12-02 18:30:14 -0800845 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400846 }
847
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800848 private NetworkAgentInfo getNetworkAgentInfoForNetwork(Network network) {
849 if (network == null) {
850 return null;
851 }
852 synchronized (mNetworkForNetId) {
853 return mNetworkForNetId.get(network.netId);
854 }
855 };
856
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900857 private Network[] getVpnUnderlyingNetworks(int uid) {
858 if (!mLockdownEnabled) {
859 int user = UserHandle.getUserId(uid);
860 synchronized (mVpns) {
861 Vpn vpn = mVpns.get(user);
862 if (vpn != null && vpn.appliesToUid(uid)) {
863 return vpn.getUnderlyingNetworks();
864 }
865 }
866 }
867 return null;
868 }
869
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800870 private NetworkState getUnfilteredActiveNetworkState(int uid) {
871 NetworkInfo info = null;
872 LinkProperties lp = null;
873 NetworkCapabilities nc = null;
874 Network network = null;
Jeff Sharkey32566012014-12-02 18:30:14 -0800875 String subscriberId = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800876
877 NetworkAgentInfo nai = mNetworkForRequestId.get(mDefaultRequest.requestId);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800878
Lorenzo Colittid6a79802015-02-05 13:57:17 +0900879 final Network[] networks = getVpnUnderlyingNetworks(uid);
880 if (networks != null) {
881 // getUnderlyingNetworks() returns:
882 // null => there was no VPN, or the VPN didn't specify anything, so we use the default.
883 // empty array => the VPN explicitly said "no default network".
884 // non-empty array => the VPN specified one or more default networks; we use the
885 // first one.
886 if (networks.length > 0) {
887 nai = getNetworkAgentInfoForNetwork(networks[0]);
888 } else {
889 nai = null;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -0800890 }
891 }
892
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800893 if (nai != null) {
894 synchronized (nai) {
895 info = new NetworkInfo(nai.networkInfo);
896 lp = new LinkProperties(nai.linkProperties);
897 nc = new NetworkCapabilities(nai.networkCapabilities);
Paul Jensene75b9e32015-04-06 11:54:53 -0400898 // Network objects are outwardly immutable so there is no point to duplicating.
899 // Duplicating also precludes sharing socket factories and connection pools.
900 network = nai.network;
Jeff Sharkey32566012014-12-02 18:30:14 -0800901 subscriberId = (nai.networkMisc != null) ? nai.networkMisc.subscriberId : null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800902 }
903 }
904
Jeff Sharkey32566012014-12-02 18:30:14 -0800905 return new NetworkState(info, lp, nc, network, subscriberId, null);
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400906 }
907
908 /**
909 * Check if UID should be blocked from using the network with the given LinkProperties.
910 */
911 private boolean isNetworkWithLinkPropertiesBlocked(LinkProperties lp, int uid) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700912 final boolean networkCostly;
913 final int uidRules;
Robert Greenwalt12e67352014-05-13 21:41:06 -0700914
Robert Greenwalt12e67352014-05-13 21:41:06 -0700915 final String iface = (lp == null ? "" : lp.getInterfaceName());
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700916 synchronized (mRulesLock) {
917 networkCostly = mMeteredIfaces.contains(iface);
918 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700919 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700920
Amith Yamasani15e472352015-04-24 19:06:07 -0700921 if ((uidRules & RULE_REJECT_ALL) != 0
922 || (networkCostly && (uidRules & RULE_REJECT_METERED) != 0)) {
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700923 return true;
924 }
925
926 // no restrictive rules; network is visible
927 return false;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700928 }
929
930 /**
Jeff Sharkeyfdfef572011-06-16 15:07:48 -0700931 * Return a filtered {@link NetworkInfo}, potentially marked
932 * {@link DetailedState#BLOCKED} based on
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800933 * {@link #isNetworkWithLinkPropertiesBlocked}.
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700934 */
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800935 private NetworkInfo getFilteredNetworkInfo(NetworkInfo info, LinkProperties lp, int uid) {
936 if (info != null && isNetworkWithLinkPropertiesBlocked(lp, uid)) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -0400937 // network is blocked; clone and override state
938 info = new NetworkInfo(info);
939 info.setDetailedState(DetailedState.BLOCKED, null, null);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900940 if (VDBG) {
Erik Kline338317e2015-01-19 16:19:09 +0900941 log("returning Blocked NetworkInfo for ifname=" +
942 lp.getInterfaceName() + ", uid=" + uid);
943 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700944 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800945 if (info != null && mLockdownTracker != null) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700946 info = mLockdownTracker.augmentNetworkInfo(info);
Lorenzo Colitti48a423f2015-06-05 10:57:29 +0900947 if (VDBG) log("returning Locked NetworkInfo");
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700948 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -0700949 return info;
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700950 }
951
952 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800953 * Return NetworkInfo for the active (i.e., connected) network interface.
954 * It is assumed that at most one network is active at a time. If more
955 * than one is active, it is indeterminate which will be returned.
Robert Greenwalt86e9e552009-07-16 17:21:39 -0700956 * @return the info for the active network, or {@code null} if none is
957 * active
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800958 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700959 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800960 public NetworkInfo getActiveNetworkInfo() {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700961 enforceAccessPermission();
962 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800963 NetworkState state = getUnfilteredActiveNetworkState(uid);
964 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -0800965 }
966
Paul Jensen31a94f42015-02-13 14:18:39 -0500967 @Override
968 public Network getActiveNetwork() {
969 enforceAccessPermission();
970 final int uid = Binder.getCallingUid();
971 final int user = UserHandle.getUserId(uid);
972 int vpnNetId = NETID_UNSET;
973 synchronized (mVpns) {
974 final Vpn vpn = mVpns.get(user);
975 if (vpn != null && vpn.appliesToUid(uid)) vpnNetId = vpn.getNetId();
976 }
977 NetworkAgentInfo nai;
978 if (vpnNetId != NETID_UNSET) {
979 synchronized (mNetworkForNetId) {
980 nai = mNetworkForNetId.get(vpnNetId);
981 }
982 if (nai != null) return nai.network;
983 }
984 nai = getDefaultNetwork();
985 if (nai != null && isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) nai = null;
986 return nai != null ? nai.network : null;
987 }
988
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700989 public NetworkInfo getActiveNetworkInfoUnfiltered() {
990 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800991 final int uid = Binder.getCallingUid();
992 NetworkState state = getUnfilteredActiveNetworkState(uid);
993 return state.networkInfo;
Jeff Sharkey69ddab42012-08-25 00:05:46 -0700994 }
995
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -0700996 @Override
997 public NetworkInfo getActiveNetworkInfoForUid(int uid) {
998 enforceConnectivityInternalPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -0800999 NetworkState state = getUnfilteredActiveNetworkState(uid);
1000 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001001 }
1002
1003 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001004 public NetworkInfo getNetworkInfo(int networkType) {
1005 enforceAccessPermission();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001006 final int uid = Binder.getCallingUid();
Lorenzo Colittid6a79802015-02-05 13:57:17 +09001007 if (getVpnUnderlyingNetworks(uid) != null) {
1008 // A VPN is active, so we may need to return one of its underlying networks. This
1009 // information is not available in LegacyTypeTracker, so we have to get it from
1010 // getUnfilteredActiveNetworkState.
1011 NetworkState state = getUnfilteredActiveNetworkState(uid);
1012 if (state.networkInfo != null && state.networkInfo.getType() == networkType) {
1013 return getFilteredNetworkInfo(state.networkInfo, state.linkProperties, uid);
1014 }
1015 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001016 NetworkState state = getFilteredNetworkState(networkType, uid);
1017 return state.networkInfo;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001018 }
1019
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001020 @Override
1021 public NetworkInfo getNetworkInfoForNetwork(Network network) {
1022 enforceAccessPermission();
1023 final int uid = Binder.getCallingUid();
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001024 NetworkInfo info = null;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001025 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1026 if (nai != null) {
1027 synchronized (nai) {
1028 info = new NetworkInfo(nai.networkInfo);
1029 info = getFilteredNetworkInfo(info, nai.linkProperties, uid);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001030 }
1031 }
1032 return info;
1033 }
1034
1035 @Override
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001036 public NetworkInfo[] getAllNetworkInfo() {
1037 enforceAccessPermission();
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001038 final ArrayList<NetworkInfo> result = Lists.newArrayList();
Paul Jensenf9ee0e52014-09-19 11:14:12 -04001039 for (int networkType = 0; networkType <= ConnectivityManager.MAX_NETWORK_TYPE;
1040 networkType++) {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001041 NetworkInfo info = getNetworkInfo(networkType);
1042 if (info != null) {
1043 result.add(info);
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001044 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001045 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001046 return result.toArray(new NetworkInfo[result.size()]);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001047 }
1048
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001049 @Override
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001050 public Network getNetworkForType(int networkType) {
1051 enforceAccessPermission();
1052 final int uid = Binder.getCallingUid();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001053 NetworkState state = getFilteredNetworkState(networkType, uid);
1054 if (!isNetworkWithLinkPropertiesBlocked(state.linkProperties, uid)) {
1055 return state.network;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001056 }
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001057 return null;
Lorenzo Colittib57edc52014-08-22 17:10:50 -07001058 }
1059
1060 @Override
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001061 public Network[] getAllNetworks() {
1062 enforceAccessPermission();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001063 synchronized (mNetworkForNetId) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001064 final Network[] result = new Network[mNetworkForNetId.size()];
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001065 for (int i = 0; i < mNetworkForNetId.size(); i++) {
Paul Jensene75b9e32015-04-06 11:54:53 -04001066 result[i] = mNetworkForNetId.valueAt(i).network;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001067 }
Paul Jensene75b9e32015-04-06 11:54:53 -04001068 return result;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001069 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001070 }
1071
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001072 @Override
1073 public NetworkCapabilities[] getDefaultNetworkCapabilitiesForUser(int userId) {
1074 // The basic principle is: if an app's traffic could possibly go over a
1075 // network, without the app doing anything multinetwork-specific,
1076 // (hence, by "default"), then include that network's capabilities in
1077 // the array.
1078 //
1079 // In the normal case, app traffic only goes over the system's default
1080 // network connection, so that's the only network returned.
1081 //
1082 // With a VPN in force, some app traffic may go into the VPN, and thus
1083 // over whatever underlying networks the VPN specifies, while other app
1084 // traffic may go over the system default network (e.g.: a split-tunnel
1085 // VPN, or an app disallowed by the VPN), so the set of networks
1086 // returned includes the VPN's underlying networks and the system
1087 // default.
1088 enforceAccessPermission();
1089
1090 HashMap<Network, NetworkCapabilities> result = new HashMap<Network, NetworkCapabilities>();
1091
1092 NetworkAgentInfo nai = getDefaultNetwork();
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001093 NetworkCapabilities nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001094 if (nc != null) {
1095 result.put(nai.network, nc);
1096 }
1097
1098 if (!mLockdownEnabled) {
1099 synchronized (mVpns) {
1100 Vpn vpn = mVpns.get(userId);
1101 if (vpn != null) {
1102 Network[] networks = vpn.getUnderlyingNetworks();
1103 if (networks != null) {
1104 for (Network network : networks) {
1105 nai = getNetworkAgentInfoForNetwork(network);
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001106 nc = getNetworkCapabilitiesInternal(nai);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001107 if (nc != null) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001108 result.put(network, nc);
Lorenzo Colitti403aa262014-11-28 11:21:30 +09001109 }
1110 }
1111 }
1112 }
1113 }
1114 }
1115
1116 NetworkCapabilities[] out = new NetworkCapabilities[result.size()];
1117 out = result.values().toArray(out);
1118 return out;
1119 }
1120
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001121 @Override
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001122 public boolean isNetworkSupported(int networkType) {
1123 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001124 return mLegacyTypeTracker.isTypeSupported(networkType);
Robert Greenwalt9b2886e2011-08-31 11:46:42 -07001125 }
1126
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001127 /**
1128 * Return LinkProperties for the active (i.e., connected) default
1129 * network interface. It is assumed that at most one default network
1130 * is active at a time. If more than one is active, it is indeterminate
1131 * which will be returned.
1132 * @return the ip properties for the active network, or {@code null} if
1133 * none is active
1134 */
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001135 @Override
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001136 public LinkProperties getActiveLinkProperties() {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001137 enforceAccessPermission();
1138 final int uid = Binder.getCallingUid();
1139 NetworkState state = getUnfilteredActiveNetworkState(uid);
1140 return state.linkProperties;
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001141 }
1142
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001143 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001144 public LinkProperties getLinkPropertiesForType(int networkType) {
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001145 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001146 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1147 if (nai != null) {
1148 synchronized (nai) {
1149 return new LinkProperties(nai.linkProperties);
1150 }
Robert Greenwaltd192dad2010-09-14 09:18:02 -07001151 }
1152 return null;
1153 }
1154
Robert Greenwalt12e67352014-05-13 21:41:06 -07001155 // TODO - this should be ALL networks
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001156 @Override
Robert Greenwalt9258c642014-03-26 16:47:06 -07001157 public LinkProperties getLinkProperties(Network network) {
1158 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001159 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001160 if (nai != null) {
1161 synchronized (nai) {
1162 return new LinkProperties(nai.linkProperties);
1163 }
1164 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001165 return null;
1166 }
1167
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001168 private NetworkCapabilities getNetworkCapabilitiesInternal(NetworkAgentInfo nai) {
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001169 if (nai != null) {
1170 synchronized (nai) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001171 if (nai.networkCapabilities != null) {
1172 return new NetworkCapabilities(nai.networkCapabilities);
Sanket Padawe7094d222015-05-01 16:55:00 -07001173 }
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001174 }
1175 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07001176 return null;
1177 }
1178
1179 @Override
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001180 public NetworkCapabilities getNetworkCapabilities(Network network) {
1181 enforceAccessPermission();
1182 return getNetworkCapabilitiesInternal(getNetworkAgentInfoForNetwork(network));
1183 }
1184
1185 @Override
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001186 public NetworkState[] getAllNetworkState() {
Jeff Sharkey32566012014-12-02 18:30:14 -08001187 // Require internal since we're handing out IMSI details
1188 enforceConnectivityInternalPermission();
1189
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001190 final ArrayList<NetworkState> result = Lists.newArrayList();
Jeff Sharkey32566012014-12-02 18:30:14 -08001191 for (Network network : getAllNetworks()) {
1192 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
1193 if (nai != null) {
1194 synchronized (nai) {
1195 final String subscriberId = (nai.networkMisc != null)
1196 ? nai.networkMisc.subscriberId : null;
1197 result.add(new NetworkState(nai.networkInfo, nai.linkProperties,
1198 nai.networkCapabilities, network, subscriberId, null));
1199 }
Jeff Sharkeyd2a45872011-05-28 20:56:34 -07001200 }
1201 }
1202 return result.toArray(new NetworkState[result.size()]);
1203 }
1204
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001205 @Override
1206 public NetworkQuotaInfo getActiveNetworkQuotaInfo() {
1207 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001208 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001209 final long token = Binder.clearCallingIdentity();
1210 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001211 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1212 if (state.networkInfo != null) {
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001213 try {
1214 return mPolicyManager.getNetworkQuotaInfo(state);
1215 } catch (RemoteException e) {
1216 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001217 }
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001218 return null;
1219 } finally {
1220 Binder.restoreCallingIdentity(token);
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001221 }
Jeff Sharkeyf0ceede2011-08-02 17:22:34 -07001222 }
1223
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001224 @Override
1225 public boolean isActiveNetworkMetered() {
1226 enforceAccessPermission();
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001227 final int uid = Binder.getCallingUid();
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001228 final long token = Binder.clearCallingIdentity();
1229 try {
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001230 return isActiveNetworkMeteredUnchecked(uid);
Jeff Sharkey15ec7d62012-04-17 12:23:40 -07001231 } finally {
1232 Binder.restoreCallingIdentity(token);
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001233 }
Jeff Sharkey9f7cbf02012-04-12 18:34:54 -07001234 }
1235
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001236 private boolean isActiveNetworkMeteredUnchecked(int uid) {
1237 final NetworkState state = getUnfilteredActiveNetworkState(uid);
1238 if (state.networkInfo != null) {
Jeff Sharkey5f4dafb2012-04-30 15:47:05 -07001239 try {
1240 return mPolicyManager.isNetworkMetered(state);
1241 } catch (RemoteException e) {
1242 }
1243 }
1244 return false;
1245 }
1246
Jeff Sharkey216c1812012-08-05 14:29:23 -07001247 private INetworkManagementEventObserver mDataActivityObserver = new BaseNetworkObserver() {
1248 @Override
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001249 public void interfaceClassDataActivityChanged(String label, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001250 int deviceType = Integer.parseInt(label);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001251 sendDataActivityBroadcast(deviceType, active, tsNanos);
Haoyu Baidb3c8672012-06-20 14:29:57 -07001252 }
Jeff Sharkey216c1812012-08-05 14:29:23 -07001253 };
Haoyu Baidb3c8672012-06-20 14:29:57 -07001254
Robert Greenwalt9c75d4a2009-09-27 17:27:04 -07001255 /**
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001256 * Ensure that a network route exists to deliver traffic to the specified
1257 * host via the specified network interface.
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001258 * @param networkType the type of the network over which traffic to the
1259 * specified host is to be routed
1260 * @param hostAddress the IP address of the host to which the route is
1261 * desired
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001262 * @return {@code true} on success, {@code false} on failure
1263 */
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001264 public boolean requestRouteToHostAddress(int networkType, byte[] hostAddress) {
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001265 enforceChangePermission();
Robert Greenwalt50393202011-06-21 17:26:14 -07001266 if (mProtectedNetworks.contains(networkType)) {
1267 enforceConnectivityInternalPermission();
1268 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001269
Chad Brubakerc0234532014-02-14 13:24:29 -08001270 InetAddress addr;
1271 try {
1272 addr = InetAddress.getByAddress(hostAddress);
1273 } catch (UnknownHostException e) {
1274 if (DBG) log("requestRouteToHostAddress got " + e.toString());
1275 return false;
1276 }
Robert Greenwalt50393202011-06-21 17:26:14 -07001277
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001278 if (!ConnectivityManager.isNetworkTypeValid(networkType)) {
Robert Greenwalt8beff952011-12-13 15:26:02 -08001279 if (DBG) log("requestRouteToHostAddress on invalid network: " + networkType);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001280 return false;
1281 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001282
1283 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
1284 if (nai == null) {
1285 if (mLegacyTypeTracker.isTypeSupported(networkType) == false) {
1286 if (DBG) log("requestRouteToHostAddress on unsupported network: " + networkType);
1287 } else {
1288 if (DBG) log("requestRouteToHostAddress on down network: " + networkType);
1289 }
1290 return false;
Ken Mixter151d3032013-11-07 22:08:24 -08001291 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001292
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001293 DetailedState netState;
1294 synchronized (nai) {
1295 netState = nai.networkInfo.getDetailedState();
1296 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07001297
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001298 if (netState != DetailedState.CONNECTED && netState != DetailedState.CAPTIVE_PORTAL_CHECK) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001299 if (VDBG) {
Wink Savilleab9321d2013-06-29 21:10:57 -07001300 log("requestRouteToHostAddress on down network "
1301 + "(" + networkType + ") - dropped"
Robert Greenwalt2d370702014-06-03 17:22:11 -07001302 + " netState=" + netState);
Robert Greenwalt8206ff32009-09-10 15:06:20 -07001303 }
1304 return false;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001305 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001306
Sreeram Ramachandran515350a2014-05-22 16:30:48 -07001307 final int uid = Binder.getCallingUid();
Robert Greenwalt8beff952011-12-13 15:26:02 -08001308 final long token = Binder.clearCallingIdentity();
Robert Greenwalt47f69fe2010-06-15 15:43:39 -07001309 try {
Paul Jensenbcc76d32014-07-11 08:17:29 -04001310 LinkProperties lp;
1311 int netId;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001312 synchronized (nai) {
1313 lp = nai.linkProperties;
1314 netId = nai.network.netId;
1315 }
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001316 boolean ok = addLegacyRouteToHost(lp, addr, netId, uid);
Wink Savilleab9321d2013-06-29 21:10:57 -07001317 if (DBG) log("requestRouteToHostAddress ok=" + ok);
1318 return ok;
Robert Greenwalt8beff952011-12-13 15:26:02 -08001319 } finally {
1320 Binder.restoreCallingIdentity(token);
1321 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001322 }
1323
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001324 private boolean addLegacyRouteToHost(LinkProperties lp, InetAddress addr, int netId, int uid) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001325 RouteInfo bestRoute = RouteInfo.selectBestRoute(lp.getAllRoutes(), addr);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001326 if (bestRoute == null) {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001327 bestRoute = RouteInfo.makeHostRoute(addr, lp.getInterfaceName());
Robert Greenwaltad55d352011-07-22 11:55:33 -07001328 } else {
Lorenzo Colittif83d90c2013-03-15 13:58:38 +09001329 String iface = bestRoute.getInterface();
Robert Greenwaltad55d352011-07-22 11:55:33 -07001330 if (bestRoute.getGateway().equals(addr)) {
1331 // if there is no better route, add the implied hostroute for our gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001332 bestRoute = RouteInfo.makeHostRoute(addr, iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001333 } else {
1334 // if we will connect to this through another route, add a direct route
1335 // to it's gateway
Lorenzo Colittie1671352013-03-08 12:30:44 -08001336 bestRoute = RouteInfo.makeHostRoute(addr, bestRoute.getGateway(), iface);
Robert Greenwaltad55d352011-07-22 11:55:33 -07001337 }
1338 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001339 if (DBG) log("Adding " + bestRoute + " for interface " + bestRoute.getInterface());
Sreeram Ramachandran03666c72014-07-19 23:21:46 -07001340 try {
1341 mNetd.addLegacyRouteForNetId(netId, bestRoute, uid);
1342 } catch (Exception e) {
1343 // never crash - catch them all
1344 if (DBG) loge("Exception trying to add a route: " + e);
Robert Greenwalt8beff952011-12-13 15:26:02 -08001345 return false;
1346 }
Robert Greenwalt0a46db52011-07-14 14:28:05 -07001347 return true;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001348 }
1349
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001350 private INetworkPolicyListener mPolicyListener = new INetworkPolicyListener.Stub() {
1351 @Override
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001352 public void onUidRulesChanged(int uid, int uidRules) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001353 // caller is NPMS, since we only register with them
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001354 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001355 log("onUidRulesChanged(uid=" + uid + ", uidRules=" + uidRules + ")");
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001356 }
1357
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001358 synchronized (mRulesLock) {
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001359 // skip update when we've already applied rules
1360 final int oldRules = mUidRules.get(uid, RULE_ALLOW_ALL);
1361 if (oldRules == uidRules) return;
1362
1363 mUidRules.put(uid, uidRules);
1364 }
1365
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001366 // TODO: notify UID when it has requested targeted updates
1367 }
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001368
1369 @Override
1370 public void onMeteredIfacesChanged(String[] meteredIfaces) {
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001371 // caller is NPMS, since we only register with them
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001372 if (LOGD_RULES) {
Robert Greenwalt58d4c592011-08-02 17:18:41 -07001373 log("onMeteredIfacesChanged(ifaces=" + Arrays.toString(meteredIfaces) + ")");
Jeff Sharkeyfdfef572011-06-16 15:07:48 -07001374 }
1375
1376 synchronized (mRulesLock) {
1377 mMeteredIfaces.clear();
1378 for (String iface : meteredIfaces) {
1379 mMeteredIfaces.add(iface);
1380 }
1381 }
1382 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001383
1384 @Override
1385 public void onRestrictBackgroundChanged(boolean restrictBackground) {
1386 // caller is NPMS, since we only register with them
1387 if (LOGD_RULES) {
1388 log("onRestrictBackgroundChanged(restrictBackground=" + restrictBackground + ")");
1389 }
Jeff Sharkey1f8ea2d2012-02-07 12:05:43 -08001390 }
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07001391 };
1392
Robin Lee3b3dd942015-05-12 18:14:58 +01001393 /**
1394 * Require that the caller is either in the same user or has appropriate permission to interact
1395 * across users.
1396 *
1397 * @param userId Target user for whatever operation the current IPC is supposed to perform.
1398 */
1399 private void enforceCrossUserPermission(int userId) {
1400 if (userId == UserHandle.getCallingUserId()) {
1401 // Not a cross-user call.
1402 return;
1403 }
1404 mContext.enforceCallingOrSelfPermission(
1405 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL,
1406 "ConnectivityService");
1407 }
1408
Paul Jensen7ccd3df2014-08-29 09:54:01 -04001409 private void enforceInternetPermission() {
1410 mContext.enforceCallingOrSelfPermission(
1411 android.Manifest.permission.INTERNET,
1412 "ConnectivityService");
1413 }
1414
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001415 private void enforceAccessPermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001416 mContext.enforceCallingOrSelfPermission(
1417 android.Manifest.permission.ACCESS_NETWORK_STATE,
1418 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001419 }
1420
1421 private void enforceChangePermission() {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001422 mContext.enforceCallingOrSelfPermission(
1423 android.Manifest.permission.CHANGE_NETWORK_STATE,
1424 "ConnectivityService");
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001425 }
1426
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001427 private void enforceTetherAccessPermission() {
1428 mContext.enforceCallingOrSelfPermission(
1429 android.Manifest.permission.ACCESS_NETWORK_STATE,
1430 "ConnectivityService");
1431 }
1432
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001433 private void enforceConnectivityInternalPermission() {
1434 mContext.enforceCallingOrSelfPermission(
1435 android.Manifest.permission.CONNECTIVITY_INTERNAL,
1436 "ConnectivityService");
1437 }
1438
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001439 public void sendConnectedBroadcast(NetworkInfo info) {
Robert Greenwalt5a6bdc42013-02-15 10:56:35 -08001440 enforceConnectivityInternalPermission();
Jeff Sharkey961e3042011-08-29 16:02:57 -07001441 sendGeneralBroadcast(info, CONNECTIVITY_ACTION);
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001442 }
1443
1444 private void sendInetConditionBroadcast(NetworkInfo info) {
1445 sendGeneralBroadcast(info, ConnectivityManager.INET_CONDITION_ACTION);
1446 }
1447
Wink Saville628b0852011-08-04 15:01:58 -07001448 private Intent makeGeneralIntent(NetworkInfo info, String bcastType) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001449 if (mLockdownTracker != null) {
1450 info = mLockdownTracker.augmentNetworkInfo(info);
1451 }
1452
Robert Greenwalt1e9aac22010-09-15 17:36:33 -07001453 Intent intent = new Intent(bcastType);
Irfan Sheriff9538bdd2012-09-20 09:32:41 -07001454 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, new NetworkInfo(info));
Jeff Sharkey75fbb4b2012-08-06 11:41:50 -07001455 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001456 if (info.isFailover()) {
1457 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
1458 info.setFailover(false);
1459 }
1460 if (info.getReason() != null) {
1461 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
1462 }
1463 if (info.getExtraInfo() != null) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001464 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO,
1465 info.getExtraInfo());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001466 }
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07001467 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION, mDefaultInetConditionPublished);
Wink Saville628b0852011-08-04 15:01:58 -07001468 return intent;
1469 }
1470
1471 private void sendGeneralBroadcast(NetworkInfo info, String bcastType) {
1472 sendStickyBroadcast(makeGeneralIntent(info, bcastType));
1473 }
1474
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001475 private void sendDataActivityBroadcast(int deviceType, boolean active, long tsNanos) {
Haoyu Baidb3c8672012-06-20 14:29:57 -07001476 Intent intent = new Intent(ConnectivityManager.ACTION_DATA_ACTIVITY_CHANGE);
1477 intent.putExtra(ConnectivityManager.EXTRA_DEVICE_TYPE, deviceType);
1478 intent.putExtra(ConnectivityManager.EXTRA_IS_ACTIVE, active);
Ashish Sharma0535a9f2014-03-12 18:42:23 -07001479 intent.putExtra(ConnectivityManager.EXTRA_REALTIME_NS, tsNanos);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001480 final long ident = Binder.clearCallingIdentity();
1481 try {
1482 mContext.sendOrderedBroadcastAsUser(intent, UserHandle.ALL,
1483 RECEIVE_DATA_ACTIVITY_CHANGE, null, null, 0, null, null);
1484 } finally {
1485 Binder.restoreCallingIdentity(ident);
1486 }
Haoyu Baidb3c8672012-06-20 14:29:57 -07001487 }
1488
Mike Lockwood0f79b542009-08-14 14:18:49 -04001489 private void sendStickyBroadcast(Intent intent) {
1490 synchronized(this) {
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001491 if (!mSystemReady) {
1492 mInitialBroadcast = new Intent(intent);
Mike Lockwood0f79b542009-08-14 14:18:49 -04001493 }
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001494 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001495 if (DBG) {
Jeff Sharkey961e3042011-08-29 16:02:57 -07001496 log("sendStickyBroadcast: action=" + intent.getAction());
Wink Saville628b0852011-08-04 15:01:58 -07001497 }
1498
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001499 final long ident = Binder.clearCallingIdentity();
Dianne Hackborn1e01d162014-12-04 17:46:42 -08001500 if (ConnectivityManager.CONNECTIVITY_ACTION.equals(intent.getAction())) {
1501 final IBatteryStats bs = BatteryStatsService.getService();
1502 try {
1503 NetworkInfo ni = intent.getParcelableExtra(
1504 ConnectivityManager.EXTRA_NETWORK_INFO);
1505 bs.noteConnectivityChanged(intent.getIntExtra(
1506 ConnectivityManager.EXTRA_NETWORK_TYPE, ConnectivityManager.TYPE_NONE),
1507 ni != null ? ni.getState().toString() : "?");
1508 } catch (RemoteException e) {
1509 }
1510 }
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001511 try {
1512 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
1513 } finally {
1514 Binder.restoreCallingIdentity(ident);
1515 }
Mike Lockwood0f79b542009-08-14 14:18:49 -04001516 }
1517 }
1518
1519 void systemReady() {
Wink Saville948282b2013-08-29 08:55:16 -07001520 loadGlobalProxy();
1521
Mike Lockwood0f79b542009-08-14 14:18:49 -04001522 synchronized(this) {
1523 mSystemReady = true;
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001524 if (mInitialBroadcast != null) {
Dianne Hackborn5ac72a22012-08-29 18:32:08 -07001525 mContext.sendStickyBroadcastAsUser(mInitialBroadcast, UserHandle.ALL);
Dianne Hackborn1c633fc2009-12-08 19:45:14 -08001526 mInitialBroadcast = null;
Mike Lockwood0f79b542009-08-14 14:18:49 -04001527 }
1528 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07001529 // load the global proxy at startup
1530 mHandler.sendMessage(mHandler.obtainMessage(EVENT_APPLY_GLOBAL_HTTP_PROXY));
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001531
1532 // Try bringing up tracker, but if KeyStore isn't ready yet, wait
1533 // for user to unlock device.
1534 if (!updateLockdownVpn()) {
1535 final IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
1536 mContext.registerReceiver(mUserPresentReceiver, filter);
1537 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001538
Erik Klineda4bfa82015-04-30 12:58:40 +09001539 // Configure whether mobile data is always on.
1540 mHandler.sendMessage(mHandler.obtainMessage(EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON));
1541
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07001542 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SYSTEM_READY));
Sreeram Ramachandrane4a05af2014-09-24 09:16:19 -07001543
1544 mPermissionMonitor.startMonitoring();
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001545 }
1546
Jeff Sharkey69ddab42012-08-25 00:05:46 -07001547 private BroadcastReceiver mUserPresentReceiver = new BroadcastReceiver() {
1548 @Override
1549 public void onReceive(Context context, Intent intent) {
1550 // Try creating lockdown tracker, since user present usually means
1551 // unlocked keystore.
1552 if (updateLockdownVpn()) {
1553 mContext.unregisterReceiver(this);
1554 }
1555 }
1556 };
1557
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001558 /**
Robert Greenwalt7b816022014-04-18 15:25:25 -07001559 * Setup data activity tracking for the given network.
Haoyu Bai04124232012-06-28 15:26:19 -07001560 *
1561 * Every {@code setupDataActivityTracking} should be paired with a
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001562 * {@link #removeDataActivityTracking} for cleanup.
Haoyu Bai04124232012-06-28 15:26:19 -07001563 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001564 private void setupDataActivityTracking(NetworkAgentInfo networkAgent) {
1565 final String iface = networkAgent.linkProperties.getInterfaceName();
Haoyu Bai04124232012-06-28 15:26:19 -07001566
1567 final int timeout;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001568 int type = ConnectivityManager.TYPE_NONE;
Haoyu Bai04124232012-06-28 15:26:19 -07001569
Robert Greenwalt7b816022014-04-18 15:25:25 -07001570 if (networkAgent.networkCapabilities.hasTransport(
1571 NetworkCapabilities.TRANSPORT_CELLULAR)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001572 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1573 Settings.Global.DATA_ACTIVITY_TIMEOUT_MOBILE,
Dianne Hackborne13c4c02014-02-11 17:18:35 -08001574 5);
Haoyu Bai04124232012-06-28 15:26:19 -07001575 type = ConnectivityManager.TYPE_MOBILE;
Robert Greenwalt7b816022014-04-18 15:25:25 -07001576 } else if (networkAgent.networkCapabilities.hasTransport(
1577 NetworkCapabilities.TRANSPORT_WIFI)) {
Jeff Brownbf6f6f92012-09-25 15:03:20 -07001578 timeout = Settings.Global.getInt(mContext.getContentResolver(),
1579 Settings.Global.DATA_ACTIVITY_TIMEOUT_WIFI,
Adam Lesinskie08af192015-03-25 16:42:59 -07001580 5);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001581 type = ConnectivityManager.TYPE_WIFI;
Haoyu Bai04124232012-06-28 15:26:19 -07001582 } else {
1583 // do not track any other networks
1584 timeout = 0;
1585 }
1586
Robert Greenwalt7b816022014-04-18 15:25:25 -07001587 if (timeout > 0 && iface != null && type != ConnectivityManager.TYPE_NONE) {
Haoyu Bai04124232012-06-28 15:26:19 -07001588 try {
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001589 mNetd.addIdleTimer(iface, timeout, type);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001590 } catch (Exception e) {
1591 // You shall not crash!
1592 loge("Exception in setupDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001593 }
1594 }
1595 }
1596
1597 /**
1598 * Remove data activity tracking when network disconnects.
1599 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001600 private void removeDataActivityTracking(NetworkAgentInfo networkAgent) {
1601 final String iface = networkAgent.linkProperties.getInterfaceName();
1602 final NetworkCapabilities caps = networkAgent.networkCapabilities;
Haoyu Bai04124232012-06-28 15:26:19 -07001603
Robert Greenwalt7b816022014-04-18 15:25:25 -07001604 if (iface != null && (caps.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) ||
1605 caps.hasTransport(NetworkCapabilities.TRANSPORT_WIFI))) {
Haoyu Bai04124232012-06-28 15:26:19 -07001606 try {
1607 // the call fails silently if no idletimer setup for this interface
1608 mNetd.removeIdleTimer(iface);
Robert Greenwaltd9cb2f32014-03-19 14:26:28 -07001609 } catch (Exception e) {
1610 loge("Exception in removeDataActivityTracking " + e);
Haoyu Bai04124232012-06-28 15:26:19 -07001611 }
1612 }
1613 }
1614
1615 /**
sy.yun9d9b74a2013-09-02 05:24:09 +09001616 * Reads the network specific MTU size from reources.
1617 * and set it on it's iface.
1618 */
Robert Greenwalt7b816022014-04-18 15:25:25 -07001619 private void updateMtu(LinkProperties newLp, LinkProperties oldLp) {
1620 final String iface = newLp.getInterfaceName();
1621 final int mtu = newLp.getMtu();
1622 if (oldLp != null && newLp.isIdenticalMtu(oldLp)) {
1623 if (VDBG) log("identical MTU - not setting");
1624 return;
1625 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001626
Robert Greenwalt43074032014-08-15 17:53:05 -07001627 if (LinkProperties.isValidMtu(mtu, newLp.hasGlobalIPv6Address()) == false) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001628 loge("Unexpected mtu value: " + mtu + ", " + iface);
1629 return;
1630 }
sy.yun9d9b74a2013-09-02 05:24:09 +09001631
w1997615afd812014-08-05 15:18:11 -07001632 // Cannot set MTU without interface name
1633 if (TextUtils.isEmpty(iface)) {
1634 loge("Setting MTU size with null iface.");
1635 return;
1636 }
1637
Robert Greenwalt7b816022014-04-18 15:25:25 -07001638 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001639 if (DBG) log("Setting MTU size: " + iface + ", " + mtu);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001640 mNetd.setMtu(iface, mtu);
1641 } catch (Exception e) {
1642 Slog.e(TAG, "exception in setMtu()" + e);
1643 }
1644 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001645
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001646 private static final String DEFAULT_TCP_BUFFER_SIZES = "4096,87380,110208,4096,16384,110208";
Paul Jensend7b6ca92015-05-13 14:05:12 -04001647 private static final String DEFAULT_TCP_RWND_KEY = "net.tcp.default_init_rwnd";
1648
1649 // Overridden for testing purposes to avoid writing to SystemProperties.
Paul Jensen67b0b072015-06-10 11:22:17 -04001650 @VisibleForTesting
Paul Jensend7b6ca92015-05-13 14:05:12 -04001651 protected int getDefaultTcpRwnd() {
1652 return SystemProperties.getInt(DEFAULT_TCP_RWND_KEY, 0);
1653 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001654
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001655 private void updateTcpBufferSizes(NetworkAgentInfo nai) {
1656 if (isDefaultNetwork(nai) == false) {
1657 return;
Irfan Sheriffd649c122010-06-09 15:39:36 -07001658 }
1659
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001660 String tcpBufferSizes = nai.linkProperties.getTcpBufferSizes();
1661 String[] values = null;
1662 if (tcpBufferSizes != null) {
1663 values = tcpBufferSizes.split(",");
1664 }
1665
1666 if (values == null || values.length != 6) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001667 if (DBG) log("Invalid tcpBufferSizes string: " + tcpBufferSizes +", using defaults");
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001668 tcpBufferSizes = DEFAULT_TCP_BUFFER_SIZES;
1669 values = tcpBufferSizes.split(",");
1670 }
1671
1672 if (tcpBufferSizes.equals(mCurrentTcpBufferSizes)) return;
1673
1674 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001675 if (DBG) Slog.d(TAG, "Setting tx/rx TCP buffers to " + tcpBufferSizes);
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07001676
1677 final String prefix = "/sys/kernel/ipv4/tcp_";
1678 FileUtils.stringToFile(prefix + "rmem_min", values[0]);
1679 FileUtils.stringToFile(prefix + "rmem_def", values[1]);
1680 FileUtils.stringToFile(prefix + "rmem_max", values[2]);
1681 FileUtils.stringToFile(prefix + "wmem_min", values[3]);
1682 FileUtils.stringToFile(prefix + "wmem_def", values[4]);
1683 FileUtils.stringToFile(prefix + "wmem_max", values[5]);
1684 mCurrentTcpBufferSizes = tcpBufferSizes;
1685 } catch (IOException e) {
1686 loge("Can't set TCP buffer sizes:" + e);
Irfan Sheriffd649c122010-06-09 15:39:36 -07001687 }
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001688
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001689 Integer rwndValue = Settings.Global.getInt(mContext.getContentResolver(),
Paul Jensend7b6ca92015-05-13 14:05:12 -04001690 Settings.Global.TCP_DEFAULT_INIT_RWND, getDefaultTcpRwnd());
JP Abgrall32d1ac4d2014-02-21 12:05:20 -08001691 final String sysctlKey = "sys.sysctl.tcp_def_init_rwnd";
1692 if (rwndValue != 0) {
1693 SystemProperties.set(sysctlKey, rwndValue.toString());
1694 }
Irfan Sheriffd649c122010-06-09 15:39:36 -07001695 }
1696
Mattias Falk8b47b362011-08-23 14:15:13 +02001697 private void flushVmDnsCache() {
Robert Greenwalt03595d02010-11-02 14:08:23 -07001698 /*
1699 * Tell the VMs to toss their DNS caches
1700 */
1701 Intent intent = new Intent(Intent.ACTION_CLEAR_DNS_CACHE);
1702 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING);
Stan Chesnutt3d1db862011-01-05 17:14:03 -08001703 /*
1704 * Connectivity events can happen before boot has completed ...
1705 */
1706 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07001707 final long ident = Binder.clearCallingIdentity();
1708 try {
1709 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
1710 } finally {
1711 Binder.restoreCallingIdentity(ident);
1712 }
Robert Greenwalt42acef32009-08-12 16:08:25 -07001713 }
1714
Robert Greenwalt562cc542014-05-15 18:07:26 -07001715 @Override
1716 public int getRestoreDefaultNetworkDelay(int networkType) {
Robert Greenwalt42acef32009-08-12 16:08:25 -07001717 String restoreDefaultNetworkDelayStr = SystemProperties.get(
1718 NETWORK_RESTORE_DELAY_PROP_NAME);
1719 if(restoreDefaultNetworkDelayStr != null &&
1720 restoreDefaultNetworkDelayStr.length() != 0) {
1721 try {
1722 return Integer.valueOf(restoreDefaultNetworkDelayStr);
1723 } catch (NumberFormatException e) {
1724 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001725 }
Robert Greenwaltf2102f72011-05-03 19:02:44 -07001726 // if the system property isn't set, use the value for the apn type
1727 int ret = RESTORE_DEFAULT_NETWORK_DELAY;
1728
1729 if ((networkType <= ConnectivityManager.MAX_NETWORK_TYPE) &&
1730 (mNetConfigs[networkType] != null)) {
1731 ret = mNetConfigs[networkType].restoreTime;
1732 }
1733 return ret;
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001734 }
1735
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001736 private boolean argsContain(String[] args, String target) {
Erik Kline379747a2015-06-05 17:47:34 +09001737 for (String arg : args) {
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001738 if (arg.equals(target)) return true;
Erik Kline379747a2015-06-05 17:47:34 +09001739 }
1740 return false;
1741 }
1742
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001743 @Override
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001744 protected void dump(FileDescriptor fd, PrintWriter writer, String[] args) {
1745 final IndentingPrintWriter pw = new IndentingPrintWriter(writer, " ");
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001746 if (mContext.checkCallingOrSelfPermission(
1747 android.Manifest.permission.DUMP)
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001748 != PackageManager.PERMISSION_GRANTED) {
Robert Greenwalt86e9e552009-07-16 17:21:39 -07001749 pw.println("Permission Denial: can't dump ConnectivityService " +
1750 "from from pid=" + Binder.getCallingPid() + ", uid=" +
1751 Binder.getCallingUid());
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001752 return;
1753 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001754
Erik Kline379747a2015-06-05 17:47:34 +09001755 final List<NetworkDiagnostics> netDiags = new ArrayList<NetworkDiagnostics>();
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001756 if (argsContain(args, "--diag")) {
Erik Kline379747a2015-06-05 17:47:34 +09001757 final long DIAG_TIME_MS = 5000;
1758 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1759 // Start gathering diagnostic information.
1760 netDiags.add(new NetworkDiagnostics(
1761 nai.network,
1762 new LinkProperties(nai.linkProperties),
1763 DIAG_TIME_MS));
1764 }
1765
1766 for (NetworkDiagnostics netDiag : netDiags) {
1767 pw.println();
1768 netDiag.waitForMeasurements();
1769 netDiag.dump(pw);
1770 }
1771
1772 return;
1773 }
1774
Lorenzo Colittie3805462015-06-03 11:18:24 +09001775 pw.print("NetworkFactories for:");
Robert Greenwalta67be032014-05-16 15:49:14 -07001776 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001777 pw.print(" " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07001778 }
Lorenzo Colittie3805462015-06-03 11:18:24 +09001779 pw.println();
Robert Greenwalta67be032014-05-16 15:49:14 -07001780 pw.println();
1781
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001782 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
1783 pw.print("Active default network: ");
1784 if (defaultNai == null) {
1785 pw.println("none");
1786 } else {
1787 pw.println(defaultNai.network.netId);
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001788 }
Dianne Hackborn77b987f2014-02-26 16:20:52 -08001789 pw.println();
1790
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001791 pw.println("Current Networks:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001792 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001793 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
1794 pw.println(nai.toString());
1795 pw.increaseIndent();
1796 pw.println("Requests:");
1797 pw.increaseIndent();
1798 for (int i = 0; i < nai.networkRequests.size(); i++) {
1799 pw.println(nai.networkRequests.valueAt(i).toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001800 }
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001801 pw.decreaseIndent();
1802 pw.println("Lingered:");
1803 pw.increaseIndent();
1804 for (NetworkRequest nr : nai.networkLingered) pw.println(nr.toString());
1805 pw.decreaseIndent();
1806 pw.decreaseIndent();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001807 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001808 pw.decreaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001809 pw.println();
Robert Greenwaltb9285352009-12-21 18:24:07 -08001810
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001811 pw.println("Network Requests:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001812 pw.increaseIndent();
Robert Greenwaltc9c90c72014-05-13 15:36:27 -07001813 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
1814 pw.println(nri.toString());
Robert Greenwaltb9285352009-12-21 18:24:07 -08001815 }
1816 pw.println();
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001817 pw.decreaseIndent();
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001818
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001819 mLegacyTypeTracker.dump(pw);
Robert Greenwaltd49ac332014-07-30 16:31:24 -07001820
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001821 synchronized (this) {
Lorenzo Colittie3805462015-06-03 11:18:24 +09001822 pw.print("mNetTransitionWakeLock: currently " +
1823 (mNetTransitionWakeLock.isHeld() ? "" : "not ") + "held");
1824 if (!TextUtils.isEmpty(mNetTransitionWakeLockCausedBy)) {
1825 pw.println(", last requested for " + mNetTransitionWakeLockCausedBy);
1826 } else {
1827 pw.println(", last requested never");
1828 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07001829 }
1830 pw.println();
1831
Robert Greenwalt2a091d72010-02-11 18:18:40 -08001832 mTethering.dump(fd, pw, args);
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001833
Lorenzo Colittie3805462015-06-03 11:18:24 +09001834 if (mInetLog != null && mInetLog.size() > 0) {
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001835 pw.println();
1836 pw.println("Inet condition reports:");
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001837 pw.increaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001838 for(int i = 0; i < mInetLog.size(); i++) {
1839 pw.println(mInetLog.get(i));
1840 }
Jeff Sharkeye6e61972012-09-14 13:47:51 -07001841 pw.decreaseIndent();
Robert Greenwalt4e8dfef2010-09-20 14:35:25 -07001842 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07001843
1844 if (argsContain(args, "--short") == false) {
1845 pw.println();
1846 synchronized (mValidationLogs) {
1847 pw.println("mValidationLogs (most recent first):");
1848 for (Pair<Network,ReadOnlyLocalLog> p : mValidationLogs) {
1849 pw.println(p.first);
1850 pw.increaseIndent();
1851 p.second.dump(fd, pw, args);
1852 pw.decreaseIndent();
1853 }
1854 }
1855 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001856 }
1857
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001858 private boolean isLiveNetworkAgent(NetworkAgentInfo nai, String msg) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04001859 if (nai.network == null) return false;
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08001860 final NetworkAgentInfo officialNai = getNetworkAgentInfoForNetwork(nai.network);
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001861 if (officialNai != null && officialNai.equals(nai)) return true;
1862 if (officialNai != null || VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001863 loge(msg + " - isLiveNetworkAgent found mismatched netId: " + officialNai +
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07001864 " - " + nai);
1865 }
1866 return false;
1867 }
1868
Paul Jensenc8b9a742014-09-30 15:37:41 -04001869 private boolean isRequest(NetworkRequest request) {
1870 return mNetworkRequests.get(request).isRequest;
1871 }
1872
Robert Greenwalt42acef32009-08-12 16:08:25 -07001873 // must be stateless - things change under us.
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07001874 private class NetworkStateTrackerHandler extends Handler {
1875 public NetworkStateTrackerHandler(Looper looper) {
Wink Savillebb08caf2010-09-02 19:23:52 -07001876 super(looper);
1877 }
1878
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08001879 @Override
1880 public void handleMessage(Message msg) {
1881 NetworkInfo info;
1882 switch (msg.what) {
Robert Greenwalte049c232014-04-11 15:53:27 -07001883 case AsyncChannel.CMD_CHANNEL_HALF_CONNECTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001884 handleAsyncChannelHalfConnect(msg);
1885 break;
1886 }
1887 case AsyncChannel.CMD_CHANNEL_DISCONNECT: {
1888 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1889 if (nai != null) nai.asyncChannel.disconnect();
1890 break;
1891 }
1892 case AsyncChannel.CMD_CHANNEL_DISCONNECTED: {
1893 handleAsyncChannelDisconnected(msg);
1894 break;
1895 }
1896 case NetworkAgent.EVENT_NETWORK_CAPABILITIES_CHANGED: {
1897 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1898 if (nai == null) {
1899 loge("EVENT_NETWORK_CAPABILITIES_CHANGED from unknown NetworkAgent");
1900 } else {
1901 updateCapabilities(nai, (NetworkCapabilities)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07001902 }
1903 break;
1904 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001905 case NetworkAgent.EVENT_NETWORK_PROPERTIES_CHANGED: {
1906 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1907 if (nai == null) {
1908 loge("NetworkAgent not found for EVENT_NETWORK_PROPERTIES_CHANGED");
1909 } else {
Paul Jenseneec75412014-08-04 12:21:19 -04001910 if (VDBG) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07001911 log("Update of LinkProperties for " + nai.name() +
Paul Jenseneec75412014-08-04 12:21:19 -04001912 "; created=" + nai.created);
1913 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07001914 LinkProperties oldLp = nai.linkProperties;
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07001915 synchronized (nai) {
1916 nai.linkProperties = (LinkProperties)msg.obj;
1917 }
Paul Jenseneec75412014-08-04 12:21:19 -04001918 if (nai.created) updateLinkProperties(nai, oldLp);
Robert Greenwalt7b816022014-04-18 15:25:25 -07001919 }
1920 break;
1921 }
1922 case NetworkAgent.EVENT_NETWORK_INFO_CHANGED: {
1923 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1924 if (nai == null) {
1925 loge("EVENT_NETWORK_INFO_CHANGED from unknown NetworkAgent");
1926 break;
1927 }
1928 info = (NetworkInfo) msg.obj;
1929 updateNetworkInfo(nai, info);
1930 break;
1931 }
Robert Greenwalt55691b82014-05-27 13:20:24 -07001932 case NetworkAgent.EVENT_NETWORK_SCORE_CHANGED: {
1933 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1934 if (nai == null) {
1935 loge("EVENT_NETWORK_SCORE_CHANGED from unknown NetworkAgent");
1936 break;
1937 }
1938 Integer score = (Integer) msg.obj;
Robert Greenwaltac96c522014-06-03 16:43:57 -07001939 if (score != null) updateNetworkScore(nai, score.intValue());
Robert Greenwalt55691b82014-05-27 13:20:24 -07001940 break;
1941 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001942 case NetworkAgent.EVENT_UID_RANGES_ADDED: {
1943 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1944 if (nai == null) {
1945 loge("EVENT_UID_RANGES_ADDED from unknown NetworkAgent");
1946 break;
1947 }
1948 try {
1949 mNetd.addVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001950 } catch (Exception e) {
1951 // Never crash!
1952 loge("Exception in addVpnUidRanges: " + e);
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04001953 }
1954 break;
1955 }
1956 case NetworkAgent.EVENT_UID_RANGES_REMOVED: {
1957 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1958 if (nai == null) {
1959 loge("EVENT_UID_RANGES_REMOVED from unknown NetworkAgent");
1960 break;
1961 }
1962 try {
1963 mNetd.removeVpnUidRanges(nai.network.netId, (UidRange[])msg.obj);
Sreeram Ramachandran42065ac2014-07-27 00:37:35 -07001964 } catch (Exception e) {
1965 // Never crash!
1966 loge("Exception in removeVpnUidRanges: " + e);
1967 }
1968 break;
1969 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001970 case NetworkAgent.EVENT_SET_EXPLICITLY_SELECTED: {
1971 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
1972 if (nai == null) {
1973 loge("EVENT_SET_EXPLICITLY_SELECTED from unknown NetworkAgent");
1974 break;
1975 }
Paul Jensen4b9b2be2014-09-26 10:10:22 -04001976 if (nai.created && !nai.networkMisc.explicitlySelected) {
1977 loge("ERROR: created network explicitly selected.");
1978 }
Robert Greenwalte73cc462014-09-07 16:50:01 -07001979 nai.networkMisc.explicitlySelected = true;
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09001980 nai.networkMisc.acceptUnvalidated = (boolean) msg.obj;
Robert Greenwalte73cc462014-09-07 16:50:01 -07001981 break;
1982 }
Paul Jensenad50a1f2014-09-05 12:06:44 -04001983 case NetworkMonitor.EVENT_NETWORK_TESTED: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07001984 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001985 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_TESTED")) {
1986 final boolean valid =
1987 (msg.arg1 == NetworkMonitor.NETWORK_TEST_RESULT_VALID);
1988 final boolean validationChanged = (valid != nai.lastValidated);
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09001989 nai.lastValidated = valid;
Paul Jensenad50a1f2014-09-05 12:06:44 -04001990 if (valid) {
1991 if (DBG) log("Validated " + nai.name());
Lorenzo Colitti76f67792015-05-14 17:28:27 +09001992 nai.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09001993 if (!nai.everValidated) {
1994 nai.everValidated = true;
Paul Jensenb10e37f2014-11-25 12:33:08 -05001995 rematchNetworkAndRequests(nai, NascentState.JUST_VALIDATED,
1996 ReapUnvalidatedNetworks.REAP);
1997 // If score has changed, rebroadcast to NetworkFactories. b/17726566
Paul Jensenc8b9a742014-09-30 15:37:41 -04001998 sendUpdatedScoreToFactories(nai);
1999 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002000 } else {
2001 nai.networkCapabilities.removeCapability(NET_CAPABILITY_VALIDATED);
Paul Jensenad50a1f2014-09-05 12:06:44 -04002002 }
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09002003 updateInetCondition(nai);
Robert Greenwalt49f63fb2014-09-13 12:04:12 -07002004 // Let the NetworkAgent know the state of its network
2005 nai.asyncChannel.sendMessage(
2006 android.net.NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2007 (valid ? NetworkAgent.VALID_NETWORK : NetworkAgent.INVALID_NETWORK),
2008 0, null);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002009
Lorenzo Colitti76f67792015-05-14 17:28:27 +09002010 if (validationChanged) {
2011 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_CAP_CHANGED);
2012 }
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002013 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002014 break;
2015 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002016 case NetworkMonitor.EVENT_NETWORK_LINGER_COMPLETE: {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002017 NetworkAgentInfo nai = (NetworkAgentInfo)msg.obj;
Robert Greenwalt73ed9d82014-08-19 18:58:04 -07002018 if (isLiveNetworkAgent(nai, "EVENT_NETWORK_LINGER_COMPLETE")) {
2019 handleLingerComplete(nai);
2020 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002021 break;
2022 }
Paul Jensen869868be2014-05-15 10:33:05 -04002023 case NetworkMonitor.EVENT_PROVISIONING_NOTIFICATION: {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002024 final int netId = msg.arg2;
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002025 if (msg.arg1 == 0) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002026 setProvNotificationVisibleIntent(false, netId, null, 0, null, null);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04002027 } else {
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002028 final NetworkAgentInfo nai;
Paul Jensen5df4bec2014-08-25 22:45:39 -04002029 synchronized (mNetworkForNetId) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002030 nai = mNetworkForNetId.get(netId);
Paul Jensen5df4bec2014-08-25 22:45:39 -04002031 }
2032 if (nai == null) {
2033 loge("EVENT_PROVISIONING_NOTIFICATION from unknown NetworkMonitor");
2034 break;
2035 }
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002036 nai.captivePortalDetected = true;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002037 setProvNotificationVisibleIntent(true, netId, NotificationType.SIGN_IN,
2038 nai.networkInfo.getType(),nai.networkInfo.getExtraInfo(),
2039 (PendingIntent)msg.obj);
Paul Jensen869868be2014-05-15 10:33:05 -04002040 }
Paul Jensen869868be2014-05-15 10:33:05 -04002041 break;
2042 }
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002043 }
2044 }
2045 }
2046
Paul Jensen0cc17322014-11-25 15:26:53 -05002047 // Cancel any lingering so the linger timeout doesn't teardown a network.
2048 // This should be called when a network begins satisfying a NetworkRequest.
2049 // Note: depending on what state the NetworkMonitor is in (e.g.,
2050 // if it's awaiting captive portal login, or if validation failed), this
2051 // may trigger a re-evaluation of the network.
2052 private void unlinger(NetworkAgentInfo nai) {
2053 if (VDBG) log("Canceling linger of " + nai.name());
Paul Jensen573a0352015-01-08 10:49:34 -05002054 // If network has never been validated, it cannot have been lingered, so don't bother
2055 // needlessly triggering a re-evaluation.
2056 if (!nai.everValidated) return;
Paul Jensen0cc17322014-11-25 15:26:53 -05002057 nai.networkLingered.clear();
2058 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
2059 }
2060
Robert Greenwalt7b816022014-04-18 15:25:25 -07002061 private void handleAsyncChannelHalfConnect(Message msg) {
2062 AsyncChannel ac = (AsyncChannel) msg.obj;
Robert Greenwalta67be032014-05-16 15:49:14 -07002063 if (mNetworkFactoryInfos.containsKey(msg.replyTo)) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07002064 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2065 if (VDBG) log("NetworkFactory connected");
2066 // A network factory has connected. Send it all current NetworkRequests.
Robert Greenwalt9258c642014-03-26 16:47:06 -07002067 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Robert Greenwalta67be032014-05-16 15:49:14 -07002068 if (nri.isRequest == false) continue;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002069 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
Robert Greenwalt55691b82014-05-27 13:20:24 -07002070 ac.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK,
Paul Jensen2161a8e2014-09-11 11:00:39 -04002071 (nai != null ? nai.getCurrentScore() : 0), 0, nri.request);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002072 }
2073 } else {
2074 loge("Error connecting NetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07002075 mNetworkFactoryInfos.remove(msg.obj);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002076 }
2077 } else if (mNetworkAgentInfos.containsKey(msg.replyTo)) {
2078 if (msg.arg1 == AsyncChannel.STATUS_SUCCESSFUL) {
2079 if (VDBG) log("NetworkAgent connected");
2080 // A network agent has requested a connection. Establish the connection.
2081 mNetworkAgentInfos.get(msg.replyTo).asyncChannel.
2082 sendMessage(AsyncChannel.CMD_CHANNEL_FULL_CONNECTION);
2083 } else {
2084 loge("Error connecting NetworkAgent");
Robert Greenwalt12e67352014-05-13 21:41:06 -07002085 NetworkAgentInfo nai = mNetworkAgentInfos.remove(msg.replyTo);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002086 if (nai != null) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002087 final boolean wasDefault = isDefaultNetwork(nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002088 synchronized (mNetworkForNetId) {
2089 mNetworkForNetId.remove(nai.network.netId);
Paul Jensen31a94f42015-02-13 14:18:39 -05002090 mNetIdInUse.delete(nai.network.netId);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002091 }
Lorenzo Colittia793a672014-07-31 23:20:17 +09002092 // Just in case.
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002093 mLegacyTypeTracker.remove(nai, wasDefault);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002094 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002095 }
2096 }
2097 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002098
Robert Greenwalt7b816022014-04-18 15:25:25 -07002099 private void handleAsyncChannelDisconnected(Message msg) {
2100 NetworkAgentInfo nai = mNetworkAgentInfos.get(msg.replyTo);
2101 if (nai != null) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002102 if (DBG) {
2103 log(nai.name() + " got DISCONNECTED, was satisfying " + nai.networkRequests.size());
2104 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002105 // A network agent has disconnected.
Robert Greenwalt562cc542014-05-15 18:07:26 -07002106 // TODO - if we move the logic to the network agent (have them disconnect
2107 // because they lost all their requests or because their score isn't good)
2108 // then they would disconnect organically, report their new state and then
2109 // disconnect the channel.
2110 if (nai.networkInfo.isConnected()) {
2111 nai.networkInfo.setDetailedState(NetworkInfo.DetailedState.DISCONNECTED,
2112 null, null);
2113 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002114 final boolean wasDefault = isDefaultNetwork(nai);
2115 if (wasDefault) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002116 mDefaultInetConditionPublished = 0;
2117 }
Jeff Sharkey69736342014-12-08 14:50:12 -08002118 notifyIfacesChanged();
Robert Greenwalt9258c642014-03-26 16:47:06 -07002119 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOST);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002120 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_DISCONNECTED);
Paul Jensen3b759822014-05-13 11:44:01 -04002121 mNetworkAgentInfos.remove(msg.replyTo);
2122 updateClat(null, nai.linkProperties, nai);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002123 synchronized (mNetworkForNetId) {
Paul Jensen62d30802015-06-17 14:42:30 -04002124 // Remove the NetworkAgent, but don't mark the netId as
2125 // available until we've told netd to delete it below.
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07002126 mNetworkForNetId.remove(nai.network.netId);
2127 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002128 // Since we've lost the network, go through all the requests that
2129 // it was satisfying and see if any other factory can satisfy them.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04002130 // TODO: This logic may be better replaced with a call to rematchAllNetworksAndRequests
Paul Jensenca8f16a2014-05-09 12:47:55 -04002131 final ArrayList<NetworkAgentInfo> toActivate = new ArrayList<NetworkAgentInfo>();
Robert Greenwalt7b816022014-04-18 15:25:25 -07002132 for (int i = 0; i < nai.networkRequests.size(); i++) {
2133 NetworkRequest request = nai.networkRequests.valueAt(i);
2134 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(request.requestId);
2135 if (currentNetwork != null && currentNetwork.network.netId == nai.network.netId) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002136 if (DBG) {
2137 log("Checking for replacement network to handle request " + request );
2138 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002139 mNetworkForRequestId.remove(request.requestId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002140 sendUpdatedScoreToFactories(request, 0);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002141 NetworkAgentInfo alternative = null;
Paul Jensen0cc17322014-11-25 15:26:53 -05002142 for (NetworkAgentInfo existing : mNetworkAgentInfos.values()) {
2143 if (existing.satisfies(request) &&
Paul Jensenca8f16a2014-05-09 12:47:55 -04002144 (alternative == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002145 alternative.getCurrentScore() < existing.getCurrentScore())) {
Paul Jensenca8f16a2014-05-09 12:47:55 -04002146 alternative = existing;
2147 }
2148 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002149 if (alternative != null) {
2150 if (DBG) log(" found replacement in " + alternative.name());
2151 if (!toActivate.contains(alternative)) {
2152 toActivate.add(alternative);
2153 }
Paul Jensenca8f16a2014-05-09 12:47:55 -04002154 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002155 }
2156 }
2157 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
2158 removeDataActivityTracking(nai);
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09002159 notifyLockdownVpn(nai);
Robert Greenwalt27711812014-06-25 16:45:57 -07002160 requestNetworkTransitionWakelock(nai.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07002161 }
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002162 mLegacyTypeTracker.remove(nai, wasDefault);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002163 for (NetworkAgentInfo networkToActivate : toActivate) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002164 unlinger(networkToActivate);
Paul Jensenb10e37f2014-11-25 12:33:08 -05002165 rematchNetworkAndRequests(networkToActivate, NascentState.NOT_JUST_VALIDATED,
2166 ReapUnvalidatedNetworks.DONT_REAP);
Paul Jensenca8f16a2014-05-09 12:47:55 -04002167 }
Paul Jensen62d30802015-06-17 14:42:30 -04002168 if (nai.created) {
2169 // Tell netd to clean up the configuration for this network
2170 // (routing rules, DNS, etc).
2171 // This may be slow as it requires a lot of netd shelling out to ip and
2172 // ip[6]tables to flush routes and remove the incoming packet mark rule, so do it
2173 // after we've rematched networks with requests which should make a potential
2174 // fallback network the default or requested a new network from the
2175 // NetworkFactories, so network traffic isn't interrupted for an unnecessarily
2176 // long time.
2177 try {
2178 mNetd.removeNetwork(nai.network.netId);
2179 } catch (Exception e) {
2180 loge("Exception removing network: " + e);
2181 }
2182 }
2183 synchronized (mNetworkForNetId) {
2184 mNetIdInUse.delete(nai.network.netId);
2185 }
2186 } else {
2187 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(msg.replyTo);
2188 if (DBG && nfi != null) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalt7b816022014-04-18 15:25:25 -07002189 }
2190 }
2191
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002192 // If this method proves to be too slow then we can maintain a separate
2193 // pendingIntent => NetworkRequestInfo map.
2194 // This method assumes that every non-null PendingIntent maps to exactly 1 NetworkRequestInfo.
2195 private NetworkRequestInfo findExistingNetworkRequestInfo(PendingIntent pendingIntent) {
2196 Intent intent = pendingIntent.getIntent();
2197 for (Map.Entry<NetworkRequest, NetworkRequestInfo> entry : mNetworkRequests.entrySet()) {
2198 PendingIntent existingPendingIntent = entry.getValue().mPendingIntent;
2199 if (existingPendingIntent != null &&
2200 existingPendingIntent.getIntent().filterEquals(intent)) {
2201 return entry.getValue();
2202 }
2203 }
2204 return null;
2205 }
2206
2207 private void handleRegisterNetworkRequestWithIntent(Message msg) {
2208 final NetworkRequestInfo nri = (NetworkRequestInfo) (msg.obj);
2209
2210 NetworkRequestInfo existingRequest = findExistingNetworkRequestInfo(nri.mPendingIntent);
2211 if (existingRequest != null) { // remove the existing request.
2212 if (DBG) log("Replacing " + existingRequest.request + " with "
2213 + nri.request + " because their intents matched.");
2214 handleReleaseNetworkRequest(existingRequest.request, getCallingUid());
2215 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002216 handleRegisterNetworkRequest(nri);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002217 }
2218
Erik Klineda4bfa82015-04-30 12:58:40 +09002219 private void handleRegisterNetworkRequest(NetworkRequestInfo nri) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002220 mNetworkRequests.put(nri.request, nri);
2221
Paul Jensen0cc17322014-11-25 15:26:53 -05002222 // TODO: This logic may be better replaced with a call to rematchNetworkAndRequests
2223
Robert Greenwalt9258c642014-03-26 16:47:06 -07002224 // Check for the best currently alive network that satisfies this request
2225 NetworkAgentInfo bestNetwork = null;
2226 for (NetworkAgentInfo network : mNetworkAgentInfos.values()) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002227 if (DBG) log("handleRegisterNetworkRequest checking " + network.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002228 if (network.satisfies(nri.request)) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04002229 if (DBG) log("apparently satisfied. currentScore=" + network.getCurrentScore());
Paul Jensen0cc17322014-11-25 15:26:53 -05002230 if (!nri.isRequest) {
2231 // Not setting bestNetwork here as a listening NetworkRequest may be
2232 // satisfied by multiple Networks. Instead the request is added to
2233 // each satisfying Network and notified about each.
Paul Jensen3d911462015-06-12 06:40:24 -04002234 if (!network.addRequest(nri.request)) {
2235 Slog.wtf(TAG, "BUG: " + network.name() + " already has " + nri.request);
2236 }
Paul Jensen0cc17322014-11-25 15:26:53 -05002237 notifyNetworkCallback(network, nri);
2238 } else if (bestNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04002239 bestNetwork.getCurrentScore() < network.getCurrentScore()) {
Paul Jensen0cc17322014-11-25 15:26:53 -05002240 bestNetwork = network;
Robert Greenwalt9258c642014-03-26 16:47:06 -07002241 }
2242 }
2243 }
2244 if (bestNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002245 if (DBG) log("using " + bestNetwork.name());
Paul Jensen0cc17322014-11-25 15:26:53 -05002246 unlinger(bestNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04002247 if (!bestNetwork.addRequest(nri.request)) {
2248 Slog.wtf(TAG, "BUG: " + bestNetwork.name() + " already has " + nri.request);
2249 }
Robert Greenwalt2d370702014-06-03 17:22:11 -07002250 mNetworkForRequestId.put(nri.request.requestId, bestNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002251 notifyNetworkCallback(bestNetwork, nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04002252 if (nri.request.legacyType != TYPE_NONE) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09002253 mLegacyTypeTracker.add(nri.request.legacyType, bestNetwork);
2254 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002255 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002256
Lorenzo Colittia793a672014-07-31 23:20:17 +09002257 if (nri.isRequest) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07002258 if (DBG) log("sending new NetworkRequest to factories");
Paul Jensen0cc17322014-11-25 15:26:53 -05002259 final int score = bestNetwork == null ? 0 : bestNetwork.getCurrentScore();
Robert Greenwalta67be032014-05-16 15:49:14 -07002260 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002261 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score,
Robert Greenwalt562cc542014-05-15 18:07:26 -07002262 0, nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002263 }
2264 }
2265 }
2266
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002267 private void handleReleaseNetworkRequestWithIntent(PendingIntent pendingIntent,
2268 int callingUid) {
2269 NetworkRequestInfo nri = findExistingNetworkRequestInfo(pendingIntent);
2270 if (nri != null) {
2271 handleReleaseNetworkRequest(nri.request, callingUid);
2272 }
2273 }
2274
Paul Jensen99364842014-12-09 11:43:45 -05002275 // Is nai unneeded by all NetworkRequests (and should be disconnected)?
2276 // For validated Networks this is simply whether it is satsifying any NetworkRequests.
2277 // For unvalidated Networks this is whether it is satsifying any NetworkRequests or
2278 // were it to become validated, would it have a chance of satisfying any NetworkRequests.
2279 private boolean unneeded(NetworkAgentInfo nai) {
2280 if (!nai.created || nai.isVPN()) return false;
2281 boolean unneeded = true;
2282 if (nai.everValidated) {
2283 for (int i = 0; i < nai.networkRequests.size() && unneeded; i++) {
2284 final NetworkRequest nr = nai.networkRequests.valueAt(i);
2285 try {
2286 if (isRequest(nr)) unneeded = false;
2287 } catch (Exception e) {
2288 loge("Request " + nr + " not found in mNetworkRequests.");
2289 loge(" it came from request list of " + nai.name());
2290 }
2291 }
2292 } else {
2293 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
2294 // If this Network is already the highest scoring Network for a request, or if
2295 // there is hope for it to become one if it validated, then it is needed.
2296 if (nri.isRequest && nai.satisfies(nri.request) &&
2297 (nai.networkRequests.get(nri.request.requestId) != null ||
2298 // Note that this catches two important cases:
2299 // 1. Unvalidated cellular will not be reaped when unvalidated WiFi
2300 // is currently satisfying the request. This is desirable when
2301 // cellular ends up validating but WiFi does not.
2302 // 2. Unvalidated WiFi will not be reaped when validated cellular
2303 // is currently satsifying the request. This is desirable when
2304 // WiFi ends up validating and out scoring cellular.
2305 mNetworkForRequestId.get(nri.request.requestId).getCurrentScore() <
2306 nai.getCurrentScoreAsValidated())) {
2307 unneeded = false;
2308 break;
2309 }
2310 }
2311 }
2312 return unneeded;
2313 }
2314
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002315 private void handleReleaseNetworkRequest(NetworkRequest request, int callingUid) {
2316 NetworkRequestInfo nri = mNetworkRequests.get(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002317 if (nri != null) {
Jeff Davidson6f913902014-08-21 15:54:15 -07002318 if (Process.SYSTEM_UID != callingUid && nri.mUid != callingUid) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002319 if (DBG) log("Attempt to release unowned NetworkRequest " + request);
2320 return;
2321 }
2322 if (DBG) log("releasing NetworkRequest " + request);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07002323 nri.unlinkDeathRecipient();
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002324 mNetworkRequests.remove(request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002325 if (nri.isRequest) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002326 // Find all networks that are satisfying this request and remove the request
2327 // from their request lists.
Robert Greenwalt51481852015-01-08 14:43:31 -08002328 // TODO - it's my understanding that for a request there is only a single
2329 // network satisfying it, so this loop is wasteful
2330 boolean wasKept = false;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002331 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2332 if (nai.networkRequests.get(nri.request.requestId) != null) {
2333 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07002334 if (DBG) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002335 log(" Removing from current network " + nai.name() +
2336 ", leaving " + nai.networkRequests.size() +
2337 " requests.");
2338 }
Paul Jensen99364842014-12-09 11:43:45 -05002339 if (unneeded(nai)) {
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002340 if (DBG) log("no live requests for " + nai.name() + "; disconnecting");
Paul Jensen99364842014-12-09 11:43:45 -05002341 teardownUnneededNetwork(nai);
Robert Greenwalt51481852015-01-08 14:43:31 -08002342 } else {
2343 // suspect there should only be one pass through here
2344 // but if any were kept do the check below
2345 wasKept |= true;
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002346 }
2347 }
2348 }
2349
Robert Greenwalt51481852015-01-08 14:43:31 -08002350 NetworkAgentInfo nai = mNetworkForRequestId.get(nri.request.requestId);
2351 if (nai != null) {
2352 mNetworkForRequestId.remove(nri.request.requestId);
2353 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002354 // Maintain the illusion. When this request arrived, we might have pretended
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002355 // that a network connected to serve it, even though the network was already
2356 // connected. Now that this request has gone away, we might have to pretend
2357 // that the network disconnected. LegacyTypeTracker will generate that
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002358 // phantom disconnect for this type.
Robert Greenwalt51481852015-01-08 14:43:31 -08002359 if (nri.request.legacyType != TYPE_NONE && nai != null) {
2360 boolean doRemove = true;
2361 if (wasKept) {
2362 // check if any of the remaining requests for this network are for the
2363 // same legacy type - if so, don't remove the nai
2364 for (int i = 0; i < nai.networkRequests.size(); i++) {
2365 NetworkRequest otherRequest = nai.networkRequests.valueAt(i);
2366 if (otherRequest.legacyType == nri.request.legacyType &&
2367 isRequest(otherRequest)) {
2368 if (DBG) log(" still have other legacy request - leaving");
2369 doRemove = false;
2370 }
2371 }
2372 }
2373
2374 if (doRemove) {
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09002375 mLegacyTypeTracker.remove(nri.request.legacyType, nai, false);
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002376 }
2377 }
2378
Robert Greenwalta67be032014-05-16 15:49:14 -07002379 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07002380 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_CANCEL_REQUEST,
2381 nri.request);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002382 }
Robert Greenwalt4456cf32014-08-24 22:52:10 -07002383 } else {
2384 // listens don't have a singular affectedNetwork. Check all networks to see
2385 // if this listen request applies and remove it.
2386 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2387 nai.networkRequests.remove(nri.request.requestId);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002388 }
2389 }
2390 callCallbackForRequest(nri, null, ConnectivityManager.CALLBACK_RELEASED);
2391 }
2392 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002393
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002394 public void setAcceptUnvalidated(Network network, boolean accept, boolean always) {
2395 enforceConnectivityInternalPermission();
2396 mHandler.sendMessage(mHandler.obtainMessage(EVENT_SET_ACCEPT_UNVALIDATED,
2397 accept ? 1 : 0, always ? 1: 0, network));
2398 }
2399
2400 private void handleSetAcceptUnvalidated(Network network, boolean accept, boolean always) {
2401 if (DBG) log("handleSetAcceptUnvalidated network=" + network +
2402 " accept=" + accept + " always=" + always);
2403
2404 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2405 if (nai == null) {
2406 // Nothing to do.
2407 return;
2408 }
2409
2410 if (nai.everValidated) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002411 // The network validated while the dialog box was up. Take no action.
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002412 return;
2413 }
2414
2415 if (!nai.networkMisc.explicitlySelected) {
2416 Slog.wtf(TAG, "BUG: setAcceptUnvalidated non non-explicitly selected network");
2417 }
2418
2419 if (accept != nai.networkMisc.acceptUnvalidated) {
2420 int oldScore = nai.getCurrentScore();
2421 nai.networkMisc.acceptUnvalidated = accept;
2422 rematchAllNetworksAndRequests(nai, oldScore);
2423 sendUpdatedScoreToFactories(nai);
2424 }
2425
2426 if (always) {
2427 nai.asyncChannel.sendMessage(
2428 NetworkAgent.CMD_SAVE_ACCEPT_UNVALIDATED, accept ? 1 : 0);
2429 }
2430
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002431 if (!accept) {
2432 // Tell the NetworkAgent that the network does not have Internet access (because that's
2433 // what we just told the user). This will hint to Wi-Fi not to autojoin this network in
2434 // the future. We do this now because NetworkMonitor might not yet have finished
2435 // validating and thus we might not yet have received an EVENT_NETWORK_TESTED.
2436 nai.asyncChannel.sendMessage(NetworkAgent.CMD_REPORT_NETWORK_STATUS,
2437 NetworkAgent.INVALID_NETWORK, 0, null);
2438 // TODO: Tear the network down once we have determined how to tell WifiStateMachine not
2439 // to reconnect to it immediately. http://b/20739299
2440 }
2441
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002442 }
2443
2444 private void scheduleUnvalidatedPrompt(NetworkAgentInfo nai) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002445 if (DBG) log("scheduleUnvalidatedPrompt " + nai.network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002446 mHandler.sendMessageDelayed(
2447 mHandler.obtainMessage(EVENT_PROMPT_UNVALIDATED, nai.network),
2448 PROMPT_UNVALIDATED_DELAY_MS);
2449 }
2450
2451 private void handlePromptUnvalidated(Network network) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002452 if (DBG) log("handlePromptUnvalidated " + network);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002453 NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2454
2455 // Only prompt if the network is unvalidated and was explicitly selected by the user, and if
2456 // we haven't already been told to switch to it regardless of whether it validated or not.
Lorenzo Colittid49159f2015-05-14 23:15:10 +09002457 // Also don't prompt on captive portals because we're already prompting the user to sign in.
2458 if (nai == null || nai.everValidated || nai.captivePortalDetected ||
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002459 !nai.networkMisc.explicitlySelected || nai.networkMisc.acceptUnvalidated) {
2460 return;
2461 }
2462
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002463 Intent intent = new Intent(ConnectivityManager.ACTION_PROMPT_UNVALIDATED);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002464 intent.setData(Uri.fromParts("netId", Integer.toString(network.netId), null));
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002465 intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
2466 intent.setClassName("com.android.settings",
2467 "com.android.settings.wifi.WifiNoInternetDialog");
Lorenzo Colittif6673d02015-05-21 16:17:05 +09002468
2469 PendingIntent pendingIntent = PendingIntent.getActivityAsUser(
2470 mContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT, null, UserHandle.CURRENT);
2471 setProvNotificationVisibleIntent(true, nai.network.netId, NotificationType.NO_INTERNET,
2472 nai.networkInfo.getType(), nai.networkInfo.getExtraInfo(), pendingIntent);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002473 }
2474
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002475 private class InternalHandler extends Handler {
2476 public InternalHandler(Looper looper) {
2477 super(looper);
2478 }
2479
2480 @Override
2481 public void handleMessage(Message msg) {
Jeff Sharkey4c628eb2012-07-23 13:19:46 -07002482 switch (msg.what) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002483 case EVENT_EXPIRE_NET_TRANSITION_WAKELOCK:
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002484 case EVENT_CLEAR_NET_TRANSITION_WAKELOCK: {
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002485 String causedBy = null;
2486 synchronized (ConnectivityService.this) {
2487 if (msg.arg1 == mNetTransitionWakeLockSerialNumber &&
2488 mNetTransitionWakeLock.isHeld()) {
2489 mNetTransitionWakeLock.release();
2490 causedBy = mNetTransitionWakeLockCausedBy;
Robert Greenwalt27711812014-06-25 16:45:57 -07002491 } else {
2492 break;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002493 }
2494 }
Robert Greenwalt27711812014-06-25 16:45:57 -07002495 if (msg.what == EVENT_EXPIRE_NET_TRANSITION_WAKELOCK) {
2496 log("Failed to find a new network - expiring NetTransition Wakelock");
2497 } else {
2498 log("NetTransition Wakelock (" + (causedBy == null ? "unknown" : causedBy) +
2499 " cleared because we found a replacement network");
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002500 }
Robert Greenwalt057d5e92010-09-09 14:05:10 -07002501 break;
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002502 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002503 case EVENT_APPLY_GLOBAL_HTTP_PROXY: {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002504 handleDeprecatedGlobalHttpProxy();
Robert Greenwaltd55a6b42011-03-25 13:09:25 -07002505 break;
2506 }
Sreeram Ramachandranb1486ae2013-08-27 11:41:19 -07002507 case EVENT_SEND_STICKY_BROADCAST_INTENT: {
Wink Saville628b0852011-08-04 15:01:58 -07002508 Intent intent = (Intent)msg.obj;
Wink Saville628b0852011-08-04 15:01:58 -07002509 sendStickyBroadcast(intent);
2510 break;
2511 }
Jason Monkdecd2952013-10-10 14:02:51 -04002512 case EVENT_PROXY_HAS_CHANGED: {
Jason Monk207900c2014-04-25 15:00:09 -04002513 handleApplyDefaultProxy((ProxyInfo)msg.obj);
Jason Monkdecd2952013-10-10 14:02:51 -04002514 break;
2515 }
Robert Greenwalte049c232014-04-11 15:53:27 -07002516 case EVENT_REGISTER_NETWORK_FACTORY: {
Robert Greenwalta67be032014-05-16 15:49:14 -07002517 handleRegisterNetworkFactory((NetworkFactoryInfo)msg.obj);
2518 break;
2519 }
2520 case EVENT_UNREGISTER_NETWORK_FACTORY: {
2521 handleUnregisterNetworkFactory((Messenger)msg.obj);
Robert Greenwalte049c232014-04-11 15:53:27 -07002522 break;
2523 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07002524 case EVENT_REGISTER_NETWORK_AGENT: {
2525 handleRegisterNetworkAgent((NetworkAgentInfo)msg.obj);
2526 break;
2527 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002528 case EVENT_REGISTER_NETWORK_REQUEST:
2529 case EVENT_REGISTER_NETWORK_LISTENER: {
Erik Klineda4bfa82015-04-30 12:58:40 +09002530 handleRegisterNetworkRequest((NetworkRequestInfo) msg.obj);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002531 break;
2532 }
Paul Jensen694f2b82015-06-17 14:15:39 -04002533 case EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT:
2534 case EVENT_REGISTER_NETWORK_LISTENER_WITH_INTENT: {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08002535 handleRegisterNetworkRequestWithIntent(msg);
2536 break;
2537 }
2538 case EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT: {
2539 handleReleaseNetworkRequestWithIntent((PendingIntent) msg.obj, msg.arg1);
2540 break;
2541 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002542 case EVENT_RELEASE_NETWORK_REQUEST: {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04002543 handleReleaseNetworkRequest((NetworkRequest) msg.obj, msg.arg1);
Robert Greenwalt9258c642014-03-26 16:47:06 -07002544 break;
2545 }
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09002546 case EVENT_SET_ACCEPT_UNVALIDATED: {
2547 handleSetAcceptUnvalidated((Network) msg.obj, msg.arg1 != 0, msg.arg2 != 0);
2548 break;
2549 }
2550 case EVENT_PROMPT_UNVALIDATED: {
2551 handlePromptUnvalidated((Network) msg.obj);
2552 break;
2553 }
Erik Klineda4bfa82015-04-30 12:58:40 +09002554 case EVENT_CONFIGURE_MOBILE_DATA_ALWAYS_ON: {
2555 handleMobileDataAlwaysOn();
2556 break;
2557 }
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07002558 case EVENT_SYSTEM_READY: {
2559 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
2560 nai.networkMonitor.systemReady = true;
2561 }
2562 break;
2563 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08002564 }
2565 }
2566 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002567
2568 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002569 public int tether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002570 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002571 if (isTetheringSupported()) {
2572 return mTethering.tether(iface);
2573 } else {
2574 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2575 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002576 }
2577
2578 // javadoc from interface
Robert Greenwalt5a735062010-03-02 17:25:02 -08002579 public int untether(String iface) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002580 ConnectivityManager.enforceTetherChangePermission(mContext);
Robert Greenwalt5a735062010-03-02 17:25:02 -08002581
2582 if (isTetheringSupported()) {
2583 return mTethering.untether(iface);
2584 } else {
2585 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2586 }
2587 }
2588
2589 // javadoc from interface
2590 public int getLastTetherError(String iface) {
2591 enforceTetherAccessPermission();
2592
2593 if (isTetheringSupported()) {
2594 return mTethering.getLastTetherError(iface);
2595 } else {
2596 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2597 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002598 }
2599
2600 // TODO - proper iface API for selection by property, inspection, etc
2601 public String[] getTetherableUsbRegexs() {
2602 enforceTetherAccessPermission();
2603 if (isTetheringSupported()) {
2604 return mTethering.getTetherableUsbRegexs();
2605 } else {
2606 return new String[0];
2607 }
2608 }
2609
2610 public String[] getTetherableWifiRegexs() {
2611 enforceTetherAccessPermission();
2612 if (isTetheringSupported()) {
2613 return mTethering.getTetherableWifiRegexs();
2614 } else {
2615 return new String[0];
2616 }
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002617 }
2618
Danica Chang6fdd0c62010-08-11 14:54:43 -07002619 public String[] getTetherableBluetoothRegexs() {
2620 enforceTetherAccessPermission();
2621 if (isTetheringSupported()) {
2622 return mTethering.getTetherableBluetoothRegexs();
2623 } else {
2624 return new String[0];
2625 }
2626 }
2627
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002628 public int setUsbTethering(boolean enable) {
Robert Greenwaltedb47662014-09-16 17:54:19 -07002629 ConnectivityManager.enforceTetherChangePermission(mContext);
Mike Lockwood6c2260b2011-07-19 13:04:47 -07002630 if (isTetheringSupported()) {
2631 return mTethering.setUsbTethering(enable);
2632 } else {
2633 return ConnectivityManager.TETHER_ERROR_UNSUPPORTED;
2634 }
2635 }
2636
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002637 // TODO - move iface listing, queries, etc to new module
2638 // javadoc from interface
2639 public String[] getTetherableIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002640 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002641 return mTethering.getTetherableIfaces();
2642 }
2643
2644 public String[] getTetheredIfaces() {
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002645 enforceTetherAccessPermission();
Robert Greenwaltd0e18ff2010-01-26 11:40:34 -08002646 return mTethering.getTetheredIfaces();
2647 }
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002648
Robert Greenwalt5a735062010-03-02 17:25:02 -08002649 public String[] getTetheringErroredIfaces() {
2650 enforceTetherAccessPermission();
2651 return mTethering.getErroredIfaces();
2652 }
2653
Robert Greenwalt9c7e2c22014-06-23 14:53:42 -07002654 public String[] getTetheredDhcpRanges() {
2655 enforceConnectivityInternalPermission();
2656 return mTethering.getTetheredDhcpRanges();
2657 }
2658
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002659 // if ro.tether.denied = true we default to no tethering
2660 // gservices could set the secure setting to 1 though to enable it on a build where it
2661 // had previously been turned off.
2662 public boolean isTetheringSupported() {
2663 enforceTetherAccessPermission();
2664 int defaultVal = (SystemProperties.get("ro.tether.denied").equals("true") ? 0 : 1);
Jeff Brownbf6f6f92012-09-25 15:03:20 -07002665 boolean tetherEnabledInSettings = (Settings.Global.getInt(mContext.getContentResolver(),
Julia Reynoldsfc6b2a02014-06-24 10:56:55 -04002666 Settings.Global.TETHER_SUPPORTED, defaultVal) != 0)
2667 && !mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING);
Robert Greenwaltc13368b2013-07-18 14:24:42 -07002668 return tetherEnabledInSettings && ((mTethering.getTetherableUsbRegexs().length != 0 ||
2669 mTethering.getTetherableWifiRegexs().length != 0 ||
2670 mTethering.getTetherableBluetoothRegexs().length != 0) &&
2671 mTethering.getUpstreamIfaceTypes().length != 0);
Robert Greenwalt2a091d72010-02-11 18:18:40 -08002672 }
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002673
Robert Greenwalt17c3e0f2014-07-02 09:59:16 -07002674 // Called when we lose the default network and have no replacement yet.
2675 // This will automatically be cleared after X seconds or a new default network
2676 // becomes CONNECTED, whichever happens first. The timer is started by the
2677 // first caller and not restarted by subsequent callers.
2678 private void requestNetworkTransitionWakelock(String forWhom) {
Robert Greenwalt27711812014-06-25 16:45:57 -07002679 int serialNum = 0;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002680 synchronized (this) {
2681 if (mNetTransitionWakeLock.isHeld()) return;
Robert Greenwalt27711812014-06-25 16:45:57 -07002682 serialNum = ++mNetTransitionWakeLockSerialNumber;
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002683 mNetTransitionWakeLock.acquire();
2684 mNetTransitionWakeLockCausedBy = forWhom;
2685 }
2686 mHandler.sendMessageDelayed(mHandler.obtainMessage(
Robert Greenwalt27711812014-06-25 16:45:57 -07002687 EVENT_EXPIRE_NET_TRANSITION_WAKELOCK, serialNum, 0),
Robert Greenwalt14f2ef42010-06-15 12:19:37 -07002688 mNetTransitionWakeLockTimeout);
2689 return;
2690 }
Robert Greenwaltca4306c2010-09-09 13:15:32 -07002691
Robert Greenwaltd7085fc2010-09-08 15:24:47 -07002692 // 100 percent is full good, 0 is full bad.
2693 public void reportInetCondition(int networkType, int percentage) {
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07002694 NetworkAgentInfo nai = mLegacyTypeTracker.getNetworkForType(networkType);
Lorenzo Colitti0831f662015-02-11 07:39:20 +09002695 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002696 reportNetworkConnectivity(nai.network, percentage > 50);
Robert Greenwalt8dcc28b2010-09-23 10:05:56 -07002697 }
2698
Paul Jensenbfd17b72015-04-07 12:43:13 -04002699 public void reportNetworkConnectivity(Network network, boolean hasConnectivity) {
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002700 enforceAccessPermission();
2701 enforceInternetPermission();
2702
Paul Jensenbfd17b72015-04-07 12:43:13 -04002703 NetworkAgentInfo nai;
2704 if (network == null) {
2705 nai = getDefaultNetwork();
2706 } else {
2707 nai = getNetworkAgentInfoForNetwork(network);
2708 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002709 if (nai == null) return;
Paul Jensenbfd17b72015-04-07 12:43:13 -04002710 // Revalidate if the app report does not match our current validated state.
2711 if (hasConnectivity == nai.lastValidated) return;
2712 final int uid = Binder.getCallingUid();
2713 if (DBG) {
2714 log("reportNetworkConnectivity(" + nai.network.netId + ", " + hasConnectivity +
2715 ") by " + uid);
2716 }
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002717 synchronized (nai) {
Paul Jensenc8b9a742014-09-30 15:37:41 -04002718 // Validating an uncreated network could result in a call to rematchNetworkAndRequests()
2719 // which isn't meant to work on uncreated networks.
2720 if (!nai.created) return;
2721
Sreeram Ramachandran21b5ee32014-11-12 22:31:52 -08002722 if (isNetworkWithLinkPropertiesBlocked(nai.linkProperties, uid)) return;
Paul Jensen7ccd3df2014-08-29 09:54:01 -04002723
2724 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_FORCE_REEVALUATION, uid);
2725 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07002726 }
2727
Paul Jensen25a217c2015-02-27 22:55:47 -05002728 public void captivePortalAppResponse(Network network, int response, String actionToken) {
2729 if (response == ConnectivityManager.CAPTIVE_PORTAL_APP_RETURN_WANTED_AS_IS) {
2730 enforceConnectivityInternalPermission();
2731 }
2732 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2733 if (nai == null) return;
2734 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_CAPTIVE_PORTAL_APP_FINISHED, response, 0,
2735 actionToken);
2736 }
2737
Paul Jensencee9b512015-05-06 07:32:40 -04002738 private ProxyInfo getDefaultProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002739 // this information is already available as a world read/writable jvm property
2740 // so this API change wouldn't have a benifit. It also breaks the passing
2741 // of proxy info to all the JVMs.
2742 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002743 synchronized (mProxyLock) {
Jason Monk207900c2014-04-25 15:00:09 -04002744 ProxyInfo ret = mGlobalProxy;
Jason Monk602b2322013-07-03 17:04:33 -04002745 if ((ret == null) && !mDefaultProxyDisabled) ret = mDefaultProxy;
2746 return ret;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002747 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002748 }
2749
Paul Jensencee9b512015-05-06 07:32:40 -04002750 public ProxyInfo getProxyForNetwork(Network network) {
2751 if (network == null) return getDefaultProxy();
2752 final ProxyInfo globalProxy = getGlobalProxy();
2753 if (globalProxy != null) return globalProxy;
2754 if (!NetworkUtils.queryUserAccess(Binder.getCallingUid(), network.netId)) return null;
2755 // Don't call getLinkProperties() as it requires ACCESS_NETWORK_STATE permission, which
2756 // caller may not have.
2757 final NetworkAgentInfo nai = getNetworkAgentInfoForNetwork(network);
2758 if (nai == null) return null;
2759 synchronized (nai) {
2760 final ProxyInfo proxyInfo = nai.linkProperties.getHttpProxy();
2761 if (proxyInfo == null) return null;
2762 return new ProxyInfo(proxyInfo);
2763 }
2764 }
2765
Paul Jensene0bef712014-12-10 15:12:18 -05002766 // Convert empty ProxyInfo's to null as null-checks are used to determine if proxies are present
2767 // (e.g. if mGlobalProxy==null fall back to network-specific proxy, if network-specific
2768 // proxy is null then there is no proxy in place).
2769 private ProxyInfo canonicalizeProxyInfo(ProxyInfo proxy) {
2770 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
2771 && (proxy.getPacFileUrl() == null || Uri.EMPTY.equals(proxy.getPacFileUrl()))) {
2772 proxy = null;
2773 }
2774 return proxy;
2775 }
2776
2777 // ProxyInfo equality function with a couple modifications over ProxyInfo.equals() to make it
2778 // better for determining if a new proxy broadcast is necessary:
2779 // 1. Canonicalize empty ProxyInfos to null so an empty proxy compares equal to null so as to
2780 // avoid unnecessary broadcasts.
2781 // 2. Make sure all parts of the ProxyInfo's compare true, including the host when a PAC URL
2782 // is in place. This is important so legacy PAC resolver (see com.android.proxyhandler)
2783 // changes aren't missed. The legacy PAC resolver pretends to be a simple HTTP proxy but
2784 // actually uses the PAC to resolve; this results in ProxyInfo's with PAC URL, host and port
2785 // all set.
2786 private boolean proxyInfoEqual(ProxyInfo a, ProxyInfo b) {
2787 a = canonicalizeProxyInfo(a);
2788 b = canonicalizeProxyInfo(b);
2789 // ProxyInfo.equals() doesn't check hosts when PAC URLs are present, but we need to check
2790 // hosts even when PAC URLs are present to account for the legacy PAC resolver.
2791 return Objects.equals(a, b) && (a == null || Objects.equals(a.getHost(), b.getHost()));
2792 }
2793
Jason Monk207900c2014-04-25 15:00:09 -04002794 public void setGlobalProxy(ProxyInfo proxyProperties) {
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002795 enforceConnectivityInternalPermission();
Jason Monk602b2322013-07-03 17:04:33 -04002796
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002797 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002798 if (proxyProperties == mGlobalProxy) return;
2799 if (proxyProperties != null && proxyProperties.equals(mGlobalProxy)) return;
2800 if (mGlobalProxy != null && mGlobalProxy.equals(proxyProperties)) return;
2801
2802 String host = "";
2803 int port = 0;
2804 String exclList = "";
Jason Monk602b2322013-07-03 17:04:33 -04002805 String pacFileUrl = "";
2806 if (proxyProperties != null && (!TextUtils.isEmpty(proxyProperties.getHost()) ||
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002807 !Uri.EMPTY.equals(proxyProperties.getPacFileUrl()))) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002808 if (!proxyProperties.isValid()) {
2809 if (DBG)
2810 log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2811 return;
2812 }
Jason Monk207900c2014-04-25 15:00:09 -04002813 mGlobalProxy = new ProxyInfo(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002814 host = mGlobalProxy.getHost();
2815 port = mGlobalProxy.getPort();
Jason Monk207900c2014-04-25 15:00:09 -04002816 exclList = mGlobalProxy.getExclusionListAsString();
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002817 if (!Uri.EMPTY.equals(proxyProperties.getPacFileUrl())) {
Jason Monk207900c2014-04-25 15:00:09 -04002818 pacFileUrl = proxyProperties.getPacFileUrl().toString();
Jason Monk602b2322013-07-03 17:04:33 -04002819 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002820 } else {
2821 mGlobalProxy = null;
2822 }
2823 ContentResolver res = mContext.getContentResolver();
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002824 final long token = Binder.clearCallingIdentity();
2825 try {
2826 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST, host);
2827 Settings.Global.putInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, port);
2828 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST,
2829 exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002830 Settings.Global.putString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC, pacFileUrl);
Robert Greenwalta9bebc22013-04-10 15:32:18 -07002831 } finally {
2832 Binder.restoreCallingIdentity(token);
2833 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002834
Jason Monkcf0f97a2014-10-02 15:39:38 -04002835 if (mGlobalProxy == null) {
2836 proxyProperties = mDefaultProxy;
2837 }
2838 sendProxyBroadcast(proxyProperties);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002839 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002840 }
2841
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002842 private void loadGlobalProxy() {
2843 ContentResolver res = mContext.getContentResolver();
Jeff Sharkey625239a2012-09-26 22:03:49 -07002844 String host = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_HOST);
2845 int port = Settings.Global.getInt(res, Settings.Global.GLOBAL_HTTP_PROXY_PORT, 0);
2846 String exclList = Settings.Global.getString(res,
2847 Settings.Global.GLOBAL_HTTP_PROXY_EXCLUSION_LIST);
Jason Monk602b2322013-07-03 17:04:33 -04002848 String pacFileUrl = Settings.Global.getString(res, Settings.Global.GLOBAL_HTTP_PROXY_PAC);
2849 if (!TextUtils.isEmpty(host) || !TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002850 ProxyInfo proxyProperties;
Jason Monk602b2322013-07-03 17:04:33 -04002851 if (!TextUtils.isEmpty(pacFileUrl)) {
Jason Monk207900c2014-04-25 15:00:09 -04002852 proxyProperties = new ProxyInfo(pacFileUrl);
Jason Monk602b2322013-07-03 17:04:33 -04002853 } else {
Jason Monk207900c2014-04-25 15:00:09 -04002854 proxyProperties = new ProxyInfo(host, port, exclList);
Jason Monk602b2322013-07-03 17:04:33 -04002855 }
Raj Mamadgi92d024912013-11-11 13:52:58 -08002856 if (!proxyProperties.isValid()) {
2857 if (DBG) log("Invalid proxy properties, ignoring: " + proxyProperties.toString());
2858 return;
2859 }
2860
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002861 synchronized (mProxyLock) {
Robert Greenwaltb7090d62010-12-02 11:31:00 -08002862 mGlobalProxy = proxyProperties;
2863 }
2864 }
2865 }
2866
Jason Monk207900c2014-04-25 15:00:09 -04002867 public ProxyInfo getGlobalProxy() {
Robert Greenwalte436e4f2013-02-22 14:57:00 -08002868 // this information is already available as a world read/writable jvm property
2869 // so this API change wouldn't have a benifit. It also breaks the passing
2870 // of proxy info to all the JVMs.
2871 // enforceAccessPermission();
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002872 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002873 return mGlobalProxy;
2874 }
2875 }
2876
Jason Monk207900c2014-04-25 15:00:09 -04002877 private void handleApplyDefaultProxy(ProxyInfo proxy) {
Jason Monk602b2322013-07-03 17:04:33 -04002878 if (proxy != null && TextUtils.isEmpty(proxy.getHost())
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002879 && Uri.EMPTY.equals(proxy.getPacFileUrl())) {
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002880 proxy = null;
2881 }
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002882 synchronized (mProxyLock) {
Robert Greenwalt434203a2010-10-11 16:00:27 -07002883 if (mDefaultProxy != null && mDefaultProxy.equals(proxy)) return;
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002884 if (mDefaultProxy == proxy) return; // catches repeated nulls
Robert Greenwalta8dae992013-11-18 09:43:59 -08002885 if (proxy != null && !proxy.isValid()) {
Raj Mamadgi92d024912013-11-11 13:52:58 -08002886 if (DBG) log("Invalid proxy properties, ignoring: " + proxy.toString());
2887 return;
2888 }
Jason Monk56cf1ab2014-04-28 14:57:27 -04002889
2890 // This call could be coming from the PacManager, containing the port of the local
2891 // proxy. If this new proxy matches the global proxy then copy this proxy to the
2892 // global (to get the correct local port), and send a broadcast.
2893 // TODO: Switch PacManager to have its own message to send back rather than
2894 // reusing EVENT_HAS_CHANGED_PROXY and this call to handleApplyDefaultProxy.
Geoffrey Borggaard79adc952014-11-20 14:35:32 -05002895 if ((mGlobalProxy != null) && (proxy != null)
2896 && (!Uri.EMPTY.equals(proxy.getPacFileUrl()))
Jason Monk56cf1ab2014-04-28 14:57:27 -04002897 && proxy.getPacFileUrl().equals(mGlobalProxy.getPacFileUrl())) {
2898 mGlobalProxy = proxy;
2899 sendProxyBroadcast(mGlobalProxy);
2900 return;
2901 }
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002902 mDefaultProxy = proxy;
2903
Robert Greenwalt00e8d4c2013-04-05 17:14:19 -07002904 if (mGlobalProxy != null) return;
Chia-chi Yeh4c12a472011-10-03 15:34:04 -07002905 if (!mDefaultProxyDisabled) {
2906 sendProxyBroadcast(proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002907 }
2908 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002909 }
2910
Paul Jensene0bef712014-12-10 15:12:18 -05002911 // If the proxy has changed from oldLp to newLp, resend proxy broadcast with default proxy.
2912 // This method gets called when any network changes proxy, but the broadcast only ever contains
2913 // the default proxy (even if it hasn't changed).
2914 // TODO: Deprecate the broadcast extras as they aren't necessarily applicable in a multi-network
2915 // world where an app might be bound to a non-default network.
2916 private void updateProxy(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
2917 ProxyInfo newProxyInfo = newLp == null ? null : newLp.getHttpProxy();
2918 ProxyInfo oldProxyInfo = oldLp == null ? null : oldLp.getHttpProxy();
2919
2920 if (!proxyInfoEqual(newProxyInfo, oldProxyInfo)) {
2921 sendProxyBroadcast(getDefaultProxy());
2922 }
2923 }
2924
Robert Greenwalt434203a2010-10-11 16:00:27 -07002925 private void handleDeprecatedGlobalHttpProxy() {
Jeff Sharkey625239a2012-09-26 22:03:49 -07002926 String proxy = Settings.Global.getString(mContext.getContentResolver(),
2927 Settings.Global.HTTP_PROXY);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002928 if (!TextUtils.isEmpty(proxy)) {
2929 String data[] = proxy.split(":");
Andreas Huber7b8e1ea2013-05-28 15:17:37 -07002930 if (data.length == 0) {
2931 return;
2932 }
2933
Robert Greenwalt434203a2010-10-11 16:00:27 -07002934 String proxyHost = data[0];
2935 int proxyPort = 8080;
2936 if (data.length > 1) {
2937 try {
2938 proxyPort = Integer.parseInt(data[1]);
2939 } catch (NumberFormatException e) {
2940 return;
2941 }
2942 }
Jason Monk207900c2014-04-25 15:00:09 -04002943 ProxyInfo p = new ProxyInfo(data[0], proxyPort, "");
Robert Greenwalt434203a2010-10-11 16:00:27 -07002944 setGlobalProxy(p);
2945 }
2946 }
2947
Jason Monk207900c2014-04-25 15:00:09 -04002948 private void sendProxyBroadcast(ProxyInfo proxy) {
2949 if (proxy == null) proxy = new ProxyInfo("", 0, "");
Jason Monk6f8a68f2013-08-23 19:21:25 -04002950 if (mPacManager.setCurrentProxyScriptUrl(proxy)) return;
Robert Greenwalt58d4c592011-08-02 17:18:41 -07002951 if (DBG) log("sending Proxy Broadcast for " + proxy);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002952 Intent intent = new Intent(Proxy.PROXY_CHANGE_ACTION);
Stan Chesnuttb35d67a2011-01-06 11:00:19 -08002953 intent.addFlags(Intent.FLAG_RECEIVER_REPLACE_PENDING |
2954 Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002955 intent.putExtra(Proxy.EXTRA_PROXY_INFO, proxy);
Dianne Hackbornfd8bf5c2012-09-04 18:48:37 -07002956 final long ident = Binder.clearCallingIdentity();
2957 try {
2958 mContext.sendStickyBroadcastAsUser(intent, UserHandle.ALL);
2959 } finally {
2960 Binder.restoreCallingIdentity(ident);
2961 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002962 }
2963
2964 private static class SettingsObserver extends ContentObserver {
Erik Klineda4bfa82015-04-30 12:58:40 +09002965 final private HashMap<Uri, Integer> mUriEventMap;
2966 final private Context mContext;
2967 final private Handler mHandler;
2968
2969 SettingsObserver(Context context, Handler handler) {
2970 super(null);
2971 mUriEventMap = new HashMap<Uri, Integer>();
2972 mContext = context;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002973 mHandler = handler;
Robert Greenwalt434203a2010-10-11 16:00:27 -07002974 }
2975
Erik Klineda4bfa82015-04-30 12:58:40 +09002976 void observe(Uri uri, int what) {
2977 mUriEventMap.put(uri, what);
2978 final ContentResolver resolver = mContext.getContentResolver();
2979 resolver.registerContentObserver(uri, false, this);
Robert Greenwalt434203a2010-10-11 16:00:27 -07002980 }
2981
2982 @Override
2983 public void onChange(boolean selfChange) {
Erik Klineda4bfa82015-04-30 12:58:40 +09002984 Slog.wtf(TAG, "Should never be reached.");
2985 }
2986
2987 @Override
2988 public void onChange(boolean selfChange, Uri uri) {
2989 final Integer what = mUriEventMap.get(uri);
2990 if (what != null) {
2991 mHandler.obtainMessage(what.intValue()).sendToTarget();
2992 } else {
2993 loge("No matching event to send for URI=" + uri);
2994 }
Robert Greenwalt434203a2010-10-11 16:00:27 -07002995 }
2996 }
Wink Savilleed9c02b2010-12-03 12:01:38 -08002997
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07002998 private static void log(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08002999 Slog.d(TAG, s);
3000 }
3001
Jeff Sharkeyfb878b62012-07-26 18:32:30 -07003002 private static void loge(String s) {
Wink Savilleed9c02b2010-12-03 12:01:38 -08003003 Slog.e(TAG, s);
3004 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003005
Jeff Sharkeyc006f1a2011-05-19 17:12:49 -07003006 private static <T> T checkNotNull(T value, String message) {
3007 if (value == null) {
3008 throw new NullPointerException(message);
3009 }
3010 return value;
3011 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003012
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003013 /**
Jeff Davidson11008a72014-11-20 13:12:46 -08003014 * Prepare for a VPN application.
Robin Lee3b3dd942015-05-12 18:14:58 +01003015 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3016 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3017 *
3018 * @param oldPackage Package name of the application which currently controls VPN, which will
3019 * be replaced. If there is no such application, this should should either be
3020 * {@code null} or {@link VpnConfig.LEGACY_VPN}.
3021 * @param newPackage Package name of the application which should gain control of VPN, or
3022 * {@code null} to disable.
3023 * @param userId User for whom to prepare the new VPN.
3024 *
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003025 * @hide
3026 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003027 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003028 public boolean prepareVpn(@Nullable String oldPackage, @Nullable String newPackage,
3029 int userId) {
3030 enforceCrossUserPermission(userId);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003031 throwIfLockdownEnabled();
Robin Lee3b3dd942015-05-12 18:14:58 +01003032
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003033 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003034 Vpn vpn = mVpns.get(userId);
3035 if (vpn != null) {
3036 return vpn.prepare(oldPackage, newPackage);
3037 } else {
3038 return false;
3039 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003040 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003041 }
3042
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003043 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003044 * Set whether the VPN package has the ability to launch VPNs without user intervention.
3045 * This method is used by system-privileged apps.
3046 * VPN permissions are checked in the {@link Vpn} class. If the caller is not {@code userId},
3047 * {@link android.Manifest.permission.INTERACT_ACROSS_USERS_FULL} permission is required.
3048 *
3049 * @param packageName The package for which authorization state should change.
3050 * @param userId User for whom {@code packageName} is installed.
3051 * @param authorized {@code true} if this app should be able to start a VPN connection without
3052 * explicit user approval, {@code false} if not.
3053 *
Jeff Davidson05542602014-08-11 14:07:27 -07003054 * @hide
3055 */
3056 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003057 public void setVpnPackageAuthorization(String packageName, int userId, boolean authorized) {
3058 enforceCrossUserPermission(userId);
3059
Jeff Davidson05542602014-08-11 14:07:27 -07003060 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003061 Vpn vpn = mVpns.get(userId);
3062 if (vpn != null) {
3063 vpn.setPackageAuthorization(packageName, authorized);
3064 }
Jeff Davidson05542602014-08-11 14:07:27 -07003065 }
3066 }
3067
3068 /**
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003069 * Configure a TUN interface and return its file descriptor. Parameters
3070 * are encoded and opaque to this class. This method is used by VpnBuilder
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003071 * and not available in ConnectivityManager. Permissions are checked in
3072 * Vpn class.
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003073 * @hide
3074 */
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003075 @Override
Chia-chi Yeh04ba25c2011-06-15 17:07:27 -07003076 public ParcelFileDescriptor establishVpn(VpnConfig config) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003077 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003078 int user = UserHandle.getUserId(Binder.getCallingUid());
3079 synchronized(mVpns) {
3080 return mVpns.get(user).establish(config);
3081 }
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003082 }
3083
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003084 /**
Jeff Sharkey82f85212012-08-24 11:17:25 -07003085 * Start legacy VPN, controlling native daemons as needed. Creates a
3086 * secondary thread to perform connection work, returning quickly.
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003087 */
3088 @Override
Jeff Sharkey82f85212012-08-24 11:17:25 -07003089 public void startLegacyVpn(VpnProfile profile) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003090 throwIfLockdownEnabled();
Jeff Sharkey82f85212012-08-24 11:17:25 -07003091 final LinkProperties egress = getActiveLinkProperties();
3092 if (egress == null) {
3093 throw new IllegalStateException("Missing active network connection");
3094 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003095 int user = UserHandle.getUserId(Binder.getCallingUid());
3096 synchronized(mVpns) {
3097 mVpns.get(user).startLegacyVpn(profile, mKeyStore, egress);
3098 }
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003099 }
3100
3101 /**
3102 * Return the information of the ongoing legacy VPN. This method is used
3103 * by VpnSettings and not available in ConnectivityManager. Permissions
3104 * are checked in Vpn class.
Chia-chi Yeh2e467642011-07-04 03:23:12 -07003105 */
3106 @Override
3107 public LegacyVpnInfo getLegacyVpnInfo() {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003108 throwIfLockdownEnabled();
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003109 int user = UserHandle.getUserId(Binder.getCallingUid());
3110 synchronized(mVpns) {
3111 return mVpns.get(user).getLegacyVpnInfo();
3112 }
Chia-chi Yeh77fd4852011-07-02 17:15:00 -07003113 }
3114
Chia-chi Yehff3bdca2011-05-23 17:26:46 -07003115 /**
Wenchao Tongf5ea3402015-03-04 13:26:38 -08003116 * Return the information of all ongoing VPNs. This method is used by NetworkStatsService
3117 * and not available in ConnectivityManager.
3118 */
3119 @Override
3120 public VpnInfo[] getAllVpnInfo() {
3121 enforceConnectivityInternalPermission();
3122 if (mLockdownEnabled) {
3123 return new VpnInfo[0];
3124 }
3125
3126 synchronized(mVpns) {
3127 List<VpnInfo> infoList = new ArrayList<>();
3128 for (int i = 0; i < mVpns.size(); i++) {
3129 VpnInfo info = createVpnInfo(mVpns.valueAt(i));
3130 if (info != null) {
3131 infoList.add(info);
3132 }
3133 }
3134 return infoList.toArray(new VpnInfo[infoList.size()]);
3135 }
3136 }
3137
3138 /**
3139 * @return VPN information for accounting, or null if we can't retrieve all required
3140 * information, e.g primary underlying iface.
3141 */
3142 @Nullable
3143 private VpnInfo createVpnInfo(Vpn vpn) {
3144 VpnInfo info = vpn.getVpnInfo();
3145 if (info == null) {
3146 return null;
3147 }
3148 Network[] underlyingNetworks = vpn.getUnderlyingNetworks();
3149 // see VpnService.setUnderlyingNetworks()'s javadoc about how to interpret
3150 // the underlyingNetworks list.
3151 if (underlyingNetworks == null) {
3152 NetworkAgentInfo defaultNetwork = getDefaultNetwork();
3153 if (defaultNetwork != null && defaultNetwork.linkProperties != null) {
3154 info.primaryUnderlyingIface = getDefaultNetwork().linkProperties.getInterfaceName();
3155 }
3156 } else if (underlyingNetworks.length > 0) {
3157 LinkProperties linkProperties = getLinkProperties(underlyingNetworks[0]);
3158 if (linkProperties != null) {
3159 info.primaryUnderlyingIface = linkProperties.getInterfaceName();
3160 }
3161 }
3162 return info.primaryUnderlyingIface == null ? null : info;
3163 }
3164
3165 /**
Robin Lee3b3dd942015-05-12 18:14:58 +01003166 * Returns the information of the ongoing VPN for {@code userId}. This method is used by
3167 * VpnDialogs and not available in ConnectivityManager.
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003168 * Permissions are checked in Vpn class.
3169 * @hide
3170 */
3171 @Override
Robin Lee3b3dd942015-05-12 18:14:58 +01003172 public VpnConfig getVpnConfig(int userId) {
3173 enforceCrossUserPermission(userId);
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003174 synchronized(mVpns) {
Robin Lee47283452015-06-01 10:57:03 -07003175 Vpn vpn = mVpns.get(userId);
3176 if (vpn != null) {
3177 return vpn.getVpnConfig();
3178 } else {
3179 return null;
3180 }
Chad Brubakerbf6ff2c2013-07-16 18:59:12 -07003181 }
3182 }
3183
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003184 @Override
3185 public boolean updateLockdownVpn() {
Jeff Sharkey3671b1e2013-01-31 17:22:26 -08003186 if (Binder.getCallingUid() != Process.SYSTEM_UID) {
3187 Slog.w(TAG, "Lockdown VPN only available to AID_SYSTEM");
3188 return false;
3189 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003190
3191 // Tear down existing lockdown if profile was removed
3192 mLockdownEnabled = LockdownVpnTracker.isEnabled();
3193 if (mLockdownEnabled) {
Kenny Rootb9594ce2013-02-14 10:18:38 -08003194 if (!mKeyStore.isUnlocked()) {
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003195 Slog.w(TAG, "KeyStore locked; unable to create LockdownTracker");
3196 return false;
3197 }
3198
3199 final String profileName = new String(mKeyStore.get(Credentials.LOCKDOWN_VPN));
3200 final VpnProfile profile = VpnProfile.decode(
3201 profileName, mKeyStore.get(Credentials.VPN + profileName));
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003202 int user = UserHandle.getUserId(Binder.getCallingUid());
3203 synchronized(mVpns) {
3204 setLockdownTracker(new LockdownVpnTracker(mContext, mNetd, this, mVpns.get(user),
3205 profile));
3206 }
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003207 } else {
3208 setLockdownTracker(null);
3209 }
3210
3211 return true;
3212 }
3213
3214 /**
3215 * Internally set new {@link LockdownVpnTracker}, shutting down any existing
3216 * {@link LockdownVpnTracker}. Can be {@code null} to disable lockdown.
3217 */
3218 private void setLockdownTracker(LockdownVpnTracker tracker) {
3219 // Shutdown any existing tracker
3220 final LockdownVpnTracker existing = mLockdownTracker;
3221 mLockdownTracker = null;
3222 if (existing != null) {
3223 existing.shutdown();
3224 }
3225
3226 try {
3227 if (tracker != null) {
3228 mNetd.setFirewallEnabled(true);
Jeff Sharkey812085b2013-02-28 16:57:58 -08003229 mNetd.setFirewallInterfaceRule("lo", true);
Jeff Sharkey69ddab42012-08-25 00:05:46 -07003230 mLockdownTracker = tracker;
3231 mLockdownTracker.init();
3232 } else {
3233 mNetd.setFirewallEnabled(false);
3234 }
3235 } catch (RemoteException e) {
3236 // ignored; NMS lives inside system_server
3237 }
3238 }
3239
3240 private void throwIfLockdownEnabled() {
3241 if (mLockdownEnabled) {
3242 throw new IllegalStateException("Unavailable in lockdown mode");
3243 }
3244 }
Robert Greenwalt665e1ae2012-08-21 19:27:00 -07003245
Wink Savilleab9321d2013-06-29 21:10:57 -07003246 @Override
Wink Saville948282b2013-08-29 08:55:16 -07003247 public int checkMobileProvisioning(int suggestedTimeOutMs) {
Paul Jensen89e0f092014-09-15 15:59:36 -04003248 // TODO: Remove? Any reason to trigger a provisioning check?
3249 return -1;
Wink Saville948282b2013-08-29 08:55:16 -07003250 }
3251
3252 private static final String NOTIFICATION_ID = "CaptivePortal.Notification";
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003253 private static enum NotificationType { SIGN_IN, NO_INTERNET; };
Wink Saville948282b2013-08-29 08:55:16 -07003254
Paul Jensen89e0f092014-09-15 15:59:36 -04003255 private void setProvNotificationVisible(boolean visible, int networkType, String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003256 if (DBG) {
3257 log("setProvNotificationVisible: E visible=" + visible + " networkType=" + networkType
Paul Jensen89e0f092014-09-15 15:59:36 -04003258 + " action=" + action);
Wink Saville948282b2013-08-29 08:55:16 -07003259 }
Paul Jensen89e0f092014-09-15 15:59:36 -04003260 Intent intent = new Intent(action);
3261 PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003262 // Concatenate the range of types onto the range of NetIDs.
3263 int id = MAX_NET_ID + 1 + (networkType - ConnectivityManager.TYPE_NONE);
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003264 setProvNotificationVisibleIntent(visible, id, NotificationType.SIGN_IN,
3265 networkType, null, pendingIntent);
Paul Jensen869868be2014-05-15 10:33:05 -04003266 }
3267
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003268 /**
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003269 * Show or hide network provisioning notifications.
3270 *
3271 * We use notifications for two purposes: to notify that a network requires sign in
3272 * (NotificationType.SIGN_IN), or to notify that a network does not have Internet access
3273 * (NotificationType.NO_INTERNET). We display at most one notification per ID, so on a
3274 * particular network we can display the notification type that was most recently requested.
3275 * So for example if a captive portal fails to reply within a few seconds of connecting, we
3276 * might first display NO_INTERNET, and then when the captive portal check completes, display
3277 * SIGN_IN.
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003278 *
3279 * @param id an identifier that uniquely identifies this notification. This must match
3280 * between show and hide calls. We use the NetID value but for legacy callers
3281 * we concatenate the range of types with the range of NetIDs.
3282 */
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003283 private void setProvNotificationVisibleIntent(boolean visible, int id,
3284 NotificationType notifyType, int networkType, String extraInfo, PendingIntent intent) {
Paul Jensen869868be2014-05-15 10:33:05 -04003285 if (DBG) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003286 log("setProvNotificationVisibleIntent " + notifyType + " visible=" + visible
3287 + " networkType=" + getNetworkTypeName(networkType)
3288 + " extraInfo=" + extraInfo);
Paul Jensen869868be2014-05-15 10:33:05 -04003289 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003290
3291 Resources r = Resources.getSystem();
3292 NotificationManager notificationManager = (NotificationManager) mContext
3293 .getSystemService(Context.NOTIFICATION_SERVICE);
3294
3295 if (visible) {
3296 CharSequence title;
3297 CharSequence details;
3298 int icon;
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003299 if (notifyType == NotificationType.NO_INTERNET &&
3300 networkType == ConnectivityManager.TYPE_WIFI) {
3301 title = r.getString(R.string.wifi_no_internet, 0);
3302 details = r.getString(R.string.wifi_no_internet_detailed);
3303 icon = R.drawable.stat_notify_wifi_in_range; // TODO: Need new icon.
3304 } else if (notifyType == NotificationType.SIGN_IN) {
3305 switch (networkType) {
3306 case ConnectivityManager.TYPE_WIFI:
3307 title = r.getString(R.string.wifi_available_sign_in, 0);
3308 details = r.getString(R.string.network_available_sign_in_detailed,
3309 extraInfo);
3310 icon = R.drawable.stat_notify_wifi_in_range;
3311 break;
3312 case ConnectivityManager.TYPE_MOBILE:
3313 case ConnectivityManager.TYPE_MOBILE_HIPRI:
3314 title = r.getString(R.string.network_available_sign_in, 0);
3315 // TODO: Change this to pull from NetworkInfo once a printable
3316 // name has been added to it
3317 details = mTelephonyManager.getNetworkOperatorName();
3318 icon = R.drawable.stat_notify_rssi_in_range;
3319 break;
3320 default:
3321 title = r.getString(R.string.network_available_sign_in, 0);
3322 details = r.getString(R.string.network_available_sign_in_detailed,
3323 extraInfo);
3324 icon = R.drawable.stat_notify_rssi_in_range;
3325 break;
3326 }
3327 } else {
3328 Slog.wtf(TAG, "Unknown notification type " + notifyType + "on network type "
3329 + getNetworkTypeName(networkType));
3330 return;
Wink Savilleab9321d2013-06-29 21:10:57 -07003331 }
3332
Chris Wren1ce4b6d2015-06-11 10:19:43 -04003333 Notification notification = new Notification.Builder(mContext)
3334 .setWhen(0)
3335 .setSmallIcon(icon)
3336 .setAutoCancel(true)
3337 .setTicker(title)
3338 .setColor(mContext.getColor(
3339 com.android.internal.R.color.system_notification_accent_color))
3340 .setContentTitle(title)
3341 .setContentText(details)
3342 .setContentIntent(intent)
3343 .build();
Wink Savilleab9321d2013-06-29 21:10:57 -07003344
Wink Saville948282b2013-08-29 08:55:16 -07003345 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003346 notificationManager.notify(NOTIFICATION_ID, id, notification);
Wink Saville948282b2013-08-29 08:55:16 -07003347 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003348 loge("setNotificationVisible: visible notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003349 npe.printStackTrace();
3350 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003351 } else {
Wink Saville948282b2013-08-29 08:55:16 -07003352 try {
Paul Jensenfdc4e4a2014-07-15 12:07:36 -04003353 notificationManager.cancel(NOTIFICATION_ID, id);
Wink Saville948282b2013-08-29 08:55:16 -07003354 } catch (NullPointerException npe) {
Lorenzo Colittif6673d02015-05-21 16:17:05 +09003355 loge("setNotificationVisible: cancel notificationManager npe=" + npe);
Wink Saville948282b2013-08-29 08:55:16 -07003356 npe.printStackTrace();
3357 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003358 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003359 }
3360
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003361 /** Location to an updatable file listing carrier provisioning urls.
3362 * An example:
3363 *
3364 * <?xml version="1.0" encoding="utf-8"?>
3365 * <provisioningUrls>
3366 * <provisioningUrl mcc="310" mnc="4">http://myserver.com/foo?mdn=%3$s&amp;iccid=%1$s&amp;imei=%2$s</provisioningUrl>
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003367 * </provisioningUrls>
3368 */
3369 private static final String PROVISIONING_URL_PATH =
3370 "/data/misc/radio/provisioning_urls.xml";
3371 private final File mProvisioningUrlFile = new File(PROVISIONING_URL_PATH);
Wink Savilleab9321d2013-06-29 21:10:57 -07003372
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003373 /** XML tag for root element. */
3374 private static final String TAG_PROVISIONING_URLS = "provisioningUrls";
3375 /** XML tag for individual url */
3376 private static final String TAG_PROVISIONING_URL = "provisioningUrl";
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003377 /** XML attribute for mcc */
3378 private static final String ATTR_MCC = "mcc";
3379 /** XML attribute for mnc */
3380 private static final String ATTR_MNC = "mnc";
3381
Paul Jensen434dde82015-06-11 09:43:30 -04003382 private String getProvisioningUrlBaseFromFile() {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003383 FileReader fileReader = null;
3384 XmlPullParser parser = null;
3385 Configuration config = mContext.getResources().getConfiguration();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003386
3387 try {
3388 fileReader = new FileReader(mProvisioningUrlFile);
3389 parser = Xml.newPullParser();
3390 parser.setInput(fileReader);
3391 XmlUtils.beginDocument(parser, TAG_PROVISIONING_URLS);
3392
3393 while (true) {
3394 XmlUtils.nextElement(parser);
3395
3396 String element = parser.getName();
3397 if (element == null) break;
3398
Paul Jensen434dde82015-06-11 09:43:30 -04003399 if (element.equals(TAG_PROVISIONING_URL)) {
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003400 String mcc = parser.getAttributeValue(null, ATTR_MCC);
3401 try {
3402 if (mcc != null && Integer.parseInt(mcc) == config.mcc) {
3403 String mnc = parser.getAttributeValue(null, ATTR_MNC);
3404 if (mnc != null && Integer.parseInt(mnc) == config.mnc) {
3405 parser.next();
3406 if (parser.getEventType() == XmlPullParser.TEXT) {
3407 return parser.getText();
3408 }
3409 }
3410 }
3411 } catch (NumberFormatException e) {
3412 loge("NumberFormatException in getProvisioningUrlBaseFromFile: " + e);
3413 }
3414 }
3415 }
3416 return null;
3417 } catch (FileNotFoundException e) {
3418 loge("Carrier Provisioning Urls file not found");
3419 } catch (XmlPullParserException e) {
3420 loge("Xml parser exception reading Carrier Provisioning Urls file: " + e);
3421 } catch (IOException e) {
3422 loge("I/O exception reading Carrier Provisioning Urls file: " + e);
3423 } finally {
3424 if (fileReader != null) {
3425 try {
3426 fileReader.close();
3427 } catch (IOException e) {}
3428 }
3429 }
3430 return null;
3431 }
3432
Wink Saville42d4f082013-07-20 20:31:59 -07003433 @Override
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003434 public String getMobileProvisioningUrl() {
3435 enforceConnectivityInternalPermission();
Paul Jensen434dde82015-06-11 09:43:30 -04003436 String url = getProvisioningUrlBaseFromFile();
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003437 if (TextUtils.isEmpty(url)) {
3438 url = mContext.getResources().getString(R.string.mobile_provisioning_url);
Wink Saville42d4f082013-07-20 20:31:59 -07003439 log("getMobileProvisioningUrl: mobile_provisioining_url from resource =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003440 } else {
Wink Saville42d4f082013-07-20 20:31:59 -07003441 log("getMobileProvisioningUrl: mobile_provisioning_url from File =" + url);
Robert Greenwalte182bfe2013-07-16 12:06:09 -07003442 }
Wink Saville8cf35602013-07-10 23:00:07 -07003443 // populate the iccid, imei and phone number in the provisioning url.
Wink Savilleab9321d2013-06-29 21:10:57 -07003444 if (!TextUtils.isEmpty(url)) {
Wink Saville8cf35602013-07-10 23:00:07 -07003445 String phoneNumber = mTelephonyManager.getLine1Number();
3446 if (TextUtils.isEmpty(phoneNumber)) {
3447 phoneNumber = "0000000000";
3448 }
Wink Savilleab9321d2013-06-29 21:10:57 -07003449 url = String.format(url,
3450 mTelephonyManager.getSimSerialNumber() /* ICCID */,
3451 mTelephonyManager.getDeviceId() /* IMEI */,
Wink Saville8cf35602013-07-10 23:00:07 -07003452 phoneNumber /* Phone numer */);
Wink Savilleab9321d2013-06-29 21:10:57 -07003453 }
3454
Wink Savilleab9321d2013-06-29 21:10:57 -07003455 return url;
3456 }
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003457
Wink Saville948282b2013-08-29 08:55:16 -07003458 @Override
3459 public void setProvisioningNotificationVisible(boolean visible, int networkType,
Paul Jensen89e0f092014-09-15 15:59:36 -04003460 String action) {
Wink Saville948282b2013-08-29 08:55:16 -07003461 enforceConnectivityInternalPermission();
Paul Jensen89e0f092014-09-15 15:59:36 -04003462 final long ident = Binder.clearCallingIdentity();
3463 try {
3464 setProvNotificationVisible(visible, networkType, action);
3465 } finally {
3466 Binder.restoreCallingIdentity(ident);
3467 }
Wink Saville948282b2013-08-29 08:55:16 -07003468 }
Wink Saville7788c612013-08-29 14:57:08 -07003469
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003470 @Override
3471 public void setAirplaneMode(boolean enable) {
3472 enforceConnectivityInternalPermission();
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003473 final long ident = Binder.clearCallingIdentity();
3474 try {
Yuhao Zheng5530e4b2013-09-11 09:36:41 -07003475 final ContentResolver cr = mContext.getContentResolver();
3476 Settings.Global.putInt(cr, Settings.Global.AIRPLANE_MODE_ON, enable ? 1 : 0);
3477 Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
3478 intent.putExtra("state", enable);
xinhe98e25fc2014-11-17 11:35:01 -08003479 mContext.sendBroadcastAsUser(intent, UserHandle.ALL);
Yuhao Zheng5cd1a0e2013-09-09 17:00:04 -07003480 } finally {
3481 Binder.restoreCallingIdentity(ident);
3482 }
3483 }
3484
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003485 private void onUserStart(int userId) {
3486 synchronized(mVpns) {
3487 Vpn userVpn = mVpns.get(userId);
3488 if (userVpn != null) {
3489 loge("Starting user already has a VPN");
3490 return;
3491 }
Paul Jensene75b9e32015-04-06 11:54:53 -04003492 userVpn = new Vpn(mHandler.getLooper(), mContext, mNetd, userId);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003493 mVpns.put(userId, userVpn);
Chad Brubaker4ca19e82013-06-14 11:16:51 -07003494 }
3495 }
3496
3497 private void onUserStop(int userId) {
3498 synchronized(mVpns) {
3499 Vpn userVpn = mVpns.get(userId);
3500 if (userVpn == null) {
3501 loge("Stopping user has no VPN");
3502 return;
3503 }
3504 mVpns.delete(userId);
3505 }
3506 }
3507
3508 private BroadcastReceiver mUserIntentReceiver = new BroadcastReceiver() {
3509 @Override
3510 public void onReceive(Context context, Intent intent) {
3511 final String action = intent.getAction();
3512 final int userId = intent.getIntExtra(Intent.EXTRA_USER_HANDLE, UserHandle.USER_NULL);
3513 if (userId == UserHandle.USER_NULL) return;
3514
3515 if (Intent.ACTION_USER_STARTING.equals(action)) {
3516 onUserStart(userId);
3517 } else if (Intent.ACTION_USER_STOPPING.equals(action)) {
3518 onUserStop(userId);
3519 }
3520 }
3521 };
Vinit Deshapnde1f12cb52013-08-21 13:09:01 -07003522
Robert Greenwalta67be032014-05-16 15:49:14 -07003523 private final HashMap<Messenger, NetworkFactoryInfo> mNetworkFactoryInfos =
3524 new HashMap<Messenger, NetworkFactoryInfo>();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003525 private final HashMap<NetworkRequest, NetworkRequestInfo> mNetworkRequests =
3526 new HashMap<NetworkRequest, NetworkRequestInfo>();
Robert Greenwalte049c232014-04-11 15:53:27 -07003527
Robert Greenwalta67be032014-05-16 15:49:14 -07003528 private static class NetworkFactoryInfo {
3529 public final String name;
3530 public final Messenger messenger;
3531 public final AsyncChannel asyncChannel;
3532
3533 public NetworkFactoryInfo(String name, Messenger messenger, AsyncChannel asyncChannel) {
3534 this.name = name;
3535 this.messenger = messenger;
3536 this.asyncChannel = asyncChannel;
3537 }
3538 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003539
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003540 /**
3541 * Tracks info about the requester.
3542 * Also used to notice when the calling process dies so we can self-expire
3543 */
Robert Greenwalt9258c642014-03-26 16:47:06 -07003544 private class NetworkRequestInfo implements IBinder.DeathRecipient {
3545 static final boolean REQUEST = true;
3546 static final boolean LISTEN = false;
3547
3548 final NetworkRequest request;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003549 final PendingIntent mPendingIntent;
Jeremy Joslin79294842014-12-03 17:15:28 -08003550 boolean mPendingIntentSent;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003551 private final IBinder mBinder;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003552 final int mPid;
3553 final int mUid;
3554 final Messenger messenger;
3555 final boolean isRequest;
3556
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003557 NetworkRequestInfo(NetworkRequest r, PendingIntent pi, boolean isRequest) {
3558 request = r;
3559 mPendingIntent = pi;
3560 messenger = null;
3561 mBinder = null;
3562 mPid = getCallingPid();
3563 mUid = getCallingUid();
3564 this.isRequest = isRequest;
3565 }
3566
Robert Greenwalt9258c642014-03-26 16:47:06 -07003567 NetworkRequestInfo(Messenger m, NetworkRequest r, IBinder binder, boolean isRequest) {
3568 super();
3569 messenger = m;
3570 request = r;
3571 mBinder = binder;
3572 mPid = getCallingPid();
3573 mUid = getCallingUid();
3574 this.isRequest = isRequest;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003575 mPendingIntent = null;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003576
3577 try {
3578 mBinder.linkToDeath(this, 0);
3579 } catch (RemoteException e) {
3580 binderDied();
3581 }
3582 }
3583
3584 void unlinkDeathRecipient() {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003585 if (mBinder != null) {
3586 mBinder.unlinkToDeath(this, 0);
3587 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003588 }
3589
3590 public void binderDied() {
3591 log("ConnectivityService NetworkRequestInfo binderDied(" +
3592 request + ", " + mBinder + ")");
3593 releaseNetworkRequest(request);
3594 }
Robert Greenwalta67be032014-05-16 15:49:14 -07003595
3596 public String toString() {
3597 return (isRequest ? "Request" : "Listen") + " from uid/pid:" + mUid + "/" +
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003598 mPid + " for " + request +
3599 (mPendingIntent == null ? "" : " to trigger " + mPendingIntent);
Robert Greenwalta67be032014-05-16 15:49:14 -07003600 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003601 }
3602
3603 @Override
3604 public NetworkRequest requestNetwork(NetworkCapabilities networkCapabilities,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003605 Messenger messenger, int timeoutMs, IBinder binder, int legacyType) {
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003606 networkCapabilities = new NetworkCapabilities(networkCapabilities);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003607 enforceNetworkRequestPermissions(networkCapabilities);
3608 enforceMeteredApnPolicy(networkCapabilities);
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003609
Robert Greenwalt6078b502014-06-11 16:05:07 -07003610 if (timeoutMs < 0 || timeoutMs > ConnectivityManager.MAX_NETWORK_REQUEST_TIMEOUT_MS) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003611 throw new IllegalArgumentException("Bad timeout specified");
3612 }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003613
Robert Greenwalt39fa65a2014-07-27 10:56:49 -07003614 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, legacyType,
3615 nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003616 if (DBG) log("requestNetwork for " + networkRequest);
3617 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3618 NetworkRequestInfo.REQUEST);
3619
3620 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST, nri));
Robert Greenwalt6078b502014-06-11 16:05:07 -07003621 if (timeoutMs > 0) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07003622 mHandler.sendMessageDelayed(mHandler.obtainMessage(EVENT_TIMEOUT_NETWORK_REQUEST,
Robert Greenwalt6078b502014-06-11 16:05:07 -07003623 nri), timeoutMs);
Robert Greenwalt9258c642014-03-26 16:47:06 -07003624 }
3625 return networkRequest;
3626 }
3627
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003628 private void enforceNetworkRequestPermissions(NetworkCapabilities networkCapabilities) {
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003629 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_RESTRICTED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003630 enforceConnectivityInternalPermission();
3631 } else {
3632 enforceChangePermission();
3633 }
3634 }
3635
fenglub15e72b2015-03-20 11:29:56 -07003636 @Override
fengludb571472015-04-21 17:12:05 -07003637 public boolean requestBandwidthUpdate(Network network) {
fenglub15e72b2015-03-20 11:29:56 -07003638 enforceAccessPermission();
3639 NetworkAgentInfo nai = null;
3640 if (network == null) {
3641 return false;
3642 }
3643 synchronized (mNetworkForNetId) {
3644 nai = mNetworkForNetId.get(network.netId);
3645 }
3646 if (nai != null) {
3647 nai.asyncChannel.sendMessage(android.net.NetworkAgent.CMD_REQUEST_BANDWIDTH_UPDATE);
3648 return true;
3649 }
3650 return false;
3651 }
3652
3653
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003654 private void enforceMeteredApnPolicy(NetworkCapabilities networkCapabilities) {
3655 // if UID is restricted, don't allow them to bring up metered APNs
Lorenzo Colitti76f67792015-05-14 17:28:27 +09003656 if (networkCapabilities.hasCapability(NET_CAPABILITY_NOT_METERED) == false) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003657 final int uidRules;
3658 final int uid = Binder.getCallingUid();
3659 synchronized(mRulesLock) {
3660 uidRules = mUidRules.get(uid, RULE_ALLOW_ALL);
3661 }
Amith Yamasani15e472352015-04-24 19:06:07 -07003662 if ((uidRules & (RULE_REJECT_METERED | RULE_REJECT_ALL)) != 0) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003663 // we could silently fail or we can filter the available nets to only give
3664 // them those they have access to. Chose the more useful
Lorenzo Colitti8deb3412015-05-14 17:07:20 +09003665 networkCapabilities.addCapability(NET_CAPABILITY_NOT_METERED);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003666 }
3667 }
3668 }
3669
Robert Greenwalt9258c642014-03-26 16:47:06 -07003670 @Override
3671 public NetworkRequest pendingRequestForNetwork(NetworkCapabilities networkCapabilities,
3672 PendingIntent operation) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003673 checkNotNull(operation, "PendingIntent cannot be null.");
3674 networkCapabilities = new NetworkCapabilities(networkCapabilities);
3675 enforceNetworkRequestPermissions(networkCapabilities);
3676 enforceMeteredApnPolicy(networkCapabilities);
3677
3678 NetworkRequest networkRequest = new NetworkRequest(networkCapabilities, TYPE_NONE,
3679 nextNetworkRequestId());
3680 if (DBG) log("pendingRequest for " + networkRequest + " to trigger " + operation);
3681 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3682 NetworkRequestInfo.REQUEST);
3683 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_REQUEST_WITH_INTENT,
3684 nri));
3685 return networkRequest;
3686 }
3687
Jeremy Joslin79294842014-12-03 17:15:28 -08003688 private void releasePendingNetworkRequestWithDelay(PendingIntent operation) {
3689 mHandler.sendMessageDelayed(
3690 mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3691 getCallingUid(), 0, operation), mReleasePendingIntentDelayMs);
3692 }
3693
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003694 @Override
3695 public void releasePendingNetworkRequest(PendingIntent operation) {
Paul Jensen1a81c392015-05-21 08:15:08 -04003696 checkNotNull(operation, "PendingIntent cannot be null.");
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08003697 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST_WITH_INTENT,
3698 getCallingUid(), 0, operation));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003699 }
3700
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003701 // In order to implement the compatibility measure for pre-M apps that call
3702 // WifiManager.enableNetwork(..., true) without also binding to that network explicitly,
3703 // WifiManager registers a network listen for the purpose of calling setProcessDefaultNetwork.
3704 // This ensures it has permission to do so.
3705 private boolean hasWifiNetworkListenPermission(NetworkCapabilities nc) {
3706 if (nc == null) {
3707 return false;
3708 }
3709 int[] transportTypes = nc.getTransportTypes();
3710 if (transportTypes.length != 1 || transportTypes[0] != NetworkCapabilities.TRANSPORT_WIFI) {
3711 return false;
3712 }
3713 try {
3714 mContext.enforceCallingOrSelfPermission(
3715 android.Manifest.permission.ACCESS_WIFI_STATE,
3716 "ConnectivityService");
3717 } catch (SecurityException e) {
3718 return false;
3719 }
3720 return true;
3721 }
3722
Robert Greenwalt9258c642014-03-26 16:47:06 -07003723 @Override
3724 public NetworkRequest listenForNetwork(NetworkCapabilities networkCapabilities,
3725 Messenger messenger, IBinder binder) {
Lorenzo Colittifa57c482015-04-22 10:44:49 +09003726 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3727 enforceAccessPermission();
3728 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07003729
3730 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07003731 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
Robert Greenwalt9258c642014-03-26 16:47:06 -07003732 if (DBG) log("listenForNetwork for " + networkRequest);
3733 NetworkRequestInfo nri = new NetworkRequestInfo(messenger, networkRequest, binder,
3734 NetworkRequestInfo.LISTEN);
3735
3736 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
3737 return networkRequest;
3738 }
3739
3740 @Override
3741 public void pendingListenForNetwork(NetworkCapabilities networkCapabilities,
3742 PendingIntent operation) {
Paul Jensen694f2b82015-06-17 14:15:39 -04003743 checkNotNull(operation, "PendingIntent cannot be null.");
3744 if (!hasWifiNetworkListenPermission(networkCapabilities)) {
3745 enforceAccessPermission();
3746 }
3747
3748 NetworkRequest networkRequest = new NetworkRequest(new NetworkCapabilities(
3749 networkCapabilities), TYPE_NONE, nextNetworkRequestId());
3750 if (DBG) log("pendingListenForNetwork for " + networkRequest + " to trigger " + operation);
3751 NetworkRequestInfo nri = new NetworkRequestInfo(networkRequest, operation,
3752 NetworkRequestInfo.LISTEN);
3753
3754 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_LISTENER, nri));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003755 }
3756
3757 @Override
3758 public void releaseNetworkRequest(NetworkRequest networkRequest) {
Paul Jensen7ecb42f2014-05-16 14:31:12 -04003759 mHandler.sendMessage(mHandler.obtainMessage(EVENT_RELEASE_NETWORK_REQUEST, getCallingUid(),
3760 0, networkRequest));
Robert Greenwalt9258c642014-03-26 16:47:06 -07003761 }
3762
3763 @Override
Robert Greenwalta67be032014-05-16 15:49:14 -07003764 public void registerNetworkFactory(Messenger messenger, String name) {
Robert Greenwalte049c232014-04-11 15:53:27 -07003765 enforceConnectivityInternalPermission();
Robert Greenwalta67be032014-05-16 15:49:14 -07003766 NetworkFactoryInfo nfi = new NetworkFactoryInfo(name, messenger, new AsyncChannel());
3767 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_FACTORY, nfi));
Robert Greenwalte049c232014-04-11 15:53:27 -07003768 }
3769
Robert Greenwalta67be032014-05-16 15:49:14 -07003770 private void handleRegisterNetworkFactory(NetworkFactoryInfo nfi) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003771 if (DBG) log("Got NetworkFactory Messenger for " + nfi.name);
Robert Greenwalta67be032014-05-16 15:49:14 -07003772 mNetworkFactoryInfos.put(nfi.messenger, nfi);
3773 nfi.asyncChannel.connect(mContext, mTrackerHandler, nfi.messenger);
3774 }
3775
3776 @Override
3777 public void unregisterNetworkFactory(Messenger messenger) {
3778 enforceConnectivityInternalPermission();
3779 mHandler.sendMessage(mHandler.obtainMessage(EVENT_UNREGISTER_NETWORK_FACTORY, messenger));
3780 }
3781
3782 private void handleUnregisterNetworkFactory(Messenger messenger) {
3783 NetworkFactoryInfo nfi = mNetworkFactoryInfos.remove(messenger);
3784 if (nfi == null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003785 loge("Failed to find Messenger in unregisterNetworkFactory");
Robert Greenwalta67be032014-05-16 15:49:14 -07003786 return;
Robert Greenwalt9258c642014-03-26 16:47:06 -07003787 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003788 if (DBG) log("unregisterNetworkFactory for " + nfi.name);
Robert Greenwalte049c232014-04-11 15:53:27 -07003789 }
3790
Robert Greenwalt7b816022014-04-18 15:25:25 -07003791 /**
3792 * NetworkAgentInfo supporting a request by requestId.
3793 * These have already been vetted (their Capabilities satisfy the request)
3794 * and the are the highest scored network available.
3795 * the are keyed off the Requests requestId.
3796 */
Paul Jensen31a94f42015-02-13 14:18:39 -05003797 // TODO: Yikes, this is accessed on multiple threads: add synchronization.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003798 private final SparseArray<NetworkAgentInfo> mNetworkForRequestId =
3799 new SparseArray<NetworkAgentInfo>();
3800
Paul Jensen31a94f42015-02-13 14:18:39 -05003801 // NOTE: Accessed on multiple threads, must be synchronized on itself.
3802 @GuardedBy("mNetworkForNetId")
Robert Greenwalt9258c642014-03-26 16:47:06 -07003803 private final SparseArray<NetworkAgentInfo> mNetworkForNetId =
3804 new SparseArray<NetworkAgentInfo>();
Paul Jensen31a94f42015-02-13 14:18:39 -05003805 // NOTE: Accessed on multiple threads, synchronized with mNetworkForNetId.
3806 // An entry is first added to mNetIdInUse, prior to mNetworkForNetId, so
3807 // there may not be a strict 1:1 correlation between the two.
3808 @GuardedBy("mNetworkForNetId")
3809 private final SparseBooleanArray mNetIdInUse = new SparseBooleanArray();
Robert Greenwalt9258c642014-03-26 16:47:06 -07003810
Robert Greenwalt7b816022014-04-18 15:25:25 -07003811 // NetworkAgentInfo keyed off its connecting messenger
3812 // TODO - eval if we can reduce the number of lists/hashmaps/sparsearrays
Paul Jensen31a94f42015-02-13 14:18:39 -05003813 // NOTE: Only should be accessed on ConnectivityServiceThread, except dump().
Robert Greenwalt7b816022014-04-18 15:25:25 -07003814 private final HashMap<Messenger, NetworkAgentInfo> mNetworkAgentInfos =
3815 new HashMap<Messenger, NetworkAgentInfo>();
3816
Paul Jensen2c311d62014-11-17 12:34:51 -05003817 // Note: if mDefaultRequest is changed, NetworkMonitor needs to be updated.
Robert Greenwalt7b816022014-04-18 15:25:25 -07003818 private final NetworkRequest mDefaultRequest;
3819
Erik Klineda4bfa82015-04-30 12:58:40 +09003820 // Request used to optionally keep mobile data active even when higher
3821 // priority networks like Wi-Fi are active.
3822 private final NetworkRequest mDefaultMobileDataRequest;
3823
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003824 private NetworkAgentInfo getDefaultNetwork() {
3825 return mNetworkForRequestId.get(mDefaultRequest.requestId);
3826 }
3827
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003828 private boolean isDefaultNetwork(NetworkAgentInfo nai) {
Lorenzo Colitti403aa262014-11-28 11:21:30 +09003829 return nai == getDefaultNetwork();
Robert Greenwaltbf4eed72014-08-06 21:32:18 -07003830 }
3831
Paul Jensen31a94f42015-02-13 14:18:39 -05003832 public int registerNetworkAgent(Messenger messenger, NetworkInfo networkInfo,
Robert Greenwalt7b816022014-04-18 15:25:25 -07003833 LinkProperties linkProperties, NetworkCapabilities networkCapabilities,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07003834 int currentScore, NetworkMisc networkMisc) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003835 enforceConnectivityInternalPermission();
3836
Paul Jensen2c311d62014-11-17 12:34:51 -05003837 // TODO: Instead of passing mDefaultRequest, provide an API to determine whether a Network
3838 // satisfies mDefaultRequest.
Paul Jensen60061a62014-08-05 14:13:48 -04003839 NetworkAgentInfo nai = new NetworkAgentInfo(messenger, new AsyncChannel(),
Paul Jensen31a94f42015-02-13 14:18:39 -05003840 new Network(reserveNetId()), new NetworkInfo(networkInfo), new LinkProperties(
3841 linkProperties), new NetworkCapabilities(networkCapabilities), currentScore,
3842 mContext, mTrackerHandler, new NetworkMisc(networkMisc), mDefaultRequest);
Robert Greenwaltfb68f8f2014-08-13 13:43:32 -07003843 synchronized (this) {
3844 nai.networkMonitor.systemReady = mSystemReady;
3845 }
Robert Greenwalt22b4c6a2015-06-23 15:03:33 -07003846 addValidationLogs(nai.networkMonitor.getValidationLogs(), nai.network);
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003847 if (DBG) log("registerNetworkAgent " + nai);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003848 mHandler.sendMessage(mHandler.obtainMessage(EVENT_REGISTER_NETWORK_AGENT, nai));
Paul Jensen31a94f42015-02-13 14:18:39 -05003849 return nai.network.netId;
Robert Greenwalt7b816022014-04-18 15:25:25 -07003850 }
3851
3852 private void handleRegisterNetworkAgent(NetworkAgentInfo na) {
3853 if (VDBG) log("Got NetworkAgent Messenger");
3854 mNetworkAgentInfos.put(na.messenger, na);
Paul Jensen31a94f42015-02-13 14:18:39 -05003855 synchronized (mNetworkForNetId) {
3856 mNetworkForNetId.put(na.network.netId, na);
3857 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003858 na.asyncChannel.connect(mContext, mTrackerHandler, na.messenger);
3859 NetworkInfo networkInfo = na.networkInfo;
3860 na.networkInfo = null;
3861 updateNetworkInfo(na, networkInfo);
3862 }
3863
3864 private void updateLinkProperties(NetworkAgentInfo networkAgent, LinkProperties oldLp) {
3865 LinkProperties newLp = networkAgent.linkProperties;
3866 int netId = networkAgent.network.netId;
3867
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003868 // The NetworkAgentInfo does not know whether clatd is running on its network or not. Before
3869 // we do anything else, make sure its LinkProperties are accurate.
Lorenzo Colitti95439462014-10-09 13:44:48 +09003870 if (networkAgent.clatd != null) {
3871 networkAgent.clatd.fixupLinkProperties(oldLp);
3872 }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003873
Paul Jensen992f2522014-04-28 10:33:11 -04003874 updateInterfaces(newLp, oldLp, netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003875 updateMtu(newLp, oldLp);
3876 // TODO - figure out what to do for clat
3877// for (LinkProperties lp : newLp.getStackedLinks()) {
3878// updateMtu(lp, null);
3879// }
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003880 updateTcpBufferSizes(networkAgent);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003881
Lorenzo Colitti93155b32015-05-14 22:12:36 +09003882 // TODO: deprecate and remove mDefaultDns when we can do so safely. See http://b/18327075
3883 // In L, we used it only when the network had Internet access but provided no DNS servers.
3884 // For now, just disable it, and if disabling it doesn't break things, remove it.
3885 // final boolean useDefaultDns = networkAgent.networkCapabilities.hasCapability(
3886 // NET_CAPABILITY_INTERNET);
3887 final boolean useDefaultDns = false;
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003888 final boolean flushDns = updateRoutes(newLp, oldLp, netId);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09003889 updateDnses(newLp, oldLp, netId, flushDns, useDefaultDns);
3890
Paul Jensen3b759822014-05-13 11:44:01 -04003891 updateClat(newLp, oldLp, networkAgent);
Paul Jensene0bef712014-12-10 15:12:18 -05003892 if (isDefaultNetwork(networkAgent)) {
3893 handleApplyDefaultProxy(newLp.getHttpProxy());
3894 } else {
3895 updateProxy(newLp, oldLp, networkAgent);
3896 }
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003897 // TODO - move this check to cover the whole function
3898 if (!Objects.equals(newLp, oldLp)) {
Jeff Sharkey69736342014-12-08 14:50:12 -08003899 notifyIfacesChanged();
Robert Greenwalta848c1c2014-09-30 16:50:07 -07003900 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_IP_CHANGED);
3901 }
Paul Jensen3b759822014-05-13 11:44:01 -04003902 }
3903
Lorenzo Colitti95439462014-10-09 13:44:48 +09003904 private void updateClat(LinkProperties newLp, LinkProperties oldLp, NetworkAgentInfo nai) {
3905 final boolean wasRunningClat = nai.clatd != null && nai.clatd.isStarted();
3906 final boolean shouldRunClat = Nat464Xlat.requiresClat(nai);
Paul Jensen3b759822014-05-13 11:44:01 -04003907
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003908 if (!wasRunningClat && shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003909 nai.clatd = new Nat464Xlat(mContext, mNetd, mTrackerHandler, nai);
3910 nai.clatd.start();
Lorenzo Colitti1df5fa52014-09-20 13:47:47 +09003911 } else if (wasRunningClat && !shouldRunClat) {
Lorenzo Colitti95439462014-10-09 13:44:48 +09003912 nai.clatd.stop();
Paul Jensen3b759822014-05-13 11:44:01 -04003913 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003914 }
Paul Jensen992f2522014-04-28 10:33:11 -04003915
3916 private void updateInterfaces(LinkProperties newLp, LinkProperties oldLp, int netId) {
3917 CompareResult<String> interfaceDiff = new CompareResult<String>();
3918 if (oldLp != null) {
3919 interfaceDiff = oldLp.compareAllInterfaceNames(newLp);
3920 } else if (newLp != null) {
3921 interfaceDiff.added = newLp.getAllInterfaceNames();
3922 }
3923 for (String iface : interfaceDiff.added) {
3924 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003925 if (DBG) log("Adding iface " + iface + " to network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003926 mNetd.addInterfaceToNetwork(iface, netId);
3927 } catch (Exception e) {
3928 loge("Exception adding interface: " + e);
3929 }
3930 }
3931 for (String iface : interfaceDiff.removed) {
3932 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003933 if (DBG) log("Removing iface " + iface + " from network " + netId);
Paul Jensen992f2522014-04-28 10:33:11 -04003934 mNetd.removeInterfaceFromNetwork(iface, netId);
3935 } catch (Exception e) {
3936 loge("Exception removing interface: " + e);
3937 }
3938 }
3939 }
3940
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003941 /**
3942 * Have netd update routes from oldLp to newLp.
3943 * @return true if routes changed between oldLp and newLp
3944 */
3945 private boolean updateRoutes(LinkProperties newLp, LinkProperties oldLp, int netId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07003946 CompareResult<RouteInfo> routeDiff = new CompareResult<RouteInfo>();
3947 if (oldLp != null) {
3948 routeDiff = oldLp.compareAllRoutes(newLp);
3949 } else if (newLp != null) {
3950 routeDiff.added = newLp.getAllRoutes();
3951 }
3952
3953 // add routes before removing old in case it helps with continuous connectivity
3954
3955 // do this twice, adding non-nexthop routes first, then routes they are dependent on
3956 for (RouteInfo route : routeDiff.added) {
3957 if (route.hasGateway()) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003958 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003959 try {
3960 mNetd.addRoute(netId, route);
3961 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003962 if ((route.getDestination().getAddress() instanceof Inet4Address) || VDBG) {
3963 loge("Exception in addRoute for non-gateway: " + e);
3964 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003965 }
3966 }
3967 for (RouteInfo route : routeDiff.added) {
3968 if (route.hasGateway() == false) continue;
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003969 if (DBG) log("Adding Route [" + route + "] to network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003970 try {
3971 mNetd.addRoute(netId, route);
3972 } catch (Exception e) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003973 if ((route.getGateway() instanceof Inet4Address) || VDBG) {
3974 loge("Exception in addRoute for gateway: " + e);
3975 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07003976 }
3977 }
3978
3979 for (RouteInfo route : routeDiff.removed) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07003980 if (DBG) log("Removing Route [" + route + "] from network " + netId);
Robert Greenwalt7b816022014-04-18 15:25:25 -07003981 try {
3982 mNetd.removeRoute(netId, route);
3983 } catch (Exception e) {
3984 loge("Exception in removeRoute: " + e);
3985 }
3986 }
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04003987 return !routeDiff.added.isEmpty() || !routeDiff.removed.isEmpty();
Robert Greenwalt7b816022014-04-18 15:25:25 -07003988 }
Erik Kline41368502015-06-17 13:19:54 +09003989
3990 // TODO: investigate moving this into LinkProperties, if only to make more accurate
3991 // the isProvisioned() checks.
3992 private static Collection<InetAddress> getLikelyReachableDnsServers(LinkProperties lp) {
3993 final ArrayList<InetAddress> dnsServers = new ArrayList<InetAddress>();
3994 final List<RouteInfo> allRoutes = lp.getAllRoutes();
3995 for (InetAddress nameserver : lp.getDnsServers()) {
3996 // If the LinkProperties doesn't include a route to the nameserver, ignore it.
3997 final RouteInfo bestRoute = RouteInfo.selectBestRoute(allRoutes, nameserver);
3998 if (bestRoute == null) {
3999 continue;
4000 }
4001
4002 // TODO: better source address evaluation for destination addresses.
4003 if (nameserver instanceof Inet4Address) {
4004 if (!lp.hasIPv4Address()) {
4005 continue;
4006 }
4007 } else if (nameserver instanceof Inet6Address) {
4008 if (nameserver.isLinkLocalAddress()) {
4009 if (((Inet6Address)nameserver).getScopeId() == 0) {
4010 // For now, just make sure link-local DNS servers have
4011 // scopedIds set, since DNS lookups will fail otherwise.
4012 // TODO: verify the scopeId matches that of lp's interface.
4013 continue;
4014 }
4015 } else {
4016 if (bestRoute.isIPv6Default() && !lp.hasGlobalIPv6Address()) {
4017 // TODO: reconsider all corner cases (disconnected ULA networks, ...).
4018 continue;
4019 }
4020 }
4021 }
4022
4023 dnsServers.add(nameserver);
4024 }
4025 return Collections.unmodifiableList(dnsServers);
4026 }
4027
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004028 private void updateDnses(LinkProperties newLp, LinkProperties oldLp, int netId,
4029 boolean flush, boolean useDefaultDns) {
Erik Kline41368502015-06-17 13:19:54 +09004030 // TODO: consider comparing the getLikelyReachableDnsServers() lists, in case the
4031 // route to a DNS server has been removed (only really applicable in special cases
4032 // where there is no default route).
Robert Greenwalt7b816022014-04-18 15:25:25 -07004033 if (oldLp == null || (newLp.isIdenticalDnses(oldLp) == false)) {
Erik Kline41368502015-06-17 13:19:54 +09004034 Collection<InetAddress> dnses = getLikelyReachableDnsServers(newLp);
Lorenzo Colitti829dfa72014-11-28 20:07:46 +09004035 if (dnses.size() == 0 && mDefaultDns != null && useDefaultDns) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004036 dnses = new ArrayList();
4037 dnses.add(mDefaultDns);
4038 if (DBG) {
4039 loge("no dns provided for netId " + netId + ", so using defaults");
4040 }
4041 }
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004042 if (DBG) log("Setting Dns servers for network " + netId + " to " + dnses);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004043 try {
4044 mNetd.setDnsServersForNetwork(netId, NetworkUtils.makeStrings(dnses),
4045 newLp.getDomains());
4046 } catch (Exception e) {
4047 loge("Exception in setDnsServersForNetwork: " + e);
4048 }
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004049 NetworkAgentInfo defaultNai = mNetworkForRequestId.get(mDefaultRequest.requestId);
4050 if (defaultNai != null && defaultNai.network.netId == netId) {
4051 setDefaultDnsSystemProperties(dnses);
4052 }
Robert Greenwalt5c1c832a82014-07-28 16:32:19 -07004053 flushVmDnsCache();
Paul Jensen5fb2c6ff2014-08-06 15:51:33 -04004054 } else if (flush) {
4055 try {
4056 mNetd.flushNetworkDnsCache(netId);
4057 } catch (Exception e) {
4058 loge("Exception in flushNetworkDnsCache: " + e);
4059 }
4060 flushVmDnsCache();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004061 }
4062 }
4063
Robert Greenwaltd5648dc2014-05-15 15:27:13 -07004064 private void setDefaultDnsSystemProperties(Collection<InetAddress> dnses) {
4065 int last = 0;
4066 for (InetAddress dns : dnses) {
4067 ++last;
4068 String key = "net.dns" + last;
4069 String value = dns.getHostAddress();
4070 SystemProperties.set(key, value);
4071 }
4072 for (int i = last + 1; i <= mNumDnsEntries; ++i) {
4073 String key = "net.dns" + i;
4074 SystemProperties.set(key, "");
4075 }
4076 mNumDnsEntries = last;
4077 }
4078
Robert Greenwalt7b816022014-04-18 15:25:25 -07004079 private void updateCapabilities(NetworkAgentInfo networkAgent,
4080 NetworkCapabilities networkCapabilities) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004081 if (!Objects.equals(networkAgent.networkCapabilities, networkCapabilities)) {
4082 synchronized (networkAgent) {
4083 networkAgent.networkCapabilities = networkCapabilities;
4084 }
Lorenzo Colitti76f67792015-05-14 17:28:27 +09004085 if (networkAgent.lastValidated) {
4086 networkAgent.networkCapabilities.addCapability(NET_CAPABILITY_VALIDATED);
4087 // There's no need to remove the capability if we think the network is unvalidated,
4088 // because NetworkAgents don't set the validated capability.
4089 }
Jeff Davidson9634abe2014-11-04 16:48:27 -08004090 rematchAllNetworksAndRequests(networkAgent, networkAgent.getCurrentScore());
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004091 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_CAP_CHANGED);
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004092 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004093 }
4094
Paul Jensenc8b9a742014-09-30 15:37:41 -04004095 private void sendUpdatedScoreToFactories(NetworkAgentInfo nai) {
4096 for (int i = 0; i < nai.networkRequests.size(); i++) {
4097 NetworkRequest nr = nai.networkRequests.valueAt(i);
4098 // Don't send listening requests to factories. b/17393458
4099 if (!isRequest(nr)) continue;
4100 sendUpdatedScoreToFactories(nr, nai.getCurrentScore());
4101 }
4102 }
4103
Robert Greenwalt7b816022014-04-18 15:25:25 -07004104 private void sendUpdatedScoreToFactories(NetworkRequest networkRequest, int score) {
4105 if (VDBG) log("sending new Min Network Score(" + score + "): " + networkRequest.toString());
Robert Greenwalta67be032014-05-16 15:49:14 -07004106 for (NetworkFactoryInfo nfi : mNetworkFactoryInfos.values()) {
Robert Greenwalt55691b82014-05-27 13:20:24 -07004107 nfi.asyncChannel.sendMessage(android.net.NetworkFactory.CMD_REQUEST_NETWORK, score, 0,
4108 networkRequest);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004109 }
4110 }
4111
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004112 private void sendPendingIntentForRequest(NetworkRequestInfo nri, NetworkAgentInfo networkAgent,
4113 int notificationType) {
Jeremy Joslin79294842014-12-03 17:15:28 -08004114 if (notificationType == ConnectivityManager.CALLBACK_AVAILABLE && !nri.mPendingIntentSent) {
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004115 Intent intent = new Intent();
Jeremy Joslina68e7d72014-11-26 14:24:15 -08004116 intent.putExtra(ConnectivityManager.EXTRA_NETWORK, networkAgent.network);
4117 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_REQUEST, nri.request);
Jeremy Joslin79294842014-12-03 17:15:28 -08004118 nri.mPendingIntentSent = true;
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004119 sendIntent(nri.mPendingIntent, intent);
4120 }
4121 // else not handled
4122 }
4123
4124 private void sendIntent(PendingIntent pendingIntent, Intent intent) {
4125 mPendingIntentWakeLock.acquire();
4126 try {
4127 if (DBG) log("Sending " + pendingIntent);
4128 pendingIntent.send(mContext, 0, intent, this /* onFinished */, null /* Handler */);
4129 } catch (PendingIntent.CanceledException e) {
4130 if (DBG) log(pendingIntent + " was not sent, it had been canceled.");
4131 mPendingIntentWakeLock.release();
4132 releasePendingNetworkRequest(pendingIntent);
4133 }
4134 // ...otherwise, mPendingIntentWakeLock.release() gets called by onSendFinished()
4135 }
4136
4137 @Override
4138 public void onSendFinished(PendingIntent pendingIntent, Intent intent, int resultCode,
4139 String resultData, Bundle resultExtras) {
4140 if (DBG) log("Finished sending " + pendingIntent);
4141 mPendingIntentWakeLock.release();
Jeremy Joslin79294842014-12-03 17:15:28 -08004142 // Release with a delay so the receiving client has an opportunity to put in its
4143 // own request.
4144 releasePendingNetworkRequestWithDelay(pendingIntent);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004145 }
4146
Robert Greenwalt9258c642014-03-26 16:47:06 -07004147 private void callCallbackForRequest(NetworkRequestInfo nri,
Robert Greenwalt7b816022014-04-18 15:25:25 -07004148 NetworkAgentInfo networkAgent, int notificationType) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004149 if (nri.messenger == null) return; // Default request has no msgr
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004150 Bundle bundle = new Bundle();
4151 bundle.putParcelable(NetworkRequest.class.getSimpleName(),
4152 new NetworkRequest(nri.request));
4153 Message msg = Message.obtain();
4154 if (notificationType != ConnectivityManager.CALLBACK_UNAVAIL &&
4155 notificationType != ConnectivityManager.CALLBACK_RELEASED) {
4156 bundle.putParcelable(Network.class.getSimpleName(), networkAgent.network);
4157 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004158 switch (notificationType) {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004159 case ConnectivityManager.CALLBACK_LOSING: {
4160 msg.arg1 = 30 * 1000; // TODO - read this from NetworkMonitor
4161 break;
4162 }
4163 case ConnectivityManager.CALLBACK_CAP_CHANGED: {
4164 bundle.putParcelable(NetworkCapabilities.class.getSimpleName(),
4165 new NetworkCapabilities(networkAgent.networkCapabilities));
4166 break;
4167 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004168 case ConnectivityManager.CALLBACK_IP_CHANGED: {
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004169 bundle.putParcelable(LinkProperties.class.getSimpleName(),
4170 new LinkProperties(networkAgent.linkProperties));
Robert Greenwalt9258c642014-03-26 16:47:06 -07004171 break;
4172 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004173 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004174 msg.what = notificationType;
Robert Greenwalta848c1c2014-09-30 16:50:07 -07004175 msg.setData(bundle);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004176 try {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004177 if (VDBG) {
4178 log("sending notification " + notifyTypeToName(notificationType) +
4179 " for " + nri.request);
4180 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004181 nri.messenger.send(msg);
4182 } catch (RemoteException e) {
4183 // may occur naturally in the race of binder death.
4184 loge("RemoteException caught trying to send a callback msg for " + nri.request);
4185 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004186 }
4187
Paul Jensenc8b9a742014-09-30 15:37:41 -04004188 private void teardownUnneededNetwork(NetworkAgentInfo nai) {
4189 for (int i = 0; i < nai.networkRequests.size(); i++) {
4190 NetworkRequest nr = nai.networkRequests.valueAt(i);
4191 // Ignore listening requests.
4192 if (!isRequest(nr)) continue;
4193 loge("Dead network still had at least " + nr);
4194 break;
4195 }
4196 nai.asyncChannel.disconnect();
4197 }
4198
Robert Greenwalt7b816022014-04-18 15:25:25 -07004199 private void handleLingerComplete(NetworkAgentInfo oldNetwork) {
4200 if (oldNetwork == null) {
4201 loge("Unknown NetworkAgentInfo in handleLingerComplete");
4202 return;
4203 }
Paul Jensenc8b9a742014-09-30 15:37:41 -04004204 if (DBG) log("handleLingerComplete for " + oldNetwork.name());
4205 teardownUnneededNetwork(oldNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004206 }
4207
Paul Jensen27b02b72014-07-14 12:03:33 -04004208 private void makeDefault(NetworkAgentInfo newNetwork) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004209 if (DBG) log("Switching to new default network: " + newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004210 setupDataActivityTracking(newNetwork);
4211 try {
4212 mNetd.setDefaultNetId(newNetwork.network.netId);
4213 } catch (Exception e) {
4214 loge("Exception setting default network :" + e);
4215 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004216 notifyLockdownVpn(newNetwork);
Paul Jensen27b02b72014-07-14 12:03:33 -04004217 handleApplyDefaultProxy(newNetwork.linkProperties.getHttpProxy());
Robert Greenwalt3f05bf42014-08-06 12:00:25 -07004218 updateTcpBufferSizes(newNetwork);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004219 setDefaultDnsSystemProperties(newNetwork.linkProperties.getDnsServers());
Paul Jensen27b02b72014-07-14 12:03:33 -04004220 }
4221
Paul Jensen2161a8e2014-09-11 11:00:39 -04004222 // Handles a network appearing or improving its score.
4223 //
4224 // - Evaluates all current NetworkRequests that can be
4225 // satisfied by newNetwork, and reassigns to newNetwork
4226 // any such requests for which newNetwork is the best.
4227 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004228 // - Lingers any validated Networks that as a result are no longer
Paul Jensen2161a8e2014-09-11 11:00:39 -04004229 // needed. A network is needed if it is the best network for
4230 // one or more NetworkRequests, or if it is a VPN.
4231 //
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004232 // - Tears down newNetwork if it just became validated
Paul Jensenb10e37f2014-11-25 12:33:08 -05004233 // (i.e. nascent==JUST_VALIDATED) but turns out to be unneeded.
4234 //
4235 // - If reapUnvalidatedNetworks==REAP, tears down unvalidated
4236 // networks that have no chance (i.e. even if validated)
4237 // of becoming the highest scoring network.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004238 //
4239 // NOTE: This function only adds NetworkRequests that "newNetwork" could satisfy,
4240 // it does not remove NetworkRequests that other Networks could better satisfy.
4241 // If you need to handle decreases in score, use {@link rematchAllNetworksAndRequests}.
4242 // This function should be used when possible instead of {@code rematchAllNetworksAndRequests}
4243 // as it performs better by a factor of the number of Networks.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004244 //
Paul Jensenb10e37f2014-11-25 12:33:08 -05004245 // @param newNetwork is the network to be matched against NetworkRequests.
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004246 // @param nascent indicates if newNetwork just became validated, in which case it should be
Paul Jensenb10e37f2014-11-25 12:33:08 -05004247 // torn down if unneeded.
4248 // @param reapUnvalidatedNetworks indicates if an additional pass over all networks should be
4249 // performed to tear down unvalidated networks that have no chance (i.e. even if
4250 // validated) of becoming the highest scoring network.
4251 private void rematchNetworkAndRequests(NetworkAgentInfo newNetwork, NascentState nascent,
4252 ReapUnvalidatedNetworks reapUnvalidatedNetworks) {
Paul Jensen57a767f2014-11-19 13:01:46 -05004253 if (!newNetwork.created) return;
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004254 if (nascent == NascentState.JUST_VALIDATED && !newNetwork.everValidated) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004255 loge("ERROR: nascent network not validated.");
4256 }
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004257 boolean keep = newNetwork.isVPN();
Robert Greenwalt7b816022014-04-18 15:25:25 -07004258 boolean isNewDefault = false;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004259 NetworkAgentInfo oldDefaultNetwork = null;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004260 if (DBG) log("rematching " + newNetwork.name());
4261 // Find and migrate to this Network any NetworkRequests for
4262 // which this network is now the best.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004263 ArrayList<NetworkAgentInfo> affectedNetworks = new ArrayList<NetworkAgentInfo>();
Paul Jensen3d911462015-06-12 06:40:24 -04004264 ArrayList<NetworkRequestInfo> addedRequests = new ArrayList<NetworkRequestInfo>();
Paul Jensen2161a8e2014-09-11 11:00:39 -04004265 if (VDBG) log(" network has: " + newNetwork.networkCapabilities);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004266 for (NetworkRequestInfo nri : mNetworkRequests.values()) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004267 NetworkAgentInfo currentNetwork = mNetworkForRequestId.get(nri.request.requestId);
4268 if (newNetwork == currentNetwork) {
Robert Greenwalte73cc462014-09-07 16:50:01 -07004269 if (DBG) {
4270 log("Network " + newNetwork.name() + " was already satisfying" +
4271 " request " + nri.request.requestId + ". No change.");
4272 }
Lorenzo Colittibce01062014-05-29 14:05:41 +09004273 keep = true;
4274 continue;
4275 }
4276
4277 // check if it satisfies the NetworkCapabilities
Robert Greenwalt9258c642014-03-26 16:47:06 -07004278 if (VDBG) log(" checking if request is satisfied: " + nri.request);
Paul Jensen0cc17322014-11-25 15:26:53 -05004279 if (newNetwork.satisfies(nri.request)) {
Paul Jensen0311b2b2014-08-19 10:31:40 -04004280 if (!nri.isRequest) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004281 // This is not a request, it's a callback listener.
4282 // Add it to newNetwork regardless of score.
Paul Jensen3d911462015-06-12 06:40:24 -04004283 if (newNetwork.addRequest(nri.request)) addedRequests.add(nri);
Paul Jensen0311b2b2014-08-19 10:31:40 -04004284 continue;
4285 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004286
Robert Greenwalt7b816022014-04-18 15:25:25 -07004287 // next check if it's better than any current network we're using for
4288 // this request
Robert Greenwalt7b816022014-04-18 15:25:25 -07004289 if (VDBG) {
4290 log("currentScore = " +
Paul Jensen2161a8e2014-09-11 11:00:39 -04004291 (currentNetwork != null ? currentNetwork.getCurrentScore() : 0) +
4292 ", newScore = " + newNetwork.getCurrentScore());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004293 }
4294 if (currentNetwork == null ||
Paul Jensen2161a8e2014-09-11 11:00:39 -04004295 currentNetwork.getCurrentScore() < newNetwork.getCurrentScore()) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004296 if (currentNetwork != null) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004297 if (DBG) log(" accepting network in place of " + currentNetwork.name());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004298 currentNetwork.networkRequests.remove(nri.request.requestId);
4299 currentNetwork.networkLingered.add(nri.request);
4300 affectedNetworks.add(currentNetwork);
4301 } else {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004302 if (DBG) log(" accepting network in place of null");
Robert Greenwalt7b816022014-04-18 15:25:25 -07004303 }
Paul Jensen573a0352015-01-08 10:49:34 -05004304 unlinger(newNetwork);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004305 mNetworkForRequestId.put(nri.request.requestId, newNetwork);
Paul Jensen3d911462015-06-12 06:40:24 -04004306 if (!newNetwork.addRequest(nri.request)) {
4307 Slog.wtf(TAG, "BUG: " + newNetwork.name() + " already has " + nri.request);
4308 }
4309 addedRequests.add(nri);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004310 keep = true;
Paul Jensen2161a8e2014-09-11 11:00:39 -04004311 // Tell NetworkFactories about the new score, so they can stop
4312 // trying to connect if they know they cannot match it.
Robert Greenwalt7b816022014-04-18 15:25:25 -07004313 // TODO - this could get expensive if we have alot of requests for this
4314 // network. Think about if there is a way to reduce this. Push
4315 // netid->request mapping to each factory?
Paul Jensen2161a8e2014-09-11 11:00:39 -04004316 sendUpdatedScoreToFactories(nri.request, newNetwork.getCurrentScore());
Robert Greenwalt9258c642014-03-26 16:47:06 -07004317 if (mDefaultRequest.requestId == nri.request.requestId) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004318 isNewDefault = true;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004319 oldDefaultNetwork = currentNetwork;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004320 }
4321 }
4322 }
4323 }
Paul Jensen2161a8e2014-09-11 11:00:39 -04004324 // Linger any networks that are no longer needed.
Robert Greenwalt9258c642014-03-26 16:47:06 -07004325 for (NetworkAgentInfo nai : affectedNetworks) {
Paul Jensen99364842014-12-09 11:43:45 -05004326 if (nai.everValidated && unneeded(nai)) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004327 nai.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_LINGER);
4328 notifyNetworkCallbacks(nai, ConnectivityManager.CALLBACK_LOSING);
4329 } else {
Paul Jensen0cc17322014-11-25 15:26:53 -05004330 unlinger(nai);
Robert Greenwalt9258c642014-03-26 16:47:06 -07004331 }
4332 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004333 if (keep) {
4334 if (isNewDefault) {
Paul Jensen2161a8e2014-09-11 11:00:39 -04004335 // Notify system services that this network is up.
Paul Jensen27b02b72014-07-14 12:03:33 -04004336 makeDefault(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004337 synchronized (ConnectivityService.this) {
4338 // have a new default network, release the transition wakelock in
4339 // a second if it's held. The second pause is to allow apps
4340 // to reconnect over the new network
4341 if (mNetTransitionWakeLock.isHeld()) {
4342 mHandler.sendMessageDelayed(mHandler.obtainMessage(
4343 EVENT_CLEAR_NET_TRANSITION_WAKELOCK,
4344 mNetTransitionWakeLockSerialNumber, 0),
4345 1000);
4346 }
4347 }
Robert Greenwalt152ed372014-12-17 17:19:53 -08004348 }
4349
4350 // do this after the default net is switched, but
4351 // before LegacyTypeTracker sends legacy broadcasts
Paul Jensen3d911462015-06-12 06:40:24 -04004352 for (NetworkRequestInfo nri : addedRequests) notifyNetworkCallback(newNetwork, nri);
Robert Greenwalt152ed372014-12-17 17:19:53 -08004353
4354 if (isNewDefault) {
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004355 // Maintain the illusion: since the legacy API only
4356 // understands one network at a time, we must pretend
4357 // that the current default network disconnected before
4358 // the new one connected.
4359 if (oldDefaultNetwork != null) {
4360 mLegacyTypeTracker.remove(oldDefaultNetwork.networkInfo.getType(),
Lorenzo Colitticc917ce2015-05-01 00:30:10 +09004361 oldDefaultNetwork, true);
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004362 }
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004363 mDefaultInetConditionPublished = newNetwork.everValidated ? 100 : 0;
Paul Jensenf4ffaa42014-12-15 11:56:18 -05004364 mLegacyTypeTracker.add(newNetwork.networkInfo.getType(), newNetwork);
4365 notifyLockdownVpn(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004366 }
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004367
4368 // Notify battery stats service about this network, both the normal
4369 // interface and any stacked links.
Paul Jensen2161a8e2014-09-11 11:00:39 -04004370 // TODO: Avoid redoing this; this must only be done once when a network comes online.
Dianne Hackborn29325132014-05-21 15:01:03 -07004371 try {
Jeff Sharkeyeb2c2c72014-08-11 15:22:51 -07004372 final IBatteryStats bs = BatteryStatsService.getService();
4373 final int type = newNetwork.networkInfo.getType();
4374
4375 final String baseIface = newNetwork.linkProperties.getInterfaceName();
4376 bs.noteNetworkInterfaceType(baseIface, type);
4377 for (LinkProperties stacked : newNetwork.linkProperties.getStackedLinks()) {
4378 final String stackedIface = stacked.getInterfaceName();
4379 bs.noteNetworkInterfaceType(stackedIface, type);
4380 NetworkStatsFactory.noteStackedIface(stackedIface, baseIface);
4381 }
4382 } catch (RemoteException ignored) {
4383 }
4384
Robert Greenwalt152ed372014-12-17 17:19:53 -08004385 // This has to happen after the notifyNetworkCallbacks as that tickles each
4386 // ConnectivityManager instance so that legacy requests correctly bind dns
4387 // requests to this network. The legacy users are listening for this bcast
4388 // and will generally do a dns request so they can ensureRouteToHost and if
4389 // they do that before the callbacks happen they'll use the default network.
4390 //
4391 // TODO: Is there still a race here? We send the broadcast
4392 // after sending the callback, but if the app can receive the
4393 // broadcast before the callback, it might still break.
4394 //
4395 // This *does* introduce a race where if the user uses the new api
4396 // (notification callbacks) and then uses the old api (getNetworkInfo(type))
4397 // they may get old info. Reverse this after the old startUsing api is removed.
4398 // This is on top of the multiple intent sequencing referenced in the todo above.
4399 for (int i = 0; i < newNetwork.networkRequests.size(); i++) {
4400 NetworkRequest nr = newNetwork.networkRequests.valueAt(i);
4401 if (nr.legacyType != TYPE_NONE && isRequest(nr)) {
4402 // legacy type tracker filters out repeat adds
4403 mLegacyTypeTracker.add(nr.legacyType, newNetwork);
4404 }
4405 }
Sreeram Ramachandran60c0c0d2014-10-30 14:55:29 -07004406
4407 // A VPN generally won't get added to the legacy tracker in the "for (nri)" loop above,
4408 // because usually there are no NetworkRequests it satisfies (e.g., mDefaultRequest
4409 // wants the NOT_VPN capability, so it will never be satisfied by a VPN). So, add the
4410 // newNetwork to the tracker explicitly (it's a no-op if it has already been added).
4411 if (newNetwork.isVPN()) {
4412 mLegacyTypeTracker.add(TYPE_VPN, newNetwork);
4413 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004414 } else if (nascent == NascentState.JUST_VALIDATED) {
Paul Jensen4b9b2be2014-09-26 10:10:22 -04004415 // Only tear down newly validated networks here. Leave unvalidated to either become
Paul Jensenb10e37f2014-11-25 12:33:08 -05004416 // validated (and get evaluated against peers, one losing here), or get reaped (see
4417 // reapUnvalidatedNetworks) if they have no chance of becoming the highest scoring
4418 // network. Networks that have been up for a while and are validated should be torn
4419 // down via the lingering process so communication on that network is given time to
4420 // wrap up.
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004421 if (DBG) log("Validated network turns out to be unwanted. Tear it down.");
Paul Jensenc8b9a742014-09-30 15:37:41 -04004422 teardownUnneededNetwork(newNetwork);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004423 }
Paul Jensenb10e37f2014-11-25 12:33:08 -05004424 if (reapUnvalidatedNetworks == ReapUnvalidatedNetworks.REAP) {
4425 for (NetworkAgentInfo nai : mNetworkAgentInfos.values()) {
Paul Jensen99364842014-12-09 11:43:45 -05004426 if (!nai.everValidated && unneeded(nai)) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004427 if (DBG) log("Reaping " + nai.name());
4428 teardownUnneededNetwork(nai);
4429 }
4430 }
4431 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004432 }
4433
Paul Jensen2161a8e2014-09-11 11:00:39 -04004434 // Attempt to rematch all Networks with NetworkRequests. This may result in Networks
4435 // being disconnected.
4436 // If only one Network's score or capabilities have been modified since the last time
4437 // this function was called, pass this Network in via the "changed" arugment, otherwise
4438 // pass null.
4439 // If only one Network has been changed but its NetworkCapabilities have not changed,
4440 // pass in the Network's score (from getCurrentScore()) prior to the change via
4441 // "oldScore", otherwise pass changed.getCurrentScore() or 0 if "changed" is null.
4442 private void rematchAllNetworksAndRequests(NetworkAgentInfo changed, int oldScore) {
4443 // TODO: This may get slow. The "changed" parameter is provided for future optimization
4444 // to avoid the slowness. It is not simply enough to process just "changed", for
4445 // example in the case where "changed"'s score decreases and another network should begin
4446 // satifying a NetworkRequest that "changed" currently satisfies.
4447
4448 // Optimization: Only reprocess "changed" if its score improved. This is safe because it
4449 // can only add more NetworkRequests satisfied by "changed", and this is exactly what
4450 // rematchNetworkAndRequests() handles.
4451 if (changed != null && oldScore < changed.getCurrentScore()) {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004452 rematchNetworkAndRequests(changed, NascentState.NOT_JUST_VALIDATED,
4453 ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004454 } else {
Paul Jensenb10e37f2014-11-25 12:33:08 -05004455 for (Iterator i = mNetworkAgentInfos.values().iterator(); i.hasNext(); ) {
4456 rematchNetworkAndRequests((NetworkAgentInfo)i.next(),
4457 NascentState.NOT_JUST_VALIDATED,
4458 // Only reap the last time through the loop. Reaping before all rematching
4459 // is complete could incorrectly teardown a network that hasn't yet been
4460 // rematched.
4461 i.hasNext() ? ReapUnvalidatedNetworks.DONT_REAP
4462 : ReapUnvalidatedNetworks.REAP);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004463 }
4464 }
4465 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004466
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004467 private void updateInetCondition(NetworkAgentInfo nai) {
Paul Jensenad50a1f2014-09-05 12:06:44 -04004468 // Don't bother updating until we've graduated to validated at least once.
Lorenzo Colittid3b8a3e2014-12-17 11:14:42 +09004469 if (!nai.everValidated) return;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004470 // For now only update icons for default connection.
4471 // TODO: Update WiFi and cellular icons separately. b/17237507
4472 if (!isDefaultNetwork(nai)) return;
4473
Lorenzo Colitti7b42f392014-12-17 11:26:49 +09004474 int newInetCondition = nai.lastValidated ? 100 : 0;
Paul Jensenad50a1f2014-09-05 12:06:44 -04004475 // Don't repeat publish.
4476 if (newInetCondition == mDefaultInetConditionPublished) return;
4477
4478 mDefaultInetConditionPublished = newInetCondition;
4479 sendInetConditionBroadcast(nai.networkInfo);
4480 }
4481
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004482 private void notifyLockdownVpn(NetworkAgentInfo nai) {
4483 if (mLockdownTracker != null) {
4484 if (nai != null && nai.isVPN()) {
4485 mLockdownTracker.onVpnStateChanged(nai.networkInfo);
4486 } else {
4487 mLockdownTracker.onNetworkInfoChanged();
4488 }
4489 }
4490 }
4491
Robert Greenwalt7b816022014-04-18 15:25:25 -07004492 private void updateNetworkInfo(NetworkAgentInfo networkAgent, NetworkInfo newInfo) {
4493 NetworkInfo.State state = newInfo.getState();
Robert Greenwalt73b6cbae2014-06-23 11:40:00 -07004494 NetworkInfo oldInfo = null;
4495 synchronized (networkAgent) {
4496 oldInfo = networkAgent.networkInfo;
4497 networkAgent.networkInfo = newInfo;
4498 }
Lorenzo Colitti0cb79032014-10-15 16:06:07 +09004499 notifyLockdownVpn(networkAgent);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004500
4501 if (oldInfo != null && oldInfo.getState() == state) {
4502 if (VDBG) log("ignoring duplicate network state non-change");
4503 return;
4504 }
4505 if (DBG) {
4506 log(networkAgent.name() + " EVENT_NETWORK_INFO_CHANGED, going from " +
4507 (oldInfo == null ? "null" : oldInfo.getState()) +
4508 " to " + state);
4509 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004510
Paul Jenseneec75412014-08-04 12:21:19 -04004511 if (state == NetworkInfo.State.CONNECTED && !networkAgent.created) {
Robert Greenwalt7b816022014-04-18 15:25:25 -07004512 try {
Paul Jenseneec75412014-08-04 12:21:19 -04004513 // This should never fail. Specifying an already in use NetID will cause failure.
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004514 if (networkAgent.isVPN()) {
4515 mNetd.createVirtualNetwork(networkAgent.network.netId,
Sreeram Ramachandran8cd33ed2014-07-23 15:23:15 -07004516 !networkAgent.linkProperties.getDnsServers().isEmpty(),
4517 (networkAgent.networkMisc == null ||
4518 !networkAgent.networkMisc.allowBypass));
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004519 } else {
4520 mNetd.createPhysicalNetwork(networkAgent.network.netId);
4521 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004522 } catch (Exception e) {
Lorenzo Colittibce01062014-05-29 14:05:41 +09004523 loge("Error creating network " + networkAgent.network.netId + ": "
4524 + e.getMessage());
4525 return;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004526 }
Paul Jenseneec75412014-08-04 12:21:19 -04004527 networkAgent.created = true;
Robert Greenwalt7b816022014-04-18 15:25:25 -07004528 updateLinkProperties(networkAgent, null);
Jeff Sharkey69736342014-12-08 14:50:12 -08004529 notifyIfacesChanged();
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004530
Paul Jensenca8f16a2014-05-09 12:47:55 -04004531 networkAgent.networkMonitor.sendMessage(NetworkMonitor.CMD_NETWORK_CONNECTED);
Lorenzo Colittie03c3c72015-04-03 16:38:52 +09004532 scheduleUnvalidatedPrompt(networkAgent);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004533
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004534 if (networkAgent.isVPN()) {
4535 // Temporarily disable the default proxy (not global).
4536 synchronized (mProxyLock) {
4537 if (!mDefaultProxyDisabled) {
4538 mDefaultProxyDisabled = true;
4539 if (mGlobalProxy == null && mDefaultProxy != null) {
4540 sendProxyBroadcast(null);
4541 }
4542 }
4543 }
4544 // TODO: support proxy per network.
4545 }
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004546
Paul Jensen2161a8e2014-09-11 11:00:39 -04004547 // Consider network even though it is not yet validated.
Paul Jensenb10e37f2014-11-25 12:33:08 -05004548 rematchNetworkAndRequests(networkAgent, NascentState.NOT_JUST_VALIDATED,
4549 ReapUnvalidatedNetworks.REAP);
Lorenzo Colittibdc45492015-04-09 14:35:26 +09004550
4551 // This has to happen after matching the requests, because callbacks are just requests.
4552 notifyNetworkCallbacks(networkAgent, ConnectivityManager.CALLBACK_PRECHECK);
Robert Greenwalt7b816022014-04-18 15:25:25 -07004553 } else if (state == NetworkInfo.State.DISCONNECTED ||
4554 state == NetworkInfo.State.SUSPENDED) {
4555 networkAgent.asyncChannel.disconnect();
Paul Jensen6bc2c2c2014-05-07 15:27:40 -04004556 if (networkAgent.isVPN()) {
4557 synchronized (mProxyLock) {
4558 if (mDefaultProxyDisabled) {
4559 mDefaultProxyDisabled = false;
4560 if (mGlobalProxy == null && mDefaultProxy != null) {
4561 sendProxyBroadcast(mDefaultProxy);
4562 }
4563 }
4564 }
4565 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004566 }
4567 }
4568
Robert Greenwaltac96c522014-06-03 16:43:57 -07004569 private void updateNetworkScore(NetworkAgentInfo nai, int score) {
4570 if (DBG) log("updateNetworkScore for " + nai.name() + " to " + score);
Robert Greenwalt35f7a942014-09-09 14:46:37 -07004571 if (score < 0) {
4572 loge("updateNetworkScore for " + nai.name() + " got a negative score (" + score +
4573 "). Bumping score to min of 0");
4574 score = 0;
4575 }
Robert Greenwaltac96c522014-06-03 16:43:57 -07004576
Paul Jensen2161a8e2014-09-11 11:00:39 -04004577 final int oldScore = nai.getCurrentScore();
4578 nai.setCurrentScore(score);
Robert Greenwaltac96c522014-06-03 16:43:57 -07004579
Paul Jensen57a767f2014-11-19 13:01:46 -05004580 rematchAllNetworksAndRequests(nai, oldScore);
Paul Jensen2161a8e2014-09-11 11:00:39 -04004581
Paul Jensenc8b9a742014-09-30 15:37:41 -04004582 sendUpdatedScoreToFactories(nai);
Robert Greenwalt55691b82014-05-27 13:20:24 -07004583 }
4584
Robert Greenwalt9258c642014-03-26 16:47:06 -07004585 // notify only this one new request of the current state
4586 protected void notifyNetworkCallback(NetworkAgentInfo nai, NetworkRequestInfo nri) {
4587 int notifyType = ConnectivityManager.CALLBACK_AVAILABLE;
4588 // TODO - read state from monitor to decide what to send.
4589// if (nai.networkMonitor.isLingering()) {
4590// notifyType = NetworkCallbacks.LOSING;
4591// } else if (nai.networkMonitor.isEvaluating()) {
4592// notifyType = NetworkCallbacks.callCallbackForRequest(request, nai, notifyType);
4593// }
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004594 if (nri.mPendingIntent == null) {
4595 callCallbackForRequest(nri, nai, notifyType);
4596 } else {
4597 sendPendingIntentForRequest(nri, nai, notifyType);
4598 }
Robert Greenwalt9258c642014-03-26 16:47:06 -07004599 }
4600
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004601 private void sendLegacyNetworkBroadcast(NetworkAgentInfo nai, boolean connected, int type) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004602 // The NetworkInfo we actually send out has no bearing on the real
4603 // state of affairs. For example, if the default connection is mobile,
4604 // and a request for HIPRI has just gone away, we need to pretend that
4605 // HIPRI has just disconnected. So we need to set the type to HIPRI and
4606 // the state to DISCONNECTED, even though the network is of type MOBILE
4607 // and is still connected.
4608 NetworkInfo info = new NetworkInfo(nai.networkInfo);
4609 info.setType(type);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004610 if (connected) {
Lorenzo Colittia793a672014-07-31 23:20:17 +09004611 info.setDetailedState(DetailedState.CONNECTED, null, info.getExtraInfo());
Erik Kline8f29dcf2014-12-08 16:25:20 +09004612 sendConnectedBroadcast(info);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004613 } else {
Feixiong Zhang376133f2015-06-01 18:07:58 -07004614 info.setDetailedState(DetailedState.DISCONNECTED, info.getReason(), info.getExtraInfo());
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004615 Intent intent = new Intent(ConnectivityManager.CONNECTIVITY_ACTION);
4616 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_INFO, info);
4617 intent.putExtra(ConnectivityManager.EXTRA_NETWORK_TYPE, info.getType());
4618 if (info.isFailover()) {
4619 intent.putExtra(ConnectivityManager.EXTRA_IS_FAILOVER, true);
4620 nai.networkInfo.setFailover(false);
4621 }
4622 if (info.getReason() != null) {
4623 intent.putExtra(ConnectivityManager.EXTRA_REASON, info.getReason());
4624 }
4625 if (info.getExtraInfo() != null) {
4626 intent.putExtra(ConnectivityManager.EXTRA_EXTRA_INFO, info.getExtraInfo());
4627 }
4628 NetworkAgentInfo newDefaultAgent = null;
4629 if (nai.networkRequests.get(mDefaultRequest.requestId) != null) {
4630 newDefaultAgent = mNetworkForRequestId.get(mDefaultRequest.requestId);
4631 if (newDefaultAgent != null) {
4632 intent.putExtra(ConnectivityManager.EXTRA_OTHER_NETWORK_INFO,
4633 newDefaultAgent.networkInfo);
4634 } else {
4635 intent.putExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, true);
4636 }
4637 }
4638 intent.putExtra(ConnectivityManager.EXTRA_INET_CONDITION,
4639 mDefaultInetConditionPublished);
Erik Kline8f29dcf2014-12-08 16:25:20 +09004640 sendStickyBroadcast(intent);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004641 if (newDefaultAgent != null) {
Erik Kline8f29dcf2014-12-08 16:25:20 +09004642 sendConnectedBroadcast(newDefaultAgent.networkInfo);
Robert Greenwalt32aa65a2014-06-02 15:32:02 -07004643 }
4644 }
4645 }
4646
Robert Greenwalt7b816022014-04-18 15:25:25 -07004647 protected void notifyNetworkCallbacks(NetworkAgentInfo networkAgent, int notifyType) {
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004648 if (DBG) log("notifyType " + notifyTypeToName(notifyType) + " for " + networkAgent.name());
Robert Greenwalt7b816022014-04-18 15:25:25 -07004649 for (int i = 0; i < networkAgent.networkRequests.size(); i++) {
Robert Greenwalt9258c642014-03-26 16:47:06 -07004650 NetworkRequest nr = networkAgent.networkRequests.valueAt(i);
4651 NetworkRequestInfo nri = mNetworkRequests.get(nr);
4652 if (VDBG) log(" sending notification for " + nr);
Jeremy Joslin46e3ac82014-11-05 10:32:09 -08004653 if (nri.mPendingIntent == null) {
4654 callCallbackForRequest(nri, networkAgent, notifyType);
4655 } else {
4656 sendPendingIntentForRequest(nri, networkAgent, notifyType);
4657 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004658 }
Robert Greenwalt7b816022014-04-18 15:25:25 -07004659 }
Robert Greenwalt12e67352014-05-13 21:41:06 -07004660
Robert Greenwaltfc0c6892014-08-27 14:34:02 -07004661 private String notifyTypeToName(int notifyType) {
4662 switch (notifyType) {
4663 case ConnectivityManager.CALLBACK_PRECHECK: return "PRECHECK";
4664 case ConnectivityManager.CALLBACK_AVAILABLE: return "AVAILABLE";
4665 case ConnectivityManager.CALLBACK_LOSING: return "LOSING";
4666 case ConnectivityManager.CALLBACK_LOST: return "LOST";
4667 case ConnectivityManager.CALLBACK_UNAVAIL: return "UNAVAILABLE";
4668 case ConnectivityManager.CALLBACK_CAP_CHANGED: return "CAP_CHANGED";
4669 case ConnectivityManager.CALLBACK_IP_CHANGED: return "IP_CHANGED";
4670 case ConnectivityManager.CALLBACK_RELEASED: return "RELEASED";
4671 }
4672 return "UNKNOWN";
4673 }
4674
Jeff Sharkey69736342014-12-08 14:50:12 -08004675 /**
4676 * Notify other system services that set of active ifaces has changed.
4677 */
4678 private void notifyIfacesChanged() {
4679 try {
4680 mStatsService.forceUpdateIfaces();
4681 } catch (Exception ignored) {
4682 }
4683 }
4684
Sreeram Ramachandranf4e0c0c2014-07-27 14:18:26 -07004685 @Override
4686 public boolean addVpnAddress(String address, int prefixLength) {
4687 throwIfLockdownEnabled();
4688 int user = UserHandle.getUserId(Binder.getCallingUid());
4689 synchronized (mVpns) {
4690 return mVpns.get(user).addAddress(address, prefixLength);
4691 }
4692 }
4693
4694 @Override
4695 public boolean removeVpnAddress(String address, int prefixLength) {
4696 throwIfLockdownEnabled();
4697 int user = UserHandle.getUserId(Binder.getCallingUid());
4698 synchronized (mVpns) {
4699 return mVpns.get(user).removeAddress(address, prefixLength);
4700 }
4701 }
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004702
4703 @Override
4704 public boolean setUnderlyingNetworksForVpn(Network[] networks) {
4705 throwIfLockdownEnabled();
4706 int user = UserHandle.getUserId(Binder.getCallingUid());
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004707 boolean success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004708 synchronized (mVpns) {
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004709 success = mVpns.get(user).setUnderlyingNetworks(networks);
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004710 }
Wenchao Tongf5ea3402015-03-04 13:26:38 -08004711 if (success) {
4712 notifyIfacesChanged();
4713 }
4714 return success;
Sreeram Ramachandranc2c0bea2014-11-11 16:09:21 -08004715 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004716
4717 @Override
4718 public void factoryReset() {
4719 enforceConnectivityInternalPermission();
Stuart Scotte3e314d2015-04-20 14:07:45 -07004720
4721 if (mUserManager.hasUserRestriction(UserManager.DISALLOW_NETWORK_RESET)) {
4722 return;
4723 }
4724
Robin Lee3b3dd942015-05-12 18:14:58 +01004725 final int userId = UserHandle.getCallingUserId();
4726
Stuart Scottf1fb3972015-04-02 18:00:02 -07004727 // Turn airplane mode off
4728 setAirplaneMode(false);
4729
Stuart Scotte3e314d2015-04-20 14:07:45 -07004730 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_TETHERING)) {
4731 // Untether
4732 for (String tether : getTetheredIfaces()) {
4733 untether(tether);
4734 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004735 }
4736
Stuart Scotte3e314d2015-04-20 14:07:45 -07004737 if (!mUserManager.hasUserRestriction(UserManager.DISALLOW_CONFIG_VPN)) {
4738 // Turn VPN off
4739 VpnConfig vpnConfig = getVpnConfig(userId);
4740 if (vpnConfig != null) {
4741 if (vpnConfig.legacy) {
4742 prepareVpn(VpnConfig.LEGACY_VPN, VpnConfig.LEGACY_VPN, userId);
4743 } else {
4744 // Prevent this app (packagename = vpnConfig.user) from initiating VPN connections
4745 // in the future without user intervention.
4746 setVpnPackageAuthorization(vpnConfig.user, userId, false);
Stuart Scottf1fb3972015-04-02 18:00:02 -07004747
Stuart Scotte3e314d2015-04-20 14:07:45 -07004748 prepareVpn(vpnConfig.user, VpnConfig.LEGACY_VPN, userId);
4749 }
Stuart Scottf1fb3972015-04-02 18:00:02 -07004750 }
4751 }
4752 }
The Android Open Source Project9066cfe2009-03-03 19:31:44 -08004753}